index.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ZXing = {}));
  5. }(this, (function (exports) { 'use strict';
  6. function fixProto(target, prototype) {
  7. var setPrototypeOf = Object.setPrototypeOf;
  8. setPrototypeOf ? setPrototypeOf(target, prototype) : target.__proto__ = prototype;
  9. }
  10. function fixStack(target, fn) {
  11. if (fn === void 0) {
  12. fn = target.constructor;
  13. }
  14. var captureStackTrace = Error.captureStackTrace;
  15. captureStackTrace && captureStackTrace(target, fn);
  16. }
  17. var __extends = function () {
  18. var _extendStatics = function extendStatics(d, b) {
  19. _extendStatics = Object.setPrototypeOf || {
  20. __proto__: []
  21. } instanceof Array && function (d, b) {
  22. d.__proto__ = b;
  23. } || function (d, b) {
  24. for (var p in b) {
  25. if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
  26. }
  27. };
  28. return _extendStatics(d, b);
  29. };
  30. return function (d, b) {
  31. if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  32. _extendStatics(d, b);
  33. function __() {
  34. this.constructor = d;
  35. }
  36. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  37. };
  38. }();
  39. var CustomError = function (_super) {
  40. __extends(CustomError, _super);
  41. function CustomError(message, options) {
  42. var _newTarget = this.constructor;
  43. var _this = _super.call(this, message, options) || this;
  44. Object.defineProperty(_this, 'name', {
  45. value: _newTarget.name,
  46. enumerable: false,
  47. configurable: true
  48. });
  49. fixProto(_this, _newTarget.prototype);
  50. fixStack(_this);
  51. return _this;
  52. }
  53. return CustomError;
  54. }(Error);
  55. /**
  56. * Custom Error class of type Exception.
  57. */
  58. class Exception extends CustomError {
  59. /**
  60. * Allows Exception to be constructed directly
  61. * with some message and prototype definition.
  62. */
  63. constructor(message = undefined) {
  64. super(message);
  65. this.message = message;
  66. }
  67. getKind() {
  68. const ex = this.constructor;
  69. return ex.kind;
  70. }
  71. }
  72. /**
  73. * It's typed as string so it can be extended and overriden.
  74. */
  75. Exception.kind = 'Exception';
  76. /**
  77. * Custom Error class of type Exception.
  78. */
  79. class ArgumentException extends Exception {
  80. }
  81. ArgumentException.kind = 'ArgumentException';
  82. /**
  83. * Custom Error class of type Exception.
  84. */
  85. class IllegalArgumentException extends Exception {
  86. }
  87. IllegalArgumentException.kind = 'IllegalArgumentException';
  88. /*
  89. * Copyright 2009 ZXing authors
  90. *
  91. * Licensed under the Apache License, Version 2.0 (the "License");
  92. * you may not use this file except in compliance with the License.
  93. * You may obtain a copy of the License at
  94. *
  95. * http://www.apache.org/licenses/LICENSE-2.0
  96. *
  97. * Unless required by applicable law or agreed to in writing, software
  98. * distributed under the License is distributed on an "AS IS" BASIS,
  99. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  100. * See the License for the specific language governing permissions and
  101. * limitations under the License.
  102. */
  103. class BinaryBitmap {
  104. constructor(binarizer) {
  105. this.binarizer = binarizer;
  106. if (binarizer === null) {
  107. throw new IllegalArgumentException('Binarizer must be non-null.');
  108. }
  109. }
  110. /**
  111. * @return The width of the bitmap.
  112. */
  113. getWidth() {
  114. return this.binarizer.getWidth();
  115. }
  116. /**
  117. * @return The height of the bitmap.
  118. */
  119. getHeight() {
  120. return this.binarizer.getHeight();
  121. }
  122. /**
  123. * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
  124. * cached data. Callers should assume this method is expensive and call it as seldom as possible.
  125. * This method is intended for decoding 1D barcodes and may choose to apply sharpening.
  126. *
  127. * @param y The row to fetch, which must be in [0, bitmap height)
  128. * @param row An optional preallocated array. If null or too small, it will be ignored.
  129. * If used, the Binarizer will call BitArray.clear(). Always use the returned object.
  130. * @return The array of bits for this row (true means black).
  131. * @throws NotFoundException if row can't be binarized
  132. */
  133. getBlackRow(y /*int*/, row) {
  134. return this.binarizer.getBlackRow(y, row);
  135. }
  136. /**
  137. * Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive
  138. * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
  139. * may not apply sharpening. Therefore, a row from this matrix may not be identical to one
  140. * fetched using getBlackRow(), so don't mix and match between them.
  141. *
  142. * @return The 2D array of bits for the image (true means black).
  143. * @throws NotFoundException if image can't be binarized to make a matrix
  144. */
  145. getBlackMatrix() {
  146. // The matrix is created on demand the first time it is requested, then cached. There are two
  147. // reasons for this:
  148. // 1. This work will never be done if the caller only installs 1D Reader objects, or if a
  149. // 1D Reader finds a barcode before the 2D Readers run.
  150. // 2. This work will only be done once even if the caller installs multiple 2D Readers.
  151. if (this.matrix === null || this.matrix === undefined) {
  152. this.matrix = this.binarizer.getBlackMatrix();
  153. }
  154. return this.matrix;
  155. }
  156. /**
  157. * @return Whether this bitmap can be cropped.
  158. */
  159. isCropSupported() {
  160. return this.binarizer.getLuminanceSource().isCropSupported();
  161. }
  162. /**
  163. * Returns a new object with cropped image data. Implementations may keep a reference to the
  164. * original data rather than a copy. Only callable if isCropSupported() is true.
  165. *
  166. * @param left The left coordinate, which must be in [0,getWidth())
  167. * @param top The top coordinate, which must be in [0,getHeight())
  168. * @param width The width of the rectangle to crop.
  169. * @param height The height of the rectangle to crop.
  170. * @return A cropped version of this object.
  171. */
  172. crop(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
  173. const newSource = this.binarizer.getLuminanceSource().crop(left, top, width, height);
  174. return new BinaryBitmap(this.binarizer.createBinarizer(newSource));
  175. }
  176. /**
  177. * @return Whether this bitmap supports counter-clockwise rotation.
  178. */
  179. isRotateSupported() {
  180. return this.binarizer.getLuminanceSource().isRotateSupported();
  181. }
  182. /**
  183. * Returns a new object with rotated image data by 90 degrees counterclockwise.
  184. * Only callable if {@link #isRotateSupported()} is true.
  185. *
  186. * @return A rotated version of this object.
  187. */
  188. rotateCounterClockwise() {
  189. const newSource = this.binarizer.getLuminanceSource().rotateCounterClockwise();
  190. return new BinaryBitmap(this.binarizer.createBinarizer(newSource));
  191. }
  192. /**
  193. * Returns a new object with rotated image data by 45 degrees counterclockwise.
  194. * Only callable if {@link #isRotateSupported()} is true.
  195. *
  196. * @return A rotated version of this object.
  197. */
  198. rotateCounterClockwise45() {
  199. const newSource = this.binarizer.getLuminanceSource().rotateCounterClockwise45();
  200. return new BinaryBitmap(this.binarizer.createBinarizer(newSource));
  201. }
  202. /*@Override*/
  203. toString() {
  204. try {
  205. return this.getBlackMatrix().toString();
  206. }
  207. catch (e /*: NotFoundException*/) {
  208. return '';
  209. }
  210. }
  211. }
  212. /**
  213. * Custom Error class of type Exception.
  214. */
  215. class ChecksumException extends Exception {
  216. static getChecksumInstance() {
  217. return new ChecksumException();
  218. }
  219. }
  220. ChecksumException.kind = 'ChecksumException';
  221. /*
  222. * Copyright 2009 ZXing authors
  223. *
  224. * Licensed under the Apache License, Version 2.0 (the "License");
  225. * you may not use this file except in compliance with the License.
  226. * You may obtain a copy of the License at
  227. *
  228. * http://www.apache.org/licenses/LICENSE-2.0
  229. *
  230. * Unless required by applicable law or agreed to in writing, software
  231. * distributed under the License is distributed on an "AS IS" BASIS,
  232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  233. * See the License for the specific language governing permissions and
  234. * limitations under the License.
  235. */
  236. /**
  237. * This class hierarchy provides a set of methods to convert luminance data to 1 bit data.
  238. * It allows the algorithm to vary polymorphically, for example allowing a very expensive
  239. * thresholding technique for servers and a fast one for mobile. It also permits the implementation
  240. * to vary, e.g. a JNI version for Android and a Java fallback version for other platforms.
  241. *
  242. * @author dswitkin@google.com (Daniel Switkin)
  243. */
  244. class Binarizer {
  245. constructor(source) {
  246. this.source = source;
  247. }
  248. getLuminanceSource() {
  249. return this.source;
  250. }
  251. getWidth() {
  252. return this.source.getWidth();
  253. }
  254. getHeight() {
  255. return this.source.getHeight();
  256. }
  257. }
  258. class System {
  259. // public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
  260. /**
  261. * Makes a copy of a array.
  262. */
  263. static arraycopy(src, srcPos, dest, destPos, length) {
  264. // TODO: better use split or set?
  265. while (length--) {
  266. dest[destPos++] = src[srcPos++];
  267. }
  268. }
  269. /**
  270. * Returns the current time in milliseconds.
  271. */
  272. static currentTimeMillis() {
  273. return Date.now();
  274. }
  275. }
  276. /**
  277. * Custom Error class of type Exception.
  278. */
  279. class IndexOutOfBoundsException extends Exception {
  280. }
  281. IndexOutOfBoundsException.kind = 'IndexOutOfBoundsException';
  282. /**
  283. * Custom Error class of type Exception.
  284. */
  285. class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException {
  286. constructor(index = undefined, message = undefined) {
  287. super(message);
  288. this.index = index;
  289. this.message = message;
  290. }
  291. }
  292. ArrayIndexOutOfBoundsException.kind = 'ArrayIndexOutOfBoundsException';
  293. class Arrays {
  294. /**
  295. * Assigns the specified int value to each element of the specified array
  296. * of ints.
  297. *
  298. * @param a the array to be filled
  299. * @param val the value to be stored in all elements of the array
  300. */
  301. static fill(a, val) {
  302. for (let i = 0, len = a.length; i < len; i++)
  303. a[i] = val;
  304. }
  305. /**
  306. * Assigns the specified int value to each element of the specified
  307. * range of the specified array of ints. The range to be filled
  308. * extends from index {@code fromIndex}, inclusive, to index
  309. * {@code toIndex}, exclusive. (If {@code fromIndex==toIndex}, the
  310. * range to be filled is empty.)
  311. *
  312. * @param a the array to be filled
  313. * @param fromIndex the index of the first element (inclusive) to be
  314. * filled with the specified value
  315. * @param toIndex the index of the last element (exclusive) to be
  316. * filled with the specified value
  317. * @param val the value to be stored in all elements of the array
  318. * @throws IllegalArgumentException if {@code fromIndex > toIndex}
  319. * @throws ArrayIndexOutOfBoundsException if {@code fromIndex < 0} or
  320. * {@code toIndex > a.length}
  321. */
  322. static fillWithin(a, fromIndex, toIndex, val) {
  323. Arrays.rangeCheck(a.length, fromIndex, toIndex);
  324. for (let i = fromIndex; i < toIndex; i++)
  325. a[i] = val;
  326. }
  327. /**
  328. * Checks that {@code fromIndex} and {@code toIndex} are in
  329. * the range and throws an exception if they aren't.
  330. */
  331. static rangeCheck(arrayLength, fromIndex, toIndex) {
  332. if (fromIndex > toIndex) {
  333. throw new IllegalArgumentException('fromIndex(' + fromIndex + ') > toIndex(' + toIndex + ')');
  334. }
  335. if (fromIndex < 0) {
  336. throw new ArrayIndexOutOfBoundsException(fromIndex);
  337. }
  338. if (toIndex > arrayLength) {
  339. throw new ArrayIndexOutOfBoundsException(toIndex);
  340. }
  341. }
  342. static asList(...args) {
  343. return args;
  344. }
  345. static create(rows, cols, value) {
  346. let arr = Array.from({ length: rows });
  347. return arr.map(x => Array.from({ length: cols }).fill(value));
  348. }
  349. static createInt32Array(rows, cols, value) {
  350. let arr = Array.from({ length: rows });
  351. return arr.map(x => Int32Array.from({ length: cols }).fill(value));
  352. }
  353. static equals(first, second) {
  354. if (!first) {
  355. return false;
  356. }
  357. if (!second) {
  358. return false;
  359. }
  360. if (!first.length) {
  361. return false;
  362. }
  363. if (!second.length) {
  364. return false;
  365. }
  366. if (first.length !== second.length) {
  367. return false;
  368. }
  369. for (let i = 0, length = first.length; i < length; i++) {
  370. if (first[i] !== second[i]) {
  371. return false;
  372. }
  373. }
  374. return true;
  375. }
  376. static hashCode(a) {
  377. if (a === null) {
  378. return 0;
  379. }
  380. let result = 1;
  381. for (const element of a) {
  382. result = 31 * result + element;
  383. }
  384. return result;
  385. }
  386. static fillUint8Array(a, value) {
  387. for (let i = 0; i !== a.length; i++) {
  388. a[i] = value;
  389. }
  390. }
  391. static copyOf(original, newLength) {
  392. return original.slice(0, newLength);
  393. }
  394. static copyOfUint8Array(original, newLength) {
  395. if (original.length <= newLength) {
  396. const newArray = new Uint8Array(newLength);
  397. newArray.set(original);
  398. return newArray;
  399. }
  400. return original.slice(0, newLength);
  401. }
  402. static copyOfRange(original, from, to) {
  403. const newLength = to - from;
  404. const copy = new Int32Array(newLength);
  405. System.arraycopy(original, from, copy, 0, newLength);
  406. return copy;
  407. }
  408. /*
  409. * Returns the index of of the element in a sorted array or (-n-1) where n is the insertion point
  410. * for the new element.
  411. * Parameters:
  412. * ar - A sorted array
  413. * el - An element to search for
  414. * comparator - A comparator function. The function takes two arguments: (a, b) and returns:
  415. * a negative number if a is less than b;
  416. * 0 if a is equal to b;
  417. * a positive number of a is greater than b.
  418. * The array may contain duplicate elements. If there are more than one equal elements in the array,
  419. * the returned value can be the index of any one of the equal elements.
  420. *
  421. * http://jsfiddle.net/aryzhov/pkfst550/
  422. */
  423. static binarySearch(ar, el, comparator) {
  424. if (undefined === comparator) {
  425. comparator = Arrays.numberComparator;
  426. }
  427. let m = 0;
  428. let n = ar.length - 1;
  429. while (m <= n) {
  430. const k = (n + m) >> 1;
  431. const cmp = comparator(el, ar[k]);
  432. if (cmp > 0) {
  433. m = k + 1;
  434. }
  435. else if (cmp < 0) {
  436. n = k - 1;
  437. }
  438. else {
  439. return k;
  440. }
  441. }
  442. return -m - 1;
  443. }
  444. static numberComparator(a, b) {
  445. return a - b;
  446. }
  447. }
  448. /**
  449. * Ponyfill for Java's Integer class.
  450. */
  451. class Integer {
  452. static numberOfTrailingZeros(i) {
  453. let y;
  454. if (i === 0)
  455. return 32;
  456. let n = 31;
  457. y = i << 16;
  458. if (y !== 0) {
  459. n -= 16;
  460. i = y;
  461. }
  462. y = i << 8;
  463. if (y !== 0) {
  464. n -= 8;
  465. i = y;
  466. }
  467. y = i << 4;
  468. if (y !== 0) {
  469. n -= 4;
  470. i = y;
  471. }
  472. y = i << 2;
  473. if (y !== 0) {
  474. n -= 2;
  475. i = y;
  476. }
  477. return n - ((i << 1) >>> 31);
  478. }
  479. static numberOfLeadingZeros(i) {
  480. // HD, Figure 5-6
  481. if (i === 0) {
  482. return 32;
  483. }
  484. let n = 1;
  485. if (i >>> 16 === 0) {
  486. n += 16;
  487. i <<= 16;
  488. }
  489. if (i >>> 24 === 0) {
  490. n += 8;
  491. i <<= 8;
  492. }
  493. if (i >>> 28 === 0) {
  494. n += 4;
  495. i <<= 4;
  496. }
  497. if (i >>> 30 === 0) {
  498. n += 2;
  499. i <<= 2;
  500. }
  501. n -= i >>> 31;
  502. return n;
  503. }
  504. static toHexString(i) {
  505. return i.toString(16);
  506. }
  507. static toBinaryString(intNumber) {
  508. return String(parseInt(String(intNumber), 2));
  509. }
  510. // Returns the number of one-bits in the two's complement binary representation of the specified int value. This function is sometimes referred to as the population count.
  511. // Returns:
  512. // the number of one-bits in the two's complement binary representation of the specified int value.
  513. static bitCount(i) {
  514. // HD, Figure 5-2
  515. i = i - ((i >>> 1) & 0x55555555);
  516. i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
  517. i = (i + (i >>> 4)) & 0x0f0f0f0f;
  518. i = i + (i >>> 8);
  519. i = i + (i >>> 16);
  520. return i & 0x3f;
  521. }
  522. static truncDivision(dividend, divisor) {
  523. return Math.trunc(dividend / divisor);
  524. }
  525. /**
  526. * Converts A string to an integer.
  527. * @param s A string to convert into a number.
  528. * @param radix A value between 2 and 36 that specifies the base of the number in numString. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.
  529. */
  530. static parseInt(num, radix = undefined) {
  531. return parseInt(num, radix);
  532. }
  533. }
  534. Integer.MIN_VALUE_32_BITS = -2147483648;
  535. Integer.MAX_VALUE = Number.MAX_SAFE_INTEGER;
  536. /*
  537. * Copyright 2007 ZXing authors
  538. *
  539. * Licensed under the Apache License, Version 2.0 (the "License");
  540. * you may not use this file except in compliance with the License.
  541. * You may obtain a copy of the License at
  542. *
  543. * http://www.apache.org/licenses/LICENSE-2.0
  544. *
  545. * Unless required by applicable law or agreed to in writing, software
  546. * distributed under the License is distributed on an "AS IS" BASIS,
  547. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  548. * See the License for the specific language governing permissions and
  549. * limitations under the License.
  550. */
  551. /**
  552. * <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>
  553. *
  554. * @author Sean Owen
  555. */
  556. class BitArray /*implements Cloneable*/ {
  557. // public constructor() {
  558. // this.size = 0
  559. // this.bits = new Int32Array(1)
  560. // }
  561. // public constructor(size?: number /*int*/) {
  562. // if (undefined === size) {
  563. // this.size = 0
  564. // } else {
  565. // this.size = size
  566. // }
  567. // this.bits = this.makeArray(size)
  568. // }
  569. // For testing only
  570. constructor(size /*int*/, bits) {
  571. if (undefined === size) {
  572. this.size = 0;
  573. this.bits = new Int32Array(1);
  574. }
  575. else {
  576. this.size = size;
  577. if (undefined === bits || null === bits) {
  578. this.bits = BitArray.makeArray(size);
  579. }
  580. else {
  581. this.bits = bits;
  582. }
  583. }
  584. }
  585. getSize() {
  586. return this.size;
  587. }
  588. getSizeInBytes() {
  589. return Math.floor((this.size + 7) / 8);
  590. }
  591. ensureCapacity(size /*int*/) {
  592. if (size > this.bits.length * 32) {
  593. const newBits = BitArray.makeArray(size);
  594. System.arraycopy(this.bits, 0, newBits, 0, this.bits.length);
  595. this.bits = newBits;
  596. }
  597. }
  598. /**
  599. * @param i bit to get
  600. * @return true iff bit i is set
  601. */
  602. get(i /*int*/) {
  603. return (this.bits[Math.floor(i / 32)] & (1 << (i & 0x1F))) !== 0;
  604. }
  605. /**
  606. * Sets bit i.
  607. *
  608. * @param i bit to set
  609. */
  610. set(i /*int*/) {
  611. this.bits[Math.floor(i / 32)] |= 1 << (i & 0x1F);
  612. }
  613. /**
  614. * Flips bit i.
  615. *
  616. * @param i bit to set
  617. */
  618. flip(i /*int*/) {
  619. this.bits[Math.floor(i / 32)] ^= 1 << (i & 0x1F);
  620. }
  621. /**
  622. * @param from first bit to check
  623. * @return index of first bit that is set, starting from the given index, or size if none are set
  624. * at or beyond this given index
  625. * @see #getNextUnset(int)
  626. */
  627. getNextSet(from /*int*/) {
  628. const size = this.size;
  629. if (from >= size) {
  630. return size;
  631. }
  632. const bits = this.bits;
  633. let bitsOffset = Math.floor(from / 32);
  634. let currentBits = bits[bitsOffset];
  635. // mask off lesser bits first
  636. currentBits &= ~((1 << (from & 0x1F)) - 1);
  637. const length = bits.length;
  638. while (currentBits === 0) {
  639. if (++bitsOffset === length) {
  640. return size;
  641. }
  642. currentBits = bits[bitsOffset];
  643. }
  644. const result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits);
  645. return result > size ? size : result;
  646. }
  647. /**
  648. * @param from index to start looking for unset bit
  649. * @return index of next unset bit, or {@code size} if none are unset until the end
  650. * @see #getNextSet(int)
  651. */
  652. getNextUnset(from /*int*/) {
  653. const size = this.size;
  654. if (from >= size) {
  655. return size;
  656. }
  657. const bits = this.bits;
  658. let bitsOffset = Math.floor(from / 32);
  659. let currentBits = ~bits[bitsOffset];
  660. // mask off lesser bits first
  661. currentBits &= ~((1 << (from & 0x1F)) - 1);
  662. const length = bits.length;
  663. while (currentBits === 0) {
  664. if (++bitsOffset === length) {
  665. return size;
  666. }
  667. currentBits = ~bits[bitsOffset];
  668. }
  669. const result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits);
  670. return result > size ? size : result;
  671. }
  672. /**
  673. * Sets a block of 32 bits, starting at bit i.
  674. *
  675. * @param i first bit to set
  676. * @param newBits the new value of the next 32 bits. Note again that the least-significant bit
  677. * corresponds to bit i, the next-least-significant to i+1, and so on.
  678. */
  679. setBulk(i /*int*/, newBits /*int*/) {
  680. this.bits[Math.floor(i / 32)] = newBits;
  681. }
  682. /**
  683. * Sets a range of bits.
  684. *
  685. * @param start start of range, inclusive.
  686. * @param end end of range, exclusive
  687. */
  688. setRange(start /*int*/, end /*int*/) {
  689. if (end < start || start < 0 || end > this.size) {
  690. throw new IllegalArgumentException();
  691. }
  692. if (end === start) {
  693. return;
  694. }
  695. end--; // will be easier to treat this as the last actually set bit -- inclusive
  696. const firstInt = Math.floor(start / 32);
  697. const lastInt = Math.floor(end / 32);
  698. const bits = this.bits;
  699. for (let i = firstInt; i <= lastInt; i++) {
  700. const firstBit = i > firstInt ? 0 : start & 0x1F;
  701. const lastBit = i < lastInt ? 31 : end & 0x1F;
  702. // Ones from firstBit to lastBit, inclusive
  703. const mask = (2 << lastBit) - (1 << firstBit);
  704. bits[i] |= mask;
  705. }
  706. }
  707. /**
  708. * Clears all bits (sets to false).
  709. */
  710. clear() {
  711. const max = this.bits.length;
  712. const bits = this.bits;
  713. for (let i = 0; i < max; i++) {
  714. bits[i] = 0;
  715. }
  716. }
  717. /**
  718. * Efficient method to check if a range of bits is set, or not set.
  719. *
  720. * @param start start of range, inclusive.
  721. * @param end end of range, exclusive
  722. * @param value if true, checks that bits in range are set, otherwise checks that they are not set
  723. * @return true iff all bits are set or not set in range, according to value argument
  724. * @throws IllegalArgumentException if end is less than start or the range is not contained in the array
  725. */
  726. isRange(start /*int*/, end /*int*/, value) {
  727. if (end < start || start < 0 || end > this.size) {
  728. throw new IllegalArgumentException();
  729. }
  730. if (end === start) {
  731. return true; // empty range matches
  732. }
  733. end--; // will be easier to treat this as the last actually set bit -- inclusive
  734. const firstInt = Math.floor(start / 32);
  735. const lastInt = Math.floor(end / 32);
  736. const bits = this.bits;
  737. for (let i = firstInt; i <= lastInt; i++) {
  738. const firstBit = i > firstInt ? 0 : start & 0x1F;
  739. const lastBit = i < lastInt ? 31 : end & 0x1F;
  740. // Ones from firstBit to lastBit, inclusive
  741. const mask = (2 << lastBit) - (1 << firstBit) & 0xFFFFFFFF;
  742. // TYPESCRIPTPORT: & 0xFFFFFFFF added to discard anything after 32 bits, as ES has 53 bits
  743. // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (is: that,
  744. // equals the mask, or we're looking for 0s and the masked portion is not all 0s
  745. if ((bits[i] & mask) !== (value ? mask : 0)) {
  746. return false;
  747. }
  748. }
  749. return true;
  750. }
  751. appendBit(bit) {
  752. this.ensureCapacity(this.size + 1);
  753. if (bit) {
  754. this.bits[Math.floor(this.size / 32)] |= 1 << (this.size & 0x1F);
  755. }
  756. this.size++;
  757. }
  758. /**
  759. * Appends the least-significant bits, from value, in order from most-significant to
  760. * least-significant. For example, appending 6 bits from 0x000001E will append the bits
  761. * 0, 1, 1, 1, 1, 0 in that order.
  762. *
  763. * @param value {@code int} containing bits to append
  764. * @param numBits bits from value to append
  765. */
  766. appendBits(value /*int*/, numBits /*int*/) {
  767. if (numBits < 0 || numBits > 32) {
  768. throw new IllegalArgumentException('Num bits must be between 0 and 32');
  769. }
  770. this.ensureCapacity(this.size + numBits);
  771. // const appendBit = this.appendBit;
  772. for (let numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) {
  773. this.appendBit(((value >> (numBitsLeft - 1)) & 0x01) === 1);
  774. }
  775. }
  776. appendBitArray(other) {
  777. const otherSize = other.size;
  778. this.ensureCapacity(this.size + otherSize);
  779. // const appendBit = this.appendBit;
  780. for (let i = 0; i < otherSize; i++) {
  781. this.appendBit(other.get(i));
  782. }
  783. }
  784. xor(other) {
  785. if (this.size !== other.size) {
  786. throw new IllegalArgumentException('Sizes don\'t match');
  787. }
  788. const bits = this.bits;
  789. for (let i = 0, length = bits.length; i < length; i++) {
  790. // The last int could be incomplete (i.e. not have 32 bits in
  791. // it) but there is no problem since 0 XOR 0 == 0.
  792. bits[i] ^= other.bits[i];
  793. }
  794. }
  795. /**
  796. *
  797. * @param bitOffset first bit to start writing
  798. * @param array array to write into. Bytes are written most-significant byte first. This is the opposite
  799. * of the internal representation, which is exposed by {@link #getBitArray()}
  800. * @param offset position in array to start writing
  801. * @param numBytes how many bytes to write
  802. */
  803. toBytes(bitOffset /*int*/, array, offset /*int*/, numBytes /*int*/) {
  804. for (let i = 0; i < numBytes; i++) {
  805. let theByte = 0;
  806. for (let j = 0; j < 8; j++) {
  807. if (this.get(bitOffset)) {
  808. theByte |= 1 << (7 - j);
  809. }
  810. bitOffset++;
  811. }
  812. array[offset + i] = /*(byte)*/ theByte;
  813. }
  814. }
  815. /**
  816. * @return underlying array of ints. The first element holds the first 32 bits, and the least
  817. * significant bit is bit 0.
  818. */
  819. getBitArray() {
  820. return this.bits;
  821. }
  822. /**
  823. * Reverses all bits in the array.
  824. */
  825. reverse() {
  826. const newBits = new Int32Array(this.bits.length);
  827. // reverse all int's first
  828. const len = Math.floor((this.size - 1) / 32);
  829. const oldBitsLen = len + 1;
  830. const bits = this.bits;
  831. for (let i = 0; i < oldBitsLen; i++) {
  832. let x = bits[i];
  833. x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
  834. x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
  835. x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4);
  836. x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8);
  837. x = ((x >> 16) & 0x0000ffff) | ((x & 0x0000ffff) << 16);
  838. newBits[len - i] = /*(int)*/ x;
  839. }
  840. // now correct the int's if the bit size isn't a multiple of 32
  841. if (this.size !== oldBitsLen * 32) {
  842. const leftOffset = oldBitsLen * 32 - this.size;
  843. let currentInt = newBits[0] >>> leftOffset;
  844. for (let i = 1; i < oldBitsLen; i++) {
  845. const nextInt = newBits[i];
  846. currentInt |= nextInt << (32 - leftOffset);
  847. newBits[i - 1] = currentInt;
  848. currentInt = nextInt >>> leftOffset;
  849. }
  850. newBits[oldBitsLen - 1] = currentInt;
  851. }
  852. this.bits = newBits;
  853. }
  854. static makeArray(size /*int*/) {
  855. return new Int32Array(Math.floor((size + 31) / 32));
  856. }
  857. /*@Override*/
  858. equals(o) {
  859. if (!(o instanceof BitArray)) {
  860. return false;
  861. }
  862. const other = o;
  863. return this.size === other.size && Arrays.equals(this.bits, other.bits);
  864. }
  865. /*@Override*/
  866. hashCode() {
  867. return 31 * this.size + Arrays.hashCode(this.bits);
  868. }
  869. /*@Override*/
  870. toString() {
  871. let result = '';
  872. for (let i = 0, size = this.size; i < size; i++) {
  873. if ((i & 0x07) === 0) {
  874. result += ' ';
  875. }
  876. result += this.get(i) ? 'X' : '.';
  877. }
  878. return result;
  879. }
  880. /*@Override*/
  881. clone() {
  882. return new BitArray(this.size, this.bits.slice());
  883. }
  884. /**
  885. * converts to boolean array.
  886. */
  887. toArray() {
  888. let result = [];
  889. for (let i = 0, size = this.size; i < size; i++) {
  890. result.push(this.get(i));
  891. }
  892. return result;
  893. }
  894. }
  895. /*
  896. * Copyright 2009 ZXing authors
  897. *
  898. * Licensed under the Apache License, Version 2.0 (the "License");
  899. * you may not use this file except in compliance with the License.
  900. * You may obtain a copy of the License at
  901. *
  902. * http://www.apache.org/licenses/LICENSE-2.0
  903. *
  904. * Unless required by applicable law or agreed to in writing, software
  905. * distributed under the License is distributed on an "AS IS" BASIS,
  906. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  907. * See the License for the specific language governing permissions and
  908. * limitations under the License.
  909. */
  910. /*namespace com.google.zxing {*/
  911. /**
  912. * Encapsulates a type of hint that a caller may pass to a barcode reader to help it
  913. * more quickly or accurately decode it. It is up to implementations to decide what,
  914. * if anything, to do with the information that is supplied.
  915. *
  916. * @author Sean Owen
  917. * @author dswitkin@google.com (Daniel Switkin)
  918. * @see Reader#decode(BinaryBitmap,java.util.Map)
  919. */
  920. var DecodeHintType;
  921. (function (DecodeHintType) {
  922. /**
  923. * Unspecified, application-specific hint. Maps to an unspecified {@link Object}.
  924. */
  925. DecodeHintType[DecodeHintType["OTHER"] = 0] = "OTHER"; /*(Object.class)*/
  926. /**
  927. * Image is a pure monochrome image of a barcode. Doesn't matter what it maps to;
  928. * use {@link Boolean#TRUE}.
  929. */
  930. DecodeHintType[DecodeHintType["PURE_BARCODE"] = 1] = "PURE_BARCODE"; /*(Void.class)*/
  931. /**
  932. * Image is known to be of one of a few possible formats.
  933. * Maps to a {@link List} of {@link BarcodeFormat}s.
  934. */
  935. DecodeHintType[DecodeHintType["POSSIBLE_FORMATS"] = 2] = "POSSIBLE_FORMATS"; /*(List.class)*/
  936. /**
  937. * Spend more time to try to find a barcode; optimize for accuracy, not speed.
  938. * Doesn't matter what it maps to; use {@link Boolean#TRUE}.
  939. */
  940. DecodeHintType[DecodeHintType["TRY_HARDER"] = 3] = "TRY_HARDER"; /*(Void.class)*/
  941. /**
  942. * Specifies what character encoding to use when decoding, where applicable (type String)
  943. */
  944. DecodeHintType[DecodeHintType["CHARACTER_SET"] = 4] = "CHARACTER_SET"; /*(String.class)*/
  945. /**
  946. * Allowed lengths of encoded data -- reject anything else. Maps to an {@code Int32Array}.
  947. */
  948. DecodeHintType[DecodeHintType["ALLOWED_LENGTHS"] = 5] = "ALLOWED_LENGTHS"; /*(Int32Array.class)*/
  949. /**
  950. * Assume Code 39 codes employ a check digit. Doesn't matter what it maps to;
  951. * use {@link Boolean#TRUE}.
  952. */
  953. DecodeHintType[DecodeHintType["ASSUME_CODE_39_CHECK_DIGIT"] = 6] = "ASSUME_CODE_39_CHECK_DIGIT"; /*(Void.class)*/
  954. /**
  955. * Assume the barcode is being processed as a GS1 barcode, and modify behavior as needed.
  956. * For example this affects FNC1 handling for Code 128 (aka GS1-128). Doesn't matter what it maps to;
  957. * use {@link Boolean#TRUE}.
  958. */
  959. DecodeHintType[DecodeHintType["ASSUME_GS1"] = 7] = "ASSUME_GS1"; /*(Void.class)*/
  960. /**
  961. * If true, return the start and end digits in a Codabar barcode instead of stripping them. They
  962. * are alpha, whereas the rest are numeric. By default, they are stripped, but this causes them
  963. * to not be. Doesn't matter what it maps to; use {@link Boolean#TRUE}.
  964. */
  965. DecodeHintType[DecodeHintType["RETURN_CODABAR_START_END"] = 8] = "RETURN_CODABAR_START_END"; /*(Void.class)*/
  966. /**
  967. * The caller needs to be notified via callback when a possible {@link ResultPoint}
  968. * is found. Maps to a {@link ResultPointCallback}.
  969. */
  970. DecodeHintType[DecodeHintType["NEED_RESULT_POINT_CALLBACK"] = 9] = "NEED_RESULT_POINT_CALLBACK"; /*(ResultPointCallback.class)*/
  971. /**
  972. * Allowed extension lengths for EAN or UPC barcodes. Other formats will ignore this.
  973. * Maps to an {@code Int32Array} of the allowed extension lengths, for example [2], [5], or [2, 5].
  974. * If it is optional to have an extension, do not set this hint. If this is set,
  975. * and a UPC or EAN barcode is found but an extension is not, then no result will be returned
  976. * at all.
  977. */
  978. DecodeHintType[DecodeHintType["ALLOWED_EAN_EXTENSIONS"] = 10] = "ALLOWED_EAN_EXTENSIONS"; /*(Int32Array.class)*/
  979. // End of enumeration values.
  980. /**
  981. * Data type the hint is expecting.
  982. * Among the possible values the {@link Void} stands out as being used for
  983. * hints that do not expect a value to be supplied (flag hints). Such hints
  984. * will possibly have their value ignored, or replaced by a
  985. * {@link Boolean#TRUE}. Hint suppliers should probably use
  986. * {@link Boolean#TRUE} as directed by the actual hint documentation.
  987. */
  988. // private valueType: Class<?>
  989. // DecodeHintType(valueType: Class<?>) {
  990. // this.valueType = valueType
  991. // }
  992. // public getValueType(): Class<?> {
  993. // return valueType
  994. // }
  995. })(DecodeHintType || (DecodeHintType = {}));
  996. var DecodeHintType$1 = DecodeHintType;
  997. /**
  998. * Custom Error class of type Exception.
  999. */
  1000. class FormatException extends Exception {
  1001. static getFormatInstance() {
  1002. return new FormatException();
  1003. }
  1004. }
  1005. FormatException.kind = 'FormatException';
  1006. /*
  1007. * Copyright 2008 ZXing authors
  1008. *
  1009. * Licensed under the Apache License, Version 2.0 (the "License");
  1010. * you may not use this file except in compliance with the License.
  1011. * You may obtain a copy of the License at
  1012. *
  1013. * http://www.apache.org/licenses/LICENSE-2.0
  1014. *
  1015. * Unless required by applicable law or agreed to in writing, software
  1016. * distributed under the License is distributed on an "AS IS" BASIS,
  1017. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1018. * See the License for the specific language governing permissions and
  1019. * limitations under the License.
  1020. */
  1021. /*import java.util.HashMap;*/
  1022. /*import java.util.Map;*/
  1023. var CharacterSetValueIdentifiers;
  1024. (function (CharacterSetValueIdentifiers) {
  1025. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp437"] = 0] = "Cp437";
  1026. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_1"] = 1] = "ISO8859_1";
  1027. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_2"] = 2] = "ISO8859_2";
  1028. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_3"] = 3] = "ISO8859_3";
  1029. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_4"] = 4] = "ISO8859_4";
  1030. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_5"] = 5] = "ISO8859_5";
  1031. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_6"] = 6] = "ISO8859_6";
  1032. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_7"] = 7] = "ISO8859_7";
  1033. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_8"] = 8] = "ISO8859_8";
  1034. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_9"] = 9] = "ISO8859_9";
  1035. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_10"] = 10] = "ISO8859_10";
  1036. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_11"] = 11] = "ISO8859_11";
  1037. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_13"] = 12] = "ISO8859_13";
  1038. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_14"] = 13] = "ISO8859_14";
  1039. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_15"] = 14] = "ISO8859_15";
  1040. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_16"] = 15] = "ISO8859_16";
  1041. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["SJIS"] = 16] = "SJIS";
  1042. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1250"] = 17] = "Cp1250";
  1043. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1251"] = 18] = "Cp1251";
  1044. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1252"] = 19] = "Cp1252";
  1045. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1256"] = 20] = "Cp1256";
  1046. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["UnicodeBigUnmarked"] = 21] = "UnicodeBigUnmarked";
  1047. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["UTF8"] = 22] = "UTF8";
  1048. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ASCII"] = 23] = "ASCII";
  1049. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Big5"] = 24] = "Big5";
  1050. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["GB18030"] = 25] = "GB18030";
  1051. CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["EUC_KR"] = 26] = "EUC_KR";
  1052. })(CharacterSetValueIdentifiers || (CharacterSetValueIdentifiers = {}));
  1053. /**
  1054. * Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1
  1055. * of ISO 18004.
  1056. *
  1057. * @author Sean Owen
  1058. */
  1059. class CharacterSetECI {
  1060. constructor(valueIdentifier, valuesParam, name, ...otherEncodingNames) {
  1061. this.valueIdentifier = valueIdentifier;
  1062. this.name = name;
  1063. if (typeof valuesParam === 'number') {
  1064. this.values = Int32Array.from([valuesParam]);
  1065. }
  1066. else {
  1067. this.values = valuesParam;
  1068. }
  1069. this.otherEncodingNames = otherEncodingNames;
  1070. CharacterSetECI.VALUE_IDENTIFIER_TO_ECI.set(valueIdentifier, this);
  1071. CharacterSetECI.NAME_TO_ECI.set(name, this);
  1072. const values = this.values;
  1073. for (let i = 0, length = values.length; i !== length; i++) {
  1074. const v = values[i];
  1075. CharacterSetECI.VALUES_TO_ECI.set(v, this);
  1076. }
  1077. for (const otherName of otherEncodingNames) {
  1078. CharacterSetECI.NAME_TO_ECI.set(otherName, this);
  1079. }
  1080. }
  1081. // CharacterSetECI(value: number /*int*/) {
  1082. // this(new Int32Array {value})
  1083. // }
  1084. // CharacterSetECI(value: number /*int*/, String... otherEncodingNames) {
  1085. // this.values = new Int32Array {value}
  1086. // this.otherEncodingNames = otherEncodingNames
  1087. // }
  1088. // CharacterSetECI(values: Int32Array, String... otherEncodingNames) {
  1089. // this.values = values
  1090. // this.otherEncodingNames = otherEncodingNames
  1091. // }
  1092. getValueIdentifier() {
  1093. return this.valueIdentifier;
  1094. }
  1095. getName() {
  1096. return this.name;
  1097. }
  1098. getValue() {
  1099. return this.values[0];
  1100. }
  1101. /**
  1102. * @param value character set ECI value
  1103. * @return {@code CharacterSetECI} representing ECI of given value, or null if it is legal but
  1104. * unsupported
  1105. * @throws FormatException if ECI value is invalid
  1106. */
  1107. static getCharacterSetECIByValue(value /*int*/) {
  1108. if (value < 0 || value >= 900) {
  1109. throw new FormatException('incorect value');
  1110. }
  1111. const characterSet = CharacterSetECI.VALUES_TO_ECI.get(value);
  1112. if (undefined === characterSet) {
  1113. throw new FormatException('incorect value');
  1114. }
  1115. return characterSet;
  1116. }
  1117. /**
  1118. * @param name character set ECI encoding name
  1119. * @return CharacterSetECI representing ECI for character encoding, or null if it is legal
  1120. * but unsupported
  1121. */
  1122. static getCharacterSetECIByName(name) {
  1123. const characterSet = CharacterSetECI.NAME_TO_ECI.get(name);
  1124. if (undefined === characterSet) {
  1125. throw new FormatException('incorect value');
  1126. }
  1127. return characterSet;
  1128. }
  1129. equals(o) {
  1130. if (!(o instanceof CharacterSetECI)) {
  1131. return false;
  1132. }
  1133. const other = o;
  1134. return this.getName() === other.getName();
  1135. }
  1136. }
  1137. CharacterSetECI.VALUE_IDENTIFIER_TO_ECI = new Map();
  1138. CharacterSetECI.VALUES_TO_ECI = new Map();
  1139. CharacterSetECI.NAME_TO_ECI = new Map();
  1140. // Enum name is a Java encoding valid for java.lang and java.io
  1141. // TYPESCRIPTPORT: changed the main label for ISO as the TextEncoder did not recognized them in the form from java
  1142. // (eg ISO8859_1 must be ISO88591 or ISO8859-1 or ISO-8859-1)
  1143. // later on: well, except 16 wich does not work with ISO885916 so used ISO-8859-1 form for default
  1144. CharacterSetECI.Cp437 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp437, Int32Array.from([0, 2]), 'Cp437');
  1145. CharacterSetECI.ISO8859_1 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_1, Int32Array.from([1, 3]), 'ISO-8859-1', 'ISO88591', 'ISO8859_1');
  1146. CharacterSetECI.ISO8859_2 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_2, 4, 'ISO-8859-2', 'ISO88592', 'ISO8859_2');
  1147. CharacterSetECI.ISO8859_3 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_3, 5, 'ISO-8859-3', 'ISO88593', 'ISO8859_3');
  1148. CharacterSetECI.ISO8859_4 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_4, 6, 'ISO-8859-4', 'ISO88594', 'ISO8859_4');
  1149. CharacterSetECI.ISO8859_5 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_5, 7, 'ISO-8859-5', 'ISO88595', 'ISO8859_5');
  1150. CharacterSetECI.ISO8859_6 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_6, 8, 'ISO-8859-6', 'ISO88596', 'ISO8859_6');
  1151. CharacterSetECI.ISO8859_7 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_7, 9, 'ISO-8859-7', 'ISO88597', 'ISO8859_7');
  1152. CharacterSetECI.ISO8859_8 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_8, 10, 'ISO-8859-8', 'ISO88598', 'ISO8859_8');
  1153. CharacterSetECI.ISO8859_9 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_9, 11, 'ISO-8859-9', 'ISO88599', 'ISO8859_9');
  1154. CharacterSetECI.ISO8859_10 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_10, 12, 'ISO-8859-10', 'ISO885910', 'ISO8859_10');
  1155. CharacterSetECI.ISO8859_11 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_11, 13, 'ISO-8859-11', 'ISO885911', 'ISO8859_11');
  1156. CharacterSetECI.ISO8859_13 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_13, 15, 'ISO-8859-13', 'ISO885913', 'ISO8859_13');
  1157. CharacterSetECI.ISO8859_14 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_14, 16, 'ISO-8859-14', 'ISO885914', 'ISO8859_14');
  1158. CharacterSetECI.ISO8859_15 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_15, 17, 'ISO-8859-15', 'ISO885915', 'ISO8859_15');
  1159. CharacterSetECI.ISO8859_16 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_16, 18, 'ISO-8859-16', 'ISO885916', 'ISO8859_16');
  1160. CharacterSetECI.SJIS = new CharacterSetECI(CharacterSetValueIdentifiers.SJIS, 20, 'SJIS', 'Shift_JIS');
  1161. CharacterSetECI.Cp1250 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1250, 21, 'Cp1250', 'windows-1250');
  1162. CharacterSetECI.Cp1251 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1251, 22, 'Cp1251', 'windows-1251');
  1163. CharacterSetECI.Cp1252 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1252, 23, 'Cp1252', 'windows-1252');
  1164. CharacterSetECI.Cp1256 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1256, 24, 'Cp1256', 'windows-1256');
  1165. CharacterSetECI.UnicodeBigUnmarked = new CharacterSetECI(CharacterSetValueIdentifiers.UnicodeBigUnmarked, 25, 'UnicodeBigUnmarked', 'UTF-16BE', 'UnicodeBig');
  1166. CharacterSetECI.UTF8 = new CharacterSetECI(CharacterSetValueIdentifiers.UTF8, 26, 'UTF8', 'UTF-8');
  1167. CharacterSetECI.ASCII = new CharacterSetECI(CharacterSetValueIdentifiers.ASCII, Int32Array.from([27, 170]), 'ASCII', 'US-ASCII');
  1168. CharacterSetECI.Big5 = new CharacterSetECI(CharacterSetValueIdentifiers.Big5, 28, 'Big5');
  1169. CharacterSetECI.GB18030 = new CharacterSetECI(CharacterSetValueIdentifiers.GB18030, 29, 'GB18030', 'GB2312', 'EUC_CN', 'GBK');
  1170. CharacterSetECI.EUC_KR = new CharacterSetECI(CharacterSetValueIdentifiers.EUC_KR, 30, 'EUC_KR', 'EUC-KR');
  1171. /**
  1172. * Custom Error class of type Exception.
  1173. */
  1174. class UnsupportedOperationException extends Exception {
  1175. }
  1176. UnsupportedOperationException.kind = 'UnsupportedOperationException';
  1177. /**
  1178. * Responsible for en/decoding strings.
  1179. */
  1180. class StringEncoding {
  1181. /**
  1182. * Decodes some Uint8Array to a string format.
  1183. */
  1184. static decode(bytes, encoding) {
  1185. const encodingName = this.encodingName(encoding);
  1186. if (this.customDecoder) {
  1187. return this.customDecoder(bytes, encodingName);
  1188. }
  1189. // Increases browser support.
  1190. if (typeof TextDecoder === 'undefined' || this.shouldDecodeOnFallback(encodingName)) {
  1191. return this.decodeFallback(bytes, encodingName);
  1192. }
  1193. return new TextDecoder(encodingName).decode(bytes);
  1194. }
  1195. /**
  1196. * Checks if the decoding method should use the fallback for decoding
  1197. * once Node TextDecoder doesn't support all encoding formats.
  1198. *
  1199. * @param encodingName
  1200. */
  1201. static shouldDecodeOnFallback(encodingName) {
  1202. return !StringEncoding.isBrowser() && encodingName === 'ISO-8859-1';
  1203. }
  1204. /**
  1205. * Encodes some string into a Uint8Array.
  1206. */
  1207. static encode(s, encoding) {
  1208. const encodingName = this.encodingName(encoding);
  1209. if (this.customEncoder) {
  1210. return this.customEncoder(s, encodingName);
  1211. }
  1212. // Increases browser support.
  1213. if (typeof TextEncoder === 'undefined') {
  1214. return this.encodeFallback(s);
  1215. }
  1216. // TextEncoder only encodes to UTF8 by default as specified by encoding.spec.whatwg.org
  1217. return new TextEncoder().encode(s);
  1218. }
  1219. static isBrowser() {
  1220. return (typeof window !== 'undefined' && {}.toString.call(window) === '[object Window]');
  1221. }
  1222. /**
  1223. * Returns the string value from some encoding character set.
  1224. */
  1225. static encodingName(encoding) {
  1226. return typeof encoding === 'string'
  1227. ? encoding
  1228. : encoding.getName();
  1229. }
  1230. /**
  1231. * Returns character set from some encoding character set.
  1232. */
  1233. static encodingCharacterSet(encoding) {
  1234. if (encoding instanceof CharacterSetECI) {
  1235. return encoding;
  1236. }
  1237. return CharacterSetECI.getCharacterSetECIByName(encoding);
  1238. }
  1239. /**
  1240. * Runs a fallback for the native decoding funcion.
  1241. */
  1242. static decodeFallback(bytes, encoding) {
  1243. const characterSet = this.encodingCharacterSet(encoding);
  1244. if (StringEncoding.isDecodeFallbackSupported(characterSet)) {
  1245. let s = '';
  1246. for (let i = 0, length = bytes.length; i < length; i++) {
  1247. let h = bytes[i].toString(16);
  1248. if (h.length < 2) {
  1249. h = '0' + h;
  1250. }
  1251. s += '%' + h;
  1252. }
  1253. return decodeURIComponent(s);
  1254. }
  1255. if (characterSet.equals(CharacterSetECI.UnicodeBigUnmarked)) {
  1256. return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));
  1257. }
  1258. throw new UnsupportedOperationException(`Encoding ${this.encodingName(encoding)} not supported by fallback.`);
  1259. }
  1260. static isDecodeFallbackSupported(characterSet) {
  1261. return characterSet.equals(CharacterSetECI.UTF8) ||
  1262. characterSet.equals(CharacterSetECI.ISO8859_1) ||
  1263. characterSet.equals(CharacterSetECI.ASCII);
  1264. }
  1265. /**
  1266. * Runs a fallback for the native encoding funcion.
  1267. *
  1268. * @see https://stackoverflow.com/a/17192845/4367683
  1269. */
  1270. static encodeFallback(s) {
  1271. const encodedURIstring = btoa(unescape(encodeURIComponent(s)));
  1272. const charList = encodedURIstring.split('');
  1273. const uintArray = [];
  1274. for (let i = 0; i < charList.length; i++) {
  1275. uintArray.push(charList[i].charCodeAt(0));
  1276. }
  1277. return new Uint8Array(uintArray);
  1278. }
  1279. }
  1280. /*
  1281. * Copyright (C) 2010 ZXing authors
  1282. *
  1283. * Licensed under the Apache License, Version 2.0 (the "License");
  1284. * you may not use this file except in compliance with the License.
  1285. * You may obtain a copy of the License at
  1286. *
  1287. * http://www.apache.org/licenses/LICENSE-2.0
  1288. *
  1289. * Unless required by applicable law or agreed to in writing, software
  1290. * distributed under the License is distributed on an "AS IS" BASIS,
  1291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1292. * See the License for the specific language governing permissions and
  1293. * limitations under the License.
  1294. */
  1295. /**
  1296. * Common string-related functions.
  1297. *
  1298. * @author Sean Owen
  1299. * @author Alex Dupre
  1300. */
  1301. class StringUtils {
  1302. // SHIFT_JIS.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING) ||
  1303. // EUC_JP.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING);
  1304. static castAsNonUtf8Char(code, encoding = null) {
  1305. // ISO 8859-1 is the Java default as UTF-8 is JavaScripts
  1306. // you can see this method as a Java version of String.fromCharCode
  1307. const e = encoding ? encoding.getName() : this.ISO88591;
  1308. // use passed format (fromCharCode will return UTF8 encoding)
  1309. return StringEncoding.decode(new Uint8Array([code]), e);
  1310. }
  1311. /**
  1312. * @param bytes bytes encoding a string, whose encoding should be guessed
  1313. * @param hints decode hints if applicable
  1314. * @return name of guessed encoding; at the moment will only guess one of:
  1315. * {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform
  1316. * default encoding if none of these can possibly be correct
  1317. */
  1318. static guessEncoding(bytes, hints) {
  1319. if (hints !== null && hints !== undefined && undefined !== hints.get(DecodeHintType$1.CHARACTER_SET)) {
  1320. return hints.get(DecodeHintType$1.CHARACTER_SET).toString();
  1321. }
  1322. // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
  1323. // which should be by far the most common encodings.
  1324. const length = bytes.length;
  1325. let canBeISO88591 = true;
  1326. let canBeShiftJIS = true;
  1327. let canBeUTF8 = true;
  1328. let utf8BytesLeft = 0;
  1329. // int utf8LowChars = 0
  1330. let utf2BytesChars = 0;
  1331. let utf3BytesChars = 0;
  1332. let utf4BytesChars = 0;
  1333. let sjisBytesLeft = 0;
  1334. // int sjisLowChars = 0
  1335. let sjisKatakanaChars = 0;
  1336. // int sjisDoubleBytesChars = 0
  1337. let sjisCurKatakanaWordLength = 0;
  1338. let sjisCurDoubleBytesWordLength = 0;
  1339. let sjisMaxKatakanaWordLength = 0;
  1340. let sjisMaxDoubleBytesWordLength = 0;
  1341. // int isoLowChars = 0
  1342. // int isoHighChars = 0
  1343. let isoHighOther = 0;
  1344. const utf8bom = bytes.length > 3 &&
  1345. bytes[0] === /*(byte) */ 0xEF &&
  1346. bytes[1] === /*(byte) */ 0xBB &&
  1347. bytes[2] === /*(byte) */ 0xBF;
  1348. for (let i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); i++) {
  1349. const value = bytes[i] & 0xFF;
  1350. // UTF-8 stuff
  1351. if (canBeUTF8) {
  1352. if (utf8BytesLeft > 0) {
  1353. if ((value & 0x80) === 0) {
  1354. canBeUTF8 = false;
  1355. }
  1356. else {
  1357. utf8BytesLeft--;
  1358. }
  1359. }
  1360. else if ((value & 0x80) !== 0) {
  1361. if ((value & 0x40) === 0) {
  1362. canBeUTF8 = false;
  1363. }
  1364. else {
  1365. utf8BytesLeft++;
  1366. if ((value & 0x20) === 0) {
  1367. utf2BytesChars++;
  1368. }
  1369. else {
  1370. utf8BytesLeft++;
  1371. if ((value & 0x10) === 0) {
  1372. utf3BytesChars++;
  1373. }
  1374. else {
  1375. utf8BytesLeft++;
  1376. if ((value & 0x08) === 0) {
  1377. utf4BytesChars++;
  1378. }
  1379. else {
  1380. canBeUTF8 = false;
  1381. }
  1382. }
  1383. }
  1384. }
  1385. } // else {
  1386. // utf8LowChars++
  1387. // }
  1388. }
  1389. // ISO-8859-1 stuff
  1390. if (canBeISO88591) {
  1391. if (value > 0x7F && value < 0xA0) {
  1392. canBeISO88591 = false;
  1393. }
  1394. else if (value > 0x9F) {
  1395. if (value < 0xC0 || value === 0xD7 || value === 0xF7) {
  1396. isoHighOther++;
  1397. } // else {
  1398. // isoHighChars++
  1399. // }
  1400. } // else {
  1401. // isoLowChars++
  1402. // }
  1403. }
  1404. // Shift_JIS stuff
  1405. if (canBeShiftJIS) {
  1406. if (sjisBytesLeft > 0) {
  1407. if (value < 0x40 || value === 0x7F || value > 0xFC) {
  1408. canBeShiftJIS = false;
  1409. }
  1410. else {
  1411. sjisBytesLeft--;
  1412. }
  1413. }
  1414. else if (value === 0x80 || value === 0xA0 || value > 0xEF) {
  1415. canBeShiftJIS = false;
  1416. }
  1417. else if (value > 0xA0 && value < 0xE0) {
  1418. sjisKatakanaChars++;
  1419. sjisCurDoubleBytesWordLength = 0;
  1420. sjisCurKatakanaWordLength++;
  1421. if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) {
  1422. sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength;
  1423. }
  1424. }
  1425. else if (value > 0x7F) {
  1426. sjisBytesLeft++;
  1427. // sjisDoubleBytesChars++
  1428. sjisCurKatakanaWordLength = 0;
  1429. sjisCurDoubleBytesWordLength++;
  1430. if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) {
  1431. sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength;
  1432. }
  1433. }
  1434. else {
  1435. // sjisLowChars++
  1436. sjisCurKatakanaWordLength = 0;
  1437. sjisCurDoubleBytesWordLength = 0;
  1438. }
  1439. }
  1440. }
  1441. if (canBeUTF8 && utf8BytesLeft > 0) {
  1442. canBeUTF8 = false;
  1443. }
  1444. if (canBeShiftJIS && sjisBytesLeft > 0) {
  1445. canBeShiftJIS = false;
  1446. }
  1447. // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done
  1448. if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) {
  1449. return StringUtils.UTF8;
  1450. }
  1451. // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done
  1452. if (canBeShiftJIS && (StringUtils.ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) {
  1453. return StringUtils.SHIFT_JIS;
  1454. }
  1455. // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is:
  1456. // - If we saw
  1457. // - only two consecutive katakana chars in the whole text, or
  1458. // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1,
  1459. // - then we conclude Shift_JIS, else ISO-8859-1
  1460. if (canBeISO88591 && canBeShiftJIS) {
  1461. return (sjisMaxKatakanaWordLength === 2 && sjisKatakanaChars === 2) || isoHighOther * 10 >= length
  1462. ? StringUtils.SHIFT_JIS : StringUtils.ISO88591;
  1463. }
  1464. // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding
  1465. if (canBeISO88591) {
  1466. return StringUtils.ISO88591;
  1467. }
  1468. if (canBeShiftJIS) {
  1469. return StringUtils.SHIFT_JIS;
  1470. }
  1471. if (canBeUTF8) {
  1472. return StringUtils.UTF8;
  1473. }
  1474. // Otherwise, we take a wild guess with platform encoding
  1475. return StringUtils.PLATFORM_DEFAULT_ENCODING;
  1476. }
  1477. /**
  1478. *
  1479. * @see https://stackoverflow.com/a/13439711/4367683
  1480. *
  1481. * @param append The new string to append.
  1482. * @param args Argumets values to be formated.
  1483. */
  1484. static format(append, ...args) {
  1485. let i = -1;
  1486. function callback(exp, p0, p1, p2, p3, p4) {
  1487. if (exp === '%%')
  1488. return '%';
  1489. if (args[++i] === undefined)
  1490. return undefined;
  1491. exp = p2 ? parseInt(p2.substr(1)) : undefined;
  1492. let base = p3 ? parseInt(p3.substr(1)) : undefined;
  1493. let val;
  1494. switch (p4) {
  1495. case 's':
  1496. val = args[i];
  1497. break;
  1498. case 'c':
  1499. val = args[i][0];
  1500. break;
  1501. case 'f':
  1502. val = parseFloat(args[i]).toFixed(exp);
  1503. break;
  1504. case 'p':
  1505. val = parseFloat(args[i]).toPrecision(exp);
  1506. break;
  1507. case 'e':
  1508. val = parseFloat(args[i]).toExponential(exp);
  1509. break;
  1510. case 'x':
  1511. val = parseInt(args[i]).toString(base ? base : 16);
  1512. break;
  1513. case 'd':
  1514. val = parseFloat(parseInt(args[i], base ? base : 10).toPrecision(exp)).toFixed(0);
  1515. break;
  1516. }
  1517. val = typeof val === 'object' ? JSON.stringify(val) : (+val).toString(base);
  1518. let size = parseInt(p1); /* padding size */
  1519. let ch = p1 && (p1[0] + '') === '0' ? '0' : ' '; /* isnull? */
  1520. while (val.length < size)
  1521. val = p0 !== undefined ? val + ch : ch + val; /* isminus? */
  1522. return val;
  1523. }
  1524. let regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;
  1525. return append.replace(regex, callback);
  1526. }
  1527. /**
  1528. *
  1529. */
  1530. static getBytes(str, encoding) {
  1531. return StringEncoding.encode(str, encoding);
  1532. }
  1533. /**
  1534. * Returns the charcode at the specified index or at index zero.
  1535. */
  1536. static getCharCode(str, index = 0) {
  1537. return str.charCodeAt(index);
  1538. }
  1539. /**
  1540. * Returns char for given charcode
  1541. */
  1542. static getCharAt(charCode) {
  1543. return String.fromCharCode(charCode);
  1544. }
  1545. }
  1546. StringUtils.SHIFT_JIS = CharacterSetECI.SJIS.getName(); // "SJIS"
  1547. StringUtils.GB2312 = 'GB2312';
  1548. StringUtils.ISO88591 = CharacterSetECI.ISO8859_1.getName(); // "ISO8859_1"
  1549. StringUtils.EUC_JP = 'EUC_JP';
  1550. StringUtils.UTF8 = CharacterSetECI.UTF8.getName(); // "UTF8"
  1551. StringUtils.PLATFORM_DEFAULT_ENCODING = StringUtils.UTF8; // "UTF8"//Charset.defaultCharset().name()
  1552. StringUtils.ASSUME_SHIFT_JIS = false;
  1553. class StringBuilder {
  1554. constructor(value = '') {
  1555. this.value = value;
  1556. }
  1557. enableDecoding(encoding) {
  1558. this.encoding = encoding;
  1559. return this;
  1560. }
  1561. append(s) {
  1562. if (typeof s === 'string') {
  1563. this.value += s.toString();
  1564. }
  1565. else if (this.encoding) {
  1566. // use passed format (fromCharCode will return UTF8 encoding)
  1567. this.value += StringUtils.castAsNonUtf8Char(s, this.encoding);
  1568. }
  1569. else {
  1570. // correctly converts from UTF-8, but not other encodings
  1571. this.value += String.fromCharCode(s);
  1572. }
  1573. return this;
  1574. }
  1575. appendChars(str, offset, len) {
  1576. for (let i = offset; offset < offset + len; i++) {
  1577. this.append(str[i]);
  1578. }
  1579. return this;
  1580. }
  1581. length() {
  1582. return this.value.length;
  1583. }
  1584. charAt(n) {
  1585. return this.value.charAt(n);
  1586. }
  1587. deleteCharAt(n) {
  1588. this.value = this.value.substr(0, n) + this.value.substring(n + 1);
  1589. }
  1590. setCharAt(n, c) {
  1591. this.value = this.value.substr(0, n) + c + this.value.substr(n + 1);
  1592. }
  1593. substring(start, end) {
  1594. return this.value.substring(start, end);
  1595. }
  1596. /**
  1597. * @note helper method for RSS Expanded
  1598. */
  1599. setLengthToZero() {
  1600. this.value = '';
  1601. }
  1602. toString() {
  1603. return this.value;
  1604. }
  1605. insert(n, c) {
  1606. this.value = this.value.substring(0, n) + c + this.value.substring(n);
  1607. }
  1608. }
  1609. /*
  1610. * Copyright 2007 ZXing authors
  1611. *
  1612. * Licensed under the Apache License, Version 2.0 (the "License");
  1613. * you may not use this file except in compliance with the License.
  1614. * You may obtain a copy of the License at
  1615. *
  1616. * http://www.apache.org/licenses/LICENSE-2.0
  1617. *
  1618. * Unless required by applicable law or agreed to in writing, software
  1619. * distributed under the License is distributed on an "AS IS" BASIS,
  1620. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1621. * See the License for the specific language governing permissions and
  1622. * limitations under the License.
  1623. */
  1624. /**
  1625. * <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common
  1626. * module, x is the column position, and y is the row position. The ordering is always x, y.
  1627. * The origin is at the top-left.</p>
  1628. *
  1629. * <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins
  1630. * with a new int. This is done intentionally so that we can copy out a row into a BitArray very
  1631. * efficiently.</p>
  1632. *
  1633. * <p>The ordering of bits is row-major. Within each int, the least significant bits are used first,
  1634. * meaning they represent lower x values. This is compatible with BitArray's implementation.</p>
  1635. *
  1636. * @author Sean Owen
  1637. * @author dswitkin@google.com (Daniel Switkin)
  1638. */
  1639. class BitMatrix /*implements Cloneable*/ {
  1640. /**
  1641. * Creates an empty square {@link BitMatrix}.
  1642. *
  1643. * @param dimension height and width
  1644. */
  1645. // public constructor(dimension: number /*int*/) {
  1646. // this(dimension, dimension)
  1647. // }
  1648. /**
  1649. * Creates an empty {@link BitMatrix}.
  1650. *
  1651. * @param width bit matrix width
  1652. * @param height bit matrix height
  1653. */
  1654. // public constructor(width: number /*int*/, height: number /*int*/) {
  1655. // if (width < 1 || height < 1) {
  1656. // throw new IllegalArgumentException("Both dimensions must be greater than 0")
  1657. // }
  1658. // this.width = width
  1659. // this.height = height
  1660. // this.rowSize = (width + 31) / 32
  1661. // bits = new int[rowSize * height];
  1662. // }
  1663. constructor(width /*int*/, height /*int*/, rowSize /*int*/, bits) {
  1664. this.width = width;
  1665. this.height = height;
  1666. this.rowSize = rowSize;
  1667. this.bits = bits;
  1668. if (undefined === height || null === height) {
  1669. height = width;
  1670. }
  1671. this.height = height;
  1672. if (width < 1 || height < 1) {
  1673. throw new IllegalArgumentException('Both dimensions must be greater than 0');
  1674. }
  1675. if (undefined === rowSize || null === rowSize) {
  1676. rowSize = Math.floor((width + 31) / 32);
  1677. }
  1678. this.rowSize = rowSize;
  1679. if (undefined === bits || null === bits) {
  1680. this.bits = new Int32Array(this.rowSize * this.height);
  1681. }
  1682. }
  1683. /**
  1684. * Interprets a 2D array of booleans as a {@link BitMatrix}, where "true" means an "on" bit.
  1685. *
  1686. * @function parse
  1687. * @param image bits of the image, as a row-major 2D array. Elements are arrays representing rows
  1688. * @return {@link BitMatrix} representation of image
  1689. */
  1690. static parseFromBooleanArray(image) {
  1691. const height = image.length;
  1692. const width = image[0].length;
  1693. const bits = new BitMatrix(width, height);
  1694. for (let i = 0; i < height; i++) {
  1695. const imageI = image[i];
  1696. for (let j = 0; j < width; j++) {
  1697. if (imageI[j]) {
  1698. bits.set(j, i);
  1699. }
  1700. }
  1701. }
  1702. return bits;
  1703. }
  1704. /**
  1705. *
  1706. * @function parse
  1707. * @param stringRepresentation
  1708. * @param setString
  1709. * @param unsetString
  1710. */
  1711. static parseFromString(stringRepresentation, setString, unsetString) {
  1712. if (stringRepresentation === null) {
  1713. throw new IllegalArgumentException('stringRepresentation cannot be null');
  1714. }
  1715. const bits = new Array(stringRepresentation.length);
  1716. let bitsPos = 0;
  1717. let rowStartPos = 0;
  1718. let rowLength = -1;
  1719. let nRows = 0;
  1720. let pos = 0;
  1721. while (pos < stringRepresentation.length) {
  1722. if (stringRepresentation.charAt(pos) === '\n' ||
  1723. stringRepresentation.charAt(pos) === '\r') {
  1724. if (bitsPos > rowStartPos) {
  1725. if (rowLength === -1) {
  1726. rowLength = bitsPos - rowStartPos;
  1727. }
  1728. else if (bitsPos - rowStartPos !== rowLength) {
  1729. throw new IllegalArgumentException('row lengths do not match');
  1730. }
  1731. rowStartPos = bitsPos;
  1732. nRows++;
  1733. }
  1734. pos++;
  1735. }
  1736. else if (stringRepresentation.substring(pos, pos + setString.length) === setString) {
  1737. pos += setString.length;
  1738. bits[bitsPos] = true;
  1739. bitsPos++;
  1740. }
  1741. else if (stringRepresentation.substring(pos, pos + unsetString.length) === unsetString) {
  1742. pos += unsetString.length;
  1743. bits[bitsPos] = false;
  1744. bitsPos++;
  1745. }
  1746. else {
  1747. throw new IllegalArgumentException('illegal character encountered: ' + stringRepresentation.substring(pos));
  1748. }
  1749. }
  1750. // no EOL at end?
  1751. if (bitsPos > rowStartPos) {
  1752. if (rowLength === -1) {
  1753. rowLength = bitsPos - rowStartPos;
  1754. }
  1755. else if (bitsPos - rowStartPos !== rowLength) {
  1756. throw new IllegalArgumentException('row lengths do not match');
  1757. }
  1758. nRows++;
  1759. }
  1760. const matrix = new BitMatrix(rowLength, nRows);
  1761. for (let i = 0; i < bitsPos; i++) {
  1762. if (bits[i]) {
  1763. matrix.set(Math.floor(i % rowLength), Math.floor(i / rowLength));
  1764. }
  1765. }
  1766. return matrix;
  1767. }
  1768. /**
  1769. * <p>Gets the requested bit, where true means black.</p>
  1770. *
  1771. * @param x The horizontal component (i.e. which column)
  1772. * @param y The vertical component (i.e. which row)
  1773. * @return value of given bit in matrix
  1774. */
  1775. get(x /*int*/, y /*int*/) {
  1776. const offset = y * this.rowSize + Math.floor(x / 32);
  1777. return ((this.bits[offset] >>> (x & 0x1f)) & 1) !== 0;
  1778. }
  1779. /**
  1780. * <p>Sets the given bit to true.</p>
  1781. *
  1782. * @param x The horizontal component (i.e. which column)
  1783. * @param y The vertical component (i.e. which row)
  1784. */
  1785. set(x /*int*/, y /*int*/) {
  1786. const offset = y * this.rowSize + Math.floor(x / 32);
  1787. this.bits[offset] |= (1 << (x & 0x1f)) & 0xFFFFFFFF;
  1788. }
  1789. unset(x /*int*/, y /*int*/) {
  1790. const offset = y * this.rowSize + Math.floor(x / 32);
  1791. this.bits[offset] &= ~((1 << (x & 0x1f)) & 0xFFFFFFFF);
  1792. }
  1793. /**
  1794. * <p>Flips the given bit.</p>
  1795. *
  1796. * @param x The horizontal component (i.e. which column)
  1797. * @param y The vertical component (i.e. which row)
  1798. */
  1799. flip(x /*int*/, y /*int*/) {
  1800. const offset = y * this.rowSize + Math.floor(x / 32);
  1801. this.bits[offset] ^= ((1 << (x & 0x1f)) & 0xFFFFFFFF);
  1802. }
  1803. /**
  1804. * Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
  1805. * mask bit is set.
  1806. *
  1807. * @param mask XOR mask
  1808. */
  1809. xor(mask) {
  1810. if (this.width !== mask.getWidth() || this.height !== mask.getHeight()
  1811. || this.rowSize !== mask.getRowSize()) {
  1812. throw new IllegalArgumentException('input matrix dimensions do not match');
  1813. }
  1814. const rowArray = new BitArray(Math.floor(this.width / 32) + 1);
  1815. const rowSize = this.rowSize;
  1816. const bits = this.bits;
  1817. for (let y = 0, height = this.height; y < height; y++) {
  1818. const offset = y * rowSize;
  1819. const row = mask.getRow(y, rowArray).getBitArray();
  1820. for (let x = 0; x < rowSize; x++) {
  1821. bits[offset + x] ^= row[x];
  1822. }
  1823. }
  1824. }
  1825. /**
  1826. * Clears all bits (sets to false).
  1827. */
  1828. clear() {
  1829. const bits = this.bits;
  1830. const max = bits.length;
  1831. for (let i = 0; i < max; i++) {
  1832. bits[i] = 0;
  1833. }
  1834. }
  1835. /**
  1836. * <p>Sets a square region of the bit matrix to true.</p>
  1837. *
  1838. * @param left The horizontal position to begin at (inclusive)
  1839. * @param top The vertical position to begin at (inclusive)
  1840. * @param width The width of the region
  1841. * @param height The height of the region
  1842. */
  1843. setRegion(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
  1844. if (top < 0 || left < 0) {
  1845. throw new IllegalArgumentException('Left and top must be nonnegative');
  1846. }
  1847. if (height < 1 || width < 1) {
  1848. throw new IllegalArgumentException('Height and width must be at least 1');
  1849. }
  1850. const right = left + width;
  1851. const bottom = top + height;
  1852. if (bottom > this.height || right > this.width) {
  1853. throw new IllegalArgumentException('The region must fit inside the matrix');
  1854. }
  1855. const rowSize = this.rowSize;
  1856. const bits = this.bits;
  1857. for (let y = top; y < bottom; y++) {
  1858. const offset = y * rowSize;
  1859. for (let x = left; x < right; x++) {
  1860. bits[offset + Math.floor(x / 32)] |= ((1 << (x & 0x1f)) & 0xFFFFFFFF);
  1861. }
  1862. }
  1863. }
  1864. /**
  1865. * A fast method to retrieve one row of data from the matrix as a BitArray.
  1866. *
  1867. * @param y The row to retrieve
  1868. * @param row An optional caller-allocated BitArray, will be allocated if null or too small
  1869. * @return The resulting BitArray - this reference should always be used even when passing
  1870. * your own row
  1871. */
  1872. getRow(y /*int*/, row) {
  1873. if (row === null || row === undefined || row.getSize() < this.width) {
  1874. row = new BitArray(this.width);
  1875. }
  1876. else {
  1877. row.clear();
  1878. }
  1879. const rowSize = this.rowSize;
  1880. const bits = this.bits;
  1881. const offset = y * rowSize;
  1882. for (let x = 0; x < rowSize; x++) {
  1883. row.setBulk(x * 32, bits[offset + x]);
  1884. }
  1885. return row;
  1886. }
  1887. /**
  1888. * @param y row to set
  1889. * @param row {@link BitArray} to copy from
  1890. */
  1891. setRow(y /*int*/, row) {
  1892. System.arraycopy(row.getBitArray(), 0, this.bits, y * this.rowSize, this.rowSize);
  1893. }
  1894. /**
  1895. * Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
  1896. */
  1897. rotate180() {
  1898. const width = this.getWidth();
  1899. const height = this.getHeight();
  1900. let topRow = new BitArray(width);
  1901. let bottomRow = new BitArray(width);
  1902. for (let i = 0, length = Math.floor((height + 1) / 2); i < length; i++) {
  1903. topRow = this.getRow(i, topRow);
  1904. bottomRow = this.getRow(height - 1 - i, bottomRow);
  1905. topRow.reverse();
  1906. bottomRow.reverse();
  1907. this.setRow(i, bottomRow);
  1908. this.setRow(height - 1 - i, topRow);
  1909. }
  1910. }
  1911. /**
  1912. * This is useful in detecting the enclosing rectangle of a 'pure' barcode.
  1913. *
  1914. * @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white
  1915. */
  1916. getEnclosingRectangle() {
  1917. const width = this.width;
  1918. const height = this.height;
  1919. const rowSize = this.rowSize;
  1920. const bits = this.bits;
  1921. let left = width;
  1922. let top = height;
  1923. let right = -1;
  1924. let bottom = -1;
  1925. for (let y = 0; y < height; y++) {
  1926. for (let x32 = 0; x32 < rowSize; x32++) {
  1927. const theBits = bits[y * rowSize + x32];
  1928. if (theBits !== 0) {
  1929. if (y < top) {
  1930. top = y;
  1931. }
  1932. if (y > bottom) {
  1933. bottom = y;
  1934. }
  1935. if (x32 * 32 < left) {
  1936. let bit = 0;
  1937. while (((theBits << (31 - bit)) & 0xFFFFFFFF) === 0) {
  1938. bit++;
  1939. }
  1940. if ((x32 * 32 + bit) < left) {
  1941. left = x32 * 32 + bit;
  1942. }
  1943. }
  1944. if (x32 * 32 + 31 > right) {
  1945. let bit = 31;
  1946. while ((theBits >>> bit) === 0) {
  1947. bit--;
  1948. }
  1949. if ((x32 * 32 + bit) > right) {
  1950. right = x32 * 32 + bit;
  1951. }
  1952. }
  1953. }
  1954. }
  1955. }
  1956. if (right < left || bottom < top) {
  1957. return null;
  1958. }
  1959. return Int32Array.from([left, top, right - left + 1, bottom - top + 1]);
  1960. }
  1961. /**
  1962. * This is useful in detecting a corner of a 'pure' barcode.
  1963. *
  1964. * @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white
  1965. */
  1966. getTopLeftOnBit() {
  1967. const rowSize = this.rowSize;
  1968. const bits = this.bits;
  1969. let bitsOffset = 0;
  1970. while (bitsOffset < bits.length && bits[bitsOffset] === 0) {
  1971. bitsOffset++;
  1972. }
  1973. if (bitsOffset === bits.length) {
  1974. return null;
  1975. }
  1976. const y = bitsOffset / rowSize;
  1977. let x = (bitsOffset % rowSize) * 32;
  1978. const theBits = bits[bitsOffset];
  1979. let bit = 0;
  1980. while (((theBits << (31 - bit)) & 0xFFFFFFFF) === 0) {
  1981. bit++;
  1982. }
  1983. x += bit;
  1984. return Int32Array.from([x, y]);
  1985. }
  1986. getBottomRightOnBit() {
  1987. const rowSize = this.rowSize;
  1988. const bits = this.bits;
  1989. let bitsOffset = bits.length - 1;
  1990. while (bitsOffset >= 0 && bits[bitsOffset] === 0) {
  1991. bitsOffset--;
  1992. }
  1993. if (bitsOffset < 0) {
  1994. return null;
  1995. }
  1996. const y = Math.floor(bitsOffset / rowSize);
  1997. let x = Math.floor(bitsOffset % rowSize) * 32;
  1998. const theBits = bits[bitsOffset];
  1999. let bit = 31;
  2000. while ((theBits >>> bit) === 0) {
  2001. bit--;
  2002. }
  2003. x += bit;
  2004. return Int32Array.from([x, y]);
  2005. }
  2006. /**
  2007. * @return The width of the matrix
  2008. */
  2009. getWidth() {
  2010. return this.width;
  2011. }
  2012. /**
  2013. * @return The height of the matrix
  2014. */
  2015. getHeight() {
  2016. return this.height;
  2017. }
  2018. /**
  2019. * @return The row size of the matrix
  2020. */
  2021. getRowSize() {
  2022. return this.rowSize;
  2023. }
  2024. /*@Override*/
  2025. equals(o) {
  2026. if (!(o instanceof BitMatrix)) {
  2027. return false;
  2028. }
  2029. const other = o;
  2030. return this.width === other.width && this.height === other.height && this.rowSize === other.rowSize &&
  2031. Arrays.equals(this.bits, other.bits);
  2032. }
  2033. /*@Override*/
  2034. hashCode() {
  2035. let hash = this.width;
  2036. hash = 31 * hash + this.width;
  2037. hash = 31 * hash + this.height;
  2038. hash = 31 * hash + this.rowSize;
  2039. hash = 31 * hash + Arrays.hashCode(this.bits);
  2040. return hash;
  2041. }
  2042. /**
  2043. * @return string representation using "X" for set and " " for unset bits
  2044. */
  2045. /*@Override*/
  2046. // public toString(): string {
  2047. // return toString(": "X, " ")
  2048. // }
  2049. /**
  2050. * @param setString representation of a set bit
  2051. * @param unsetString representation of an unset bit
  2052. * @return string representation of entire matrix utilizing given strings
  2053. */
  2054. // public toString(setString: string = "X ", unsetString: string = " "): string {
  2055. // return this.buildToString(setString, unsetString, "\n")
  2056. // }
  2057. /**
  2058. * @param setString representation of a set bit
  2059. * @param unsetString representation of an unset bit
  2060. * @param lineSeparator newline character in string representation
  2061. * @return string representation of entire matrix utilizing given strings and line separator
  2062. * @deprecated call {@link #toString(String,String)} only, which uses \n line separator always
  2063. */
  2064. // @Deprecated
  2065. toString(setString = 'X ', unsetString = ' ', lineSeparator = '\n') {
  2066. return this.buildToString(setString, unsetString, lineSeparator);
  2067. }
  2068. buildToString(setString, unsetString, lineSeparator) {
  2069. let result = new StringBuilder();
  2070. // result.append(lineSeparator);
  2071. for (let y = 0, height = this.height; y < height; y++) {
  2072. for (let x = 0, width = this.width; x < width; x++) {
  2073. result.append(this.get(x, y) ? setString : unsetString);
  2074. }
  2075. result.append(lineSeparator);
  2076. }
  2077. return result.toString();
  2078. }
  2079. /*@Override*/
  2080. clone() {
  2081. return new BitMatrix(this.width, this.height, this.rowSize, this.bits.slice());
  2082. }
  2083. }
  2084. /**
  2085. * Custom Error class of type Exception.
  2086. */
  2087. class NotFoundException extends Exception {
  2088. static getNotFoundInstance() {
  2089. return new NotFoundException();
  2090. }
  2091. }
  2092. NotFoundException.kind = 'NotFoundException';
  2093. /*
  2094. * Copyright 2009 ZXing authors
  2095. *
  2096. * Licensed under the Apache License, Version 2.0 (the "License");
  2097. * you may not use this file except in compliance with the License.
  2098. * You may obtain a copy of the License at
  2099. *
  2100. * http://www.apache.org/licenses/LICENSE-2.0
  2101. *
  2102. * Unless required by applicable law or agreed to in writing, software
  2103. * distributed under the License is distributed on an "AS IS" BASIS,
  2104. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2105. * See the License for the specific language governing permissions and
  2106. * limitations under the License.
  2107. */
  2108. /**
  2109. * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
  2110. * for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
  2111. * algorithm. However, because it picks a global black point, it cannot handle difficult shadows
  2112. * and gradients.
  2113. *
  2114. * Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
  2115. *
  2116. * @author dswitkin@google.com (Daniel Switkin)
  2117. * @author Sean Owen
  2118. */
  2119. class GlobalHistogramBinarizer extends Binarizer {
  2120. constructor(source) {
  2121. super(source);
  2122. this.luminances = GlobalHistogramBinarizer.EMPTY;
  2123. this.buckets = new Int32Array(GlobalHistogramBinarizer.LUMINANCE_BUCKETS);
  2124. }
  2125. // Applies simple sharpening to the row data to improve performance of the 1D Readers.
  2126. /*@Override*/
  2127. getBlackRow(y /*int*/, row) {
  2128. const source = this.getLuminanceSource();
  2129. const width = source.getWidth();
  2130. if (row === undefined || row === null || row.getSize() < width) {
  2131. row = new BitArray(width);
  2132. }
  2133. else {
  2134. row.clear();
  2135. }
  2136. this.initArrays(width);
  2137. const localLuminances = source.getRow(y, this.luminances);
  2138. const localBuckets = this.buckets;
  2139. for (let x = 0; x < width; x++) {
  2140. localBuckets[(localLuminances[x] & 0xff) >> GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;
  2141. }
  2142. const blackPoint = GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);
  2143. if (width < 3) {
  2144. // Special case for very small images
  2145. for (let x = 0; x < width; x++) {
  2146. if ((localLuminances[x] & 0xff) < blackPoint) {
  2147. row.set(x);
  2148. }
  2149. }
  2150. }
  2151. else {
  2152. let left = localLuminances[0] & 0xff;
  2153. let center = localLuminances[1] & 0xff;
  2154. for (let x = 1; x < width - 1; x++) {
  2155. const right = localLuminances[x + 1] & 0xff;
  2156. // A simple -1 4 -1 box filter with a weight of 2.
  2157. if (((center * 4) - left - right) / 2 < blackPoint) {
  2158. row.set(x);
  2159. }
  2160. left = center;
  2161. center = right;
  2162. }
  2163. }
  2164. return row;
  2165. }
  2166. // Does not sharpen the data, as this call is intended to only be used by 2D Readers.
  2167. /*@Override*/
  2168. getBlackMatrix() {
  2169. const source = this.getLuminanceSource();
  2170. const width = source.getWidth();
  2171. const height = source.getHeight();
  2172. const matrix = new BitMatrix(width, height);
  2173. // Quickly calculates the histogram by sampling four rows from the image. This proved to be
  2174. // more robust on the blackbox tests than sampling a diagonal as we used to do.
  2175. this.initArrays(width);
  2176. const localBuckets = this.buckets;
  2177. for (let y = 1; y < 5; y++) {
  2178. const row = Math.floor((height * y) / 5);
  2179. const localLuminances = source.getRow(row, this.luminances);
  2180. const right = Math.floor((width * 4) / 5);
  2181. for (let x = Math.floor(width / 5); x < right; x++) {
  2182. const pixel = localLuminances[x] & 0xff;
  2183. localBuckets[pixel >> GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;
  2184. }
  2185. }
  2186. const blackPoint = GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);
  2187. // We delay reading the entire image luminance until the black point estimation succeeds.
  2188. // Although we end up reading four rows twice, it is consistent with our motto of
  2189. // "fail quickly" which is necessary for continuous scanning.
  2190. const localLuminances = source.getMatrix();
  2191. for (let y = 0; y < height; y++) {
  2192. const offset = y * width;
  2193. for (let x = 0; x < width; x++) {
  2194. const pixel = localLuminances[offset + x] & 0xff;
  2195. if (pixel < blackPoint) {
  2196. matrix.set(x, y);
  2197. }
  2198. }
  2199. }
  2200. return matrix;
  2201. }
  2202. /*@Override*/
  2203. createBinarizer(source) {
  2204. return new GlobalHistogramBinarizer(source);
  2205. }
  2206. initArrays(luminanceSize /*int*/) {
  2207. if (this.luminances.length < luminanceSize) {
  2208. this.luminances = new Uint8ClampedArray(luminanceSize);
  2209. }
  2210. const buckets = this.buckets;
  2211. for (let x = 0; x < GlobalHistogramBinarizer.LUMINANCE_BUCKETS; x++) {
  2212. buckets[x] = 0;
  2213. }
  2214. }
  2215. static estimateBlackPoint(buckets) {
  2216. // Find the tallest peak in the histogram.
  2217. const numBuckets = buckets.length;
  2218. let maxBucketCount = 0;
  2219. let firstPeak = 0;
  2220. let firstPeakSize = 0;
  2221. for (let x = 0; x < numBuckets; x++) {
  2222. if (buckets[x] > firstPeakSize) {
  2223. firstPeak = x;
  2224. firstPeakSize = buckets[x];
  2225. }
  2226. if (buckets[x] > maxBucketCount) {
  2227. maxBucketCount = buckets[x];
  2228. }
  2229. }
  2230. // Find the second-tallest peak which is somewhat far from the tallest peak.
  2231. let secondPeak = 0;
  2232. let secondPeakScore = 0;
  2233. for (let x = 0; x < numBuckets; x++) {
  2234. const distanceToBiggest = x - firstPeak;
  2235. // Encourage more distant second peaks by multiplying by square of distance.
  2236. const score = buckets[x] * distanceToBiggest * distanceToBiggest;
  2237. if (score > secondPeakScore) {
  2238. secondPeak = x;
  2239. secondPeakScore = score;
  2240. }
  2241. }
  2242. // Make sure firstPeak corresponds to the black peak.
  2243. if (firstPeak > secondPeak) {
  2244. const temp = firstPeak;
  2245. firstPeak = secondPeak;
  2246. secondPeak = temp;
  2247. }
  2248. // If there is too little contrast in the image to pick a meaningful black point, throw rather
  2249. // than waste time trying to decode the image, and risk false positives.
  2250. if (secondPeak - firstPeak <= numBuckets / 16) {
  2251. throw new NotFoundException();
  2252. }
  2253. // Find a valley between them that is low and closer to the white peak.
  2254. let bestValley = secondPeak - 1;
  2255. let bestValleyScore = -1;
  2256. for (let x = secondPeak - 1; x > firstPeak; x--) {
  2257. const fromFirst = x - firstPeak;
  2258. const score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]);
  2259. if (score > bestValleyScore) {
  2260. bestValley = x;
  2261. bestValleyScore = score;
  2262. }
  2263. }
  2264. return bestValley << GlobalHistogramBinarizer.LUMINANCE_SHIFT;
  2265. }
  2266. }
  2267. GlobalHistogramBinarizer.LUMINANCE_BITS = 5;
  2268. GlobalHistogramBinarizer.LUMINANCE_SHIFT = 8 - GlobalHistogramBinarizer.LUMINANCE_BITS;
  2269. GlobalHistogramBinarizer.LUMINANCE_BUCKETS = 1 << GlobalHistogramBinarizer.LUMINANCE_BITS;
  2270. GlobalHistogramBinarizer.EMPTY = Uint8ClampedArray.from([0]);
  2271. /*
  2272. * Copyright 2009 ZXing authors
  2273. *
  2274. * Licensed under the Apache License, Version 2.0 (the "License");
  2275. * you may not use this file except in compliance with the License.
  2276. * You may obtain a copy of the License at
  2277. *
  2278. * http://www.apache.org/licenses/LICENSE-2.0
  2279. *
  2280. * Unless required by applicable law or agreed to in writing, software
  2281. * distributed under the License is distributed on an "AS IS" BASIS,
  2282. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2283. * See the License for the specific language governing permissions and
  2284. * limitations under the License.
  2285. */
  2286. /**
  2287. * This class implements a local thresholding algorithm, which while slower than the
  2288. * GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
  2289. * high frequency images of barcodes with black data on white backgrounds. For this application,
  2290. * it does a much better job than a global blackpoint with severe shadows and gradients.
  2291. * However it tends to produce artifacts on lower frequency images and is therefore not
  2292. * a good general purpose binarizer for uses outside ZXing.
  2293. *
  2294. * This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
  2295. * and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
  2296. * inherently local, and only fails for horizontal gradients. We can revisit that problem later,
  2297. * but for now it was not a win to use local blocks for 1D.
  2298. *
  2299. * This Binarizer is the default for the unit tests and the recommended class for library users.
  2300. *
  2301. * @author dswitkin@google.com (Daniel Switkin)
  2302. */
  2303. class HybridBinarizer extends GlobalHistogramBinarizer {
  2304. constructor(source) {
  2305. super(source);
  2306. this.matrix = null;
  2307. }
  2308. /**
  2309. * Calculates the final BitMatrix once for all requests. This could be called once from the
  2310. * constructor instead, but there are some advantages to doing it lazily, such as making
  2311. * profiling easier, and not doing heavy lifting when callers don't expect it.
  2312. */
  2313. /*@Override*/
  2314. getBlackMatrix() {
  2315. if (this.matrix !== null) {
  2316. return this.matrix;
  2317. }
  2318. const source = this.getLuminanceSource();
  2319. const width = source.getWidth();
  2320. const height = source.getHeight();
  2321. if (width >= HybridBinarizer.MINIMUM_DIMENSION && height >= HybridBinarizer.MINIMUM_DIMENSION) {
  2322. const luminances = source.getMatrix();
  2323. let subWidth = width >> HybridBinarizer.BLOCK_SIZE_POWER;
  2324. if ((width & HybridBinarizer.BLOCK_SIZE_MASK) !== 0) {
  2325. subWidth++;
  2326. }
  2327. let subHeight = height >> HybridBinarizer.BLOCK_SIZE_POWER;
  2328. if ((height & HybridBinarizer.BLOCK_SIZE_MASK) !== 0) {
  2329. subHeight++;
  2330. }
  2331. const blackPoints = HybridBinarizer.calculateBlackPoints(luminances, subWidth, subHeight, width, height);
  2332. const newMatrix = new BitMatrix(width, height);
  2333. HybridBinarizer.calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix);
  2334. this.matrix = newMatrix;
  2335. }
  2336. else {
  2337. // If the image is too small, fall back to the global histogram approach.
  2338. this.matrix = super.getBlackMatrix();
  2339. }
  2340. return this.matrix;
  2341. }
  2342. /*@Override*/
  2343. createBinarizer(source) {
  2344. return new HybridBinarizer(source);
  2345. }
  2346. /**
  2347. * For each block in the image, calculate the average black point using a 5x5 grid
  2348. * of the blocks around it. Also handles the corner cases (fractional blocks are computed based
  2349. * on the last pixels in the row/column which are also used in the previous block).
  2350. */
  2351. static calculateThresholdForBlock(luminances, subWidth /*int*/, subHeight /*int*/, width /*int*/, height /*int*/, blackPoints, matrix) {
  2352. const maxYOffset = height - HybridBinarizer.BLOCK_SIZE;
  2353. const maxXOffset = width - HybridBinarizer.BLOCK_SIZE;
  2354. for (let y = 0; y < subHeight; y++) {
  2355. let yoffset = y << HybridBinarizer.BLOCK_SIZE_POWER;
  2356. if (yoffset > maxYOffset) {
  2357. yoffset = maxYOffset;
  2358. }
  2359. const top = HybridBinarizer.cap(y, 2, subHeight - 3);
  2360. for (let x = 0; x < subWidth; x++) {
  2361. let xoffset = x << HybridBinarizer.BLOCK_SIZE_POWER;
  2362. if (xoffset > maxXOffset) {
  2363. xoffset = maxXOffset;
  2364. }
  2365. const left = HybridBinarizer.cap(x, 2, subWidth - 3);
  2366. let sum = 0;
  2367. for (let z = -2; z <= 2; z++) {
  2368. const blackRow = blackPoints[top + z];
  2369. sum += blackRow[left - 2] + blackRow[left - 1] + blackRow[left] + blackRow[left + 1] + blackRow[left + 2];
  2370. }
  2371. const average = sum / 25;
  2372. HybridBinarizer.thresholdBlock(luminances, xoffset, yoffset, average, width, matrix);
  2373. }
  2374. }
  2375. }
  2376. static cap(value /*int*/, min /*int*/, max /*int*/) {
  2377. return value < min ? min : value > max ? max : value;
  2378. }
  2379. /**
  2380. * Applies a single threshold to a block of pixels.
  2381. */
  2382. static thresholdBlock(luminances, xoffset /*int*/, yoffset /*int*/, threshold /*int*/, stride /*int*/, matrix) {
  2383. for (let y = 0, offset = yoffset * stride + xoffset; y < HybridBinarizer.BLOCK_SIZE; y++, offset += stride) {
  2384. for (let x = 0; x < HybridBinarizer.BLOCK_SIZE; x++) {
  2385. // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
  2386. if ((luminances[offset + x] & 0xFF) <= threshold) {
  2387. matrix.set(xoffset + x, yoffset + y);
  2388. }
  2389. }
  2390. }
  2391. }
  2392. /**
  2393. * Calculates a single black point for each block of pixels and saves it away.
  2394. * See the following thread for a discussion of this algorithm:
  2395. * http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
  2396. */
  2397. static calculateBlackPoints(luminances, subWidth /*int*/, subHeight /*int*/, width /*int*/, height /*int*/) {
  2398. const maxYOffset = height - HybridBinarizer.BLOCK_SIZE;
  2399. const maxXOffset = width - HybridBinarizer.BLOCK_SIZE;
  2400. // tslint:disable-next-line:whitespace
  2401. const blackPoints = new Array(subHeight); // subWidth
  2402. for (let y = 0; y < subHeight; y++) {
  2403. blackPoints[y] = new Int32Array(subWidth);
  2404. let yoffset = y << HybridBinarizer.BLOCK_SIZE_POWER;
  2405. if (yoffset > maxYOffset) {
  2406. yoffset = maxYOffset;
  2407. }
  2408. for (let x = 0; x < subWidth; x++) {
  2409. let xoffset = x << HybridBinarizer.BLOCK_SIZE_POWER;
  2410. if (xoffset > maxXOffset) {
  2411. xoffset = maxXOffset;
  2412. }
  2413. let sum = 0;
  2414. let min = 0xFF;
  2415. let max = 0;
  2416. for (let yy = 0, offset = yoffset * width + xoffset; yy < HybridBinarizer.BLOCK_SIZE; yy++, offset += width) {
  2417. for (let xx = 0; xx < HybridBinarizer.BLOCK_SIZE; xx++) {
  2418. const pixel = luminances[offset + xx] & 0xFF;
  2419. sum += pixel;
  2420. // still looking for good contrast
  2421. if (pixel < min) {
  2422. min = pixel;
  2423. }
  2424. if (pixel > max) {
  2425. max = pixel;
  2426. }
  2427. }
  2428. // short-circuit min/max tests once dynamic range is met
  2429. if (max - min > HybridBinarizer.MIN_DYNAMIC_RANGE) {
  2430. // finish the rest of the rows quickly
  2431. for (yy++, offset += width; yy < HybridBinarizer.BLOCK_SIZE; yy++, offset += width) {
  2432. for (let xx = 0; xx < HybridBinarizer.BLOCK_SIZE; xx++) {
  2433. sum += luminances[offset + xx] & 0xFF;
  2434. }
  2435. }
  2436. }
  2437. }
  2438. // The default estimate is the average of the values in the block.
  2439. let average = sum >> (HybridBinarizer.BLOCK_SIZE_POWER * 2);
  2440. if (max - min <= HybridBinarizer.MIN_DYNAMIC_RANGE) {
  2441. // If variation within the block is low, assume this is a block with only light or only
  2442. // dark pixels. In that case we do not want to use the average, as it would divide this
  2443. // low contrast area into black and white pixels, essentially creating data out of noise.
  2444. //
  2445. // The default assumption is that the block is light/background. Since no estimate for
  2446. // the level of dark pixels exists locally, use half the min for the block.
  2447. average = min / 2;
  2448. if (y > 0 && x > 0) {
  2449. // Correct the "white background" assumption for blocks that have neighbors by comparing
  2450. // the pixels in this block to the previously calculated black points. This is based on
  2451. // the fact that dark barcode symbology is always surrounded by some amount of light
  2452. // background for which reasonable black point estimates were made. The bp estimated at
  2453. // the boundaries is used for the interior.
  2454. // The (min < bp) is arbitrary but works better than other heuristics that were tried.
  2455. const averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) / 4;
  2456. if (min < averageNeighborBlackPoint) {
  2457. average = averageNeighborBlackPoint;
  2458. }
  2459. }
  2460. }
  2461. blackPoints[y][x] = average;
  2462. }
  2463. }
  2464. return blackPoints;
  2465. }
  2466. }
  2467. // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
  2468. // So this is the smallest dimension in each axis we can accept.
  2469. HybridBinarizer.BLOCK_SIZE_POWER = 3;
  2470. HybridBinarizer.BLOCK_SIZE = 1 << HybridBinarizer.BLOCK_SIZE_POWER; // ...0100...00
  2471. HybridBinarizer.BLOCK_SIZE_MASK = HybridBinarizer.BLOCK_SIZE - 1; // ...0011...11
  2472. HybridBinarizer.MINIMUM_DIMENSION = HybridBinarizer.BLOCK_SIZE * 5;
  2473. HybridBinarizer.MIN_DYNAMIC_RANGE = 24;
  2474. /*
  2475. * Copyright 2009 ZXing authors
  2476. *
  2477. * Licensed under the Apache License, Version 2.0 (the "License");
  2478. * you may not use this file except in compliance with the License.
  2479. * You may obtain a copy of the License at
  2480. *
  2481. * http://www.apache.org/licenses/LICENSE-2.0
  2482. *
  2483. * Unless required by applicable law or agreed to in writing, software
  2484. * distributed under the License is distributed on an "AS IS" BASIS,
  2485. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2486. * See the License for the specific language governing permissions and
  2487. * limitations under the License.
  2488. */
  2489. /*namespace com.google.zxing {*/
  2490. /**
  2491. * The purpose of this class hierarchy is to abstract different bitmap implementations across
  2492. * platforms into a standard interface for requesting greyscale luminance values. The interface
  2493. * only provides immutable methods; therefore crop and rotation create copies. This is to ensure
  2494. * that one Reader does not modify the original luminance source and leave it in an unknown state
  2495. * for other Readers in the chain.
  2496. *
  2497. * @author dswitkin@google.com (Daniel Switkin)
  2498. */
  2499. class LuminanceSource {
  2500. constructor(width /*int*/, height /*int*/) {
  2501. this.width = width;
  2502. this.height = height;
  2503. }
  2504. /**
  2505. * @return The width of the bitmap.
  2506. */
  2507. getWidth() {
  2508. return this.width;
  2509. }
  2510. /**
  2511. * @return The height of the bitmap.
  2512. */
  2513. getHeight() {
  2514. return this.height;
  2515. }
  2516. /**
  2517. * @return Whether this subclass supports cropping.
  2518. */
  2519. isCropSupported() {
  2520. return false;
  2521. }
  2522. /**
  2523. * Returns a new object with cropped image data. Implementations may keep a reference to the
  2524. * original data rather than a copy. Only callable if isCropSupported() is true.
  2525. *
  2526. * @param left The left coordinate, which must be in [0,getWidth())
  2527. * @param top The top coordinate, which must be in [0,getHeight())
  2528. * @param width The width of the rectangle to crop.
  2529. * @param height The height of the rectangle to crop.
  2530. * @return A cropped version of this object.
  2531. */
  2532. crop(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
  2533. throw new UnsupportedOperationException('This luminance source does not support cropping.');
  2534. }
  2535. /**
  2536. * @return Whether this subclass supports counter-clockwise rotation.
  2537. */
  2538. isRotateSupported() {
  2539. return false;
  2540. }
  2541. /**
  2542. * Returns a new object with rotated image data by 90 degrees counterclockwise.
  2543. * Only callable if {@link #isRotateSupported()} is true.
  2544. *
  2545. * @return A rotated version of this object.
  2546. */
  2547. rotateCounterClockwise() {
  2548. throw new UnsupportedOperationException('This luminance source does not support rotation by 90 degrees.');
  2549. }
  2550. /**
  2551. * Returns a new object with rotated image data by 45 degrees counterclockwise.
  2552. * Only callable if {@link #isRotateSupported()} is true.
  2553. *
  2554. * @return A rotated version of this object.
  2555. */
  2556. rotateCounterClockwise45() {
  2557. throw new UnsupportedOperationException('This luminance source does not support rotation by 45 degrees.');
  2558. }
  2559. /*@Override*/
  2560. toString() {
  2561. const row = new Uint8ClampedArray(this.width);
  2562. let result = new StringBuilder();
  2563. for (let y = 0; y < this.height; y++) {
  2564. const sourceRow = this.getRow(y, row);
  2565. for (let x = 0; x < this.width; x++) {
  2566. const luminance = sourceRow[x] & 0xFF;
  2567. let c;
  2568. if (luminance < 0x40) {
  2569. c = '#';
  2570. }
  2571. else if (luminance < 0x80) {
  2572. c = '+';
  2573. }
  2574. else if (luminance < 0xC0) {
  2575. c = '.';
  2576. }
  2577. else {
  2578. c = ' ';
  2579. }
  2580. result.append(c);
  2581. }
  2582. result.append('\n');
  2583. }
  2584. return result.toString();
  2585. }
  2586. }
  2587. /*
  2588. * Copyright 2009 ZXing authors
  2589. *
  2590. * Licensed under the Apache License, Version 2.0 (the "License");
  2591. * you may not use this file except in compliance with the License.
  2592. * You may obtain a copy of the License at
  2593. *
  2594. * http://www.apache.org/licenses/LICENSE-2.0
  2595. *
  2596. * Unless required by applicable law or agreed to in writing, software
  2597. * distributed under the License is distributed on an "AS IS" BASIS,
  2598. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2599. * See the License for the specific language governing permissions and
  2600. * limitations under the License.
  2601. */
  2602. /*namespace com.google.zxing {*/
  2603. /**
  2604. * A wrapper implementation of {@link LuminanceSource} which inverts the luminances it returns -- black becomes
  2605. * white and vice versa, and each value becomes (255-value).
  2606. *
  2607. * @author Sean Owen
  2608. */
  2609. class InvertedLuminanceSource extends LuminanceSource {
  2610. constructor(delegate) {
  2611. super(delegate.getWidth(), delegate.getHeight());
  2612. this.delegate = delegate;
  2613. }
  2614. /*@Override*/
  2615. getRow(y /*int*/, row) {
  2616. const sourceRow = this.delegate.getRow(y, row);
  2617. const width = this.getWidth();
  2618. for (let i = 0; i < width; i++) {
  2619. sourceRow[i] = /*(byte)*/ (255 - (sourceRow[i] & 0xFF));
  2620. }
  2621. return sourceRow;
  2622. }
  2623. /*@Override*/
  2624. getMatrix() {
  2625. const matrix = this.delegate.getMatrix();
  2626. const length = this.getWidth() * this.getHeight();
  2627. const invertedMatrix = new Uint8ClampedArray(length);
  2628. for (let i = 0; i < length; i++) {
  2629. invertedMatrix[i] = /*(byte)*/ (255 - (matrix[i] & 0xFF));
  2630. }
  2631. return invertedMatrix;
  2632. }
  2633. /*@Override*/
  2634. isCropSupported() {
  2635. return this.delegate.isCropSupported();
  2636. }
  2637. /*@Override*/
  2638. crop(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
  2639. return new InvertedLuminanceSource(this.delegate.crop(left, top, width, height));
  2640. }
  2641. /*@Override*/
  2642. isRotateSupported() {
  2643. return this.delegate.isRotateSupported();
  2644. }
  2645. /**
  2646. * @return original delegate {@link LuminanceSource} since invert undoes itself
  2647. */
  2648. /*@Override*/
  2649. invert() {
  2650. return this.delegate;
  2651. }
  2652. /*@Override*/
  2653. rotateCounterClockwise() {
  2654. return new InvertedLuminanceSource(this.delegate.rotateCounterClockwise());
  2655. }
  2656. /*@Override*/
  2657. rotateCounterClockwise45() {
  2658. return new InvertedLuminanceSource(this.delegate.rotateCounterClockwise45());
  2659. }
  2660. }
  2661. /**
  2662. * @deprecated Moving to @zxing/browser
  2663. */
  2664. class HTMLCanvasElementLuminanceSource extends LuminanceSource {
  2665. constructor(canvas) {
  2666. super(canvas.width, canvas.height);
  2667. this.canvas = canvas;
  2668. this.tempCanvasElement = null;
  2669. this.buffer = HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(canvas);
  2670. }
  2671. static makeBufferFromCanvasImageData(canvas) {
  2672. const imageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
  2673. return HTMLCanvasElementLuminanceSource.toGrayscaleBuffer(imageData.data, canvas.width, canvas.height);
  2674. }
  2675. static toGrayscaleBuffer(imageBuffer, width, height) {
  2676. const grayscaleBuffer = new Uint8ClampedArray(width * height);
  2677. HTMLCanvasElementLuminanceSource.FRAME_INDEX = !HTMLCanvasElementLuminanceSource.FRAME_INDEX;
  2678. if (HTMLCanvasElementLuminanceSource.FRAME_INDEX) {
  2679. for (let i = 0, j = 0, length = imageBuffer.length; i < length; i += 4, j++) {
  2680. let gray;
  2681. const alpha = imageBuffer[i + 3];
  2682. // The color of fully-transparent pixels is irrelevant. They are often, technically, fully-transparent
  2683. // black (0 alpha, and then 0 RGB). They are often used, of course as the "white" area in a
  2684. // barcode image. Force any such pixel to be white:
  2685. if (alpha === 0) {
  2686. gray = 0xFF;
  2687. }
  2688. else {
  2689. const pixelR = imageBuffer[i];
  2690. const pixelG = imageBuffer[i + 1];
  2691. const pixelB = imageBuffer[i + 2];
  2692. // .299R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC),
  2693. // (306*R) >> 10 is approximately equal to R*0.299, and so on.
  2694. // 0x200 >> 10 is 0.5, it implements rounding.
  2695. gray = (306 * pixelR +
  2696. 601 * pixelG +
  2697. 117 * pixelB +
  2698. 0x200) >> 10;
  2699. }
  2700. grayscaleBuffer[j] = gray;
  2701. }
  2702. }
  2703. else {
  2704. for (let i = 0, j = 0, length = imageBuffer.length; i < length; i += 4, j++) {
  2705. let gray;
  2706. const alpha = imageBuffer[i + 3];
  2707. // The color of fully-transparent pixels is irrelevant. They are often, technically, fully-transparent
  2708. // black (0 alpha, and then 0 RGB). They are often used, of course as the "white" area in a
  2709. // barcode image. Force any such pixel to be white:
  2710. if (alpha === 0) {
  2711. gray = 0xFF;
  2712. }
  2713. else {
  2714. const pixelR = imageBuffer[i];
  2715. const pixelG = imageBuffer[i + 1];
  2716. const pixelB = imageBuffer[i + 2];
  2717. // .299R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC),
  2718. // (306*R) >> 10 is approximately equal to R*0.299, and so on.
  2719. // 0x200 >> 10 is 0.5, it implements rounding.
  2720. gray = (306 * pixelR +
  2721. 601 * pixelG +
  2722. 117 * pixelB +
  2723. 0x200) >> 10;
  2724. }
  2725. grayscaleBuffer[j] = 0xFF - gray;
  2726. }
  2727. }
  2728. return grayscaleBuffer;
  2729. }
  2730. getRow(y /*int*/, row) {
  2731. if (y < 0 || y >= this.getHeight()) {
  2732. throw new IllegalArgumentException('Requested row is outside the image: ' + y);
  2733. }
  2734. const width = this.getWidth();
  2735. const start = y * width;
  2736. if (row === null) {
  2737. row = this.buffer.slice(start, start + width);
  2738. }
  2739. else {
  2740. if (row.length < width) {
  2741. row = new Uint8ClampedArray(width);
  2742. }
  2743. // The underlying raster of image consists of bytes with the luminance values
  2744. // TODO: can avoid set/slice?
  2745. row.set(this.buffer.slice(start, start + width));
  2746. }
  2747. return row;
  2748. }
  2749. getMatrix() {
  2750. return this.buffer;
  2751. }
  2752. isCropSupported() {
  2753. return true;
  2754. }
  2755. crop(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
  2756. super.crop(left, top, width, height);
  2757. return this;
  2758. }
  2759. /**
  2760. * This is always true, since the image is a gray-scale image.
  2761. *
  2762. * @return true
  2763. */
  2764. isRotateSupported() {
  2765. return true;
  2766. }
  2767. rotateCounterClockwise() {
  2768. this.rotate(-90);
  2769. return this;
  2770. }
  2771. rotateCounterClockwise45() {
  2772. this.rotate(-45);
  2773. return this;
  2774. }
  2775. getTempCanvasElement() {
  2776. if (null === this.tempCanvasElement) {
  2777. const tempCanvasElement = this.canvas.ownerDocument.createElement('canvas');
  2778. tempCanvasElement.width = this.canvas.width;
  2779. tempCanvasElement.height = this.canvas.height;
  2780. this.tempCanvasElement = tempCanvasElement;
  2781. }
  2782. return this.tempCanvasElement;
  2783. }
  2784. rotate(angle) {
  2785. const tempCanvasElement = this.getTempCanvasElement();
  2786. const tempContext = tempCanvasElement.getContext('2d');
  2787. const angleRadians = angle * HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS;
  2788. // Calculate and set new dimensions for temp canvas
  2789. const width = this.canvas.width;
  2790. const height = this.canvas.height;
  2791. const newWidth = Math.ceil(Math.abs(Math.cos(angleRadians)) * width + Math.abs(Math.sin(angleRadians)) * height);
  2792. const newHeight = Math.ceil(Math.abs(Math.sin(angleRadians)) * width + Math.abs(Math.cos(angleRadians)) * height);
  2793. tempCanvasElement.width = newWidth;
  2794. tempCanvasElement.height = newHeight;
  2795. // Draw at center of temp canvas to prevent clipping of image data
  2796. tempContext.translate(newWidth / 2, newHeight / 2);
  2797. tempContext.rotate(angleRadians);
  2798. tempContext.drawImage(this.canvas, width / -2, height / -2);
  2799. this.buffer = HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(tempCanvasElement);
  2800. return this;
  2801. }
  2802. invert() {
  2803. return new InvertedLuminanceSource(this);
  2804. }
  2805. }
  2806. HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS = Math.PI / 180;
  2807. HTMLCanvasElementLuminanceSource.FRAME_INDEX = true;
  2808. /**
  2809. * @deprecated Moving to @zxing/browser
  2810. *
  2811. * Video input device metadata containing the id and label of the device if available.
  2812. */
  2813. class VideoInputDevice {
  2814. /**
  2815. * Creates an instance of VideoInputDevice.
  2816. *
  2817. * @param {string} deviceId the video input device id
  2818. * @param {string} label the label of the device if available
  2819. */
  2820. constructor(deviceId, label, groupId) {
  2821. this.deviceId = deviceId;
  2822. this.label = label;
  2823. /** @inheritdoc */
  2824. this.kind = 'videoinput';
  2825. this.groupId = groupId || undefined;
  2826. }
  2827. /** @inheritdoc */
  2828. toJSON() {
  2829. return {
  2830. kind: this.kind,
  2831. groupId: this.groupId,
  2832. deviceId: this.deviceId,
  2833. label: this.label,
  2834. };
  2835. }
  2836. }
  2837. var __awaiter = ((globalThis || global || self || window || undefined) && (globalThis || global || self || window || undefined).__awaiter) || function (thisArg, _arguments, P, generator) {
  2838. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  2839. return new (P || (P = Promise))(function (resolve, reject) {
  2840. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  2841. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  2842. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  2843. step((generator = generator.apply(thisArg, _arguments || [])).next());
  2844. });
  2845. };
  2846. /**
  2847. * @deprecated Moving to @zxing/browser
  2848. *
  2849. * Base class for browser code reader.
  2850. */
  2851. class BrowserCodeReader {
  2852. /**
  2853. * Creates an instance of BrowserCodeReader.
  2854. * @param {Reader} reader The reader instance to decode the barcode
  2855. * @param {number} [timeBetweenScansMillis=500] the time delay between subsequent successful decode tries
  2856. *
  2857. * @memberOf BrowserCodeReader
  2858. */
  2859. constructor(reader, timeBetweenScansMillis = 500, _hints) {
  2860. this.reader = reader;
  2861. this.timeBetweenScansMillis = timeBetweenScansMillis;
  2862. this._hints = _hints;
  2863. /**
  2864. * This will break the loop.
  2865. */
  2866. this._stopContinuousDecode = false;
  2867. /**
  2868. * This will break the loop.
  2869. */
  2870. this._stopAsyncDecode = false;
  2871. /**
  2872. * Delay time between decode attempts made by the scanner.
  2873. */
  2874. this._timeBetweenDecodingAttempts = 0;
  2875. }
  2876. /**
  2877. * If navigator is present.
  2878. */
  2879. get hasNavigator() {
  2880. return typeof navigator !== 'undefined';
  2881. }
  2882. /**
  2883. * If mediaDevices under navigator is supported.
  2884. */
  2885. get isMediaDevicesSuported() {
  2886. return this.hasNavigator && !!navigator.mediaDevices;
  2887. }
  2888. /**
  2889. * If enumerateDevices under navigator is supported.
  2890. */
  2891. get canEnumerateDevices() {
  2892. return !!(this.isMediaDevicesSuported && navigator.mediaDevices.enumerateDevices);
  2893. }
  2894. /** Time between two decoding tries in milli seconds. */
  2895. get timeBetweenDecodingAttempts() {
  2896. return this._timeBetweenDecodingAttempts;
  2897. }
  2898. /**
  2899. * Change the time span the decoder waits between two decoding tries.
  2900. *
  2901. * @param {number} millis Time between two decoding tries in milli seconds.
  2902. */
  2903. set timeBetweenDecodingAttempts(millis) {
  2904. this._timeBetweenDecodingAttempts = millis < 0 ? 0 : millis;
  2905. }
  2906. /**
  2907. * Sets the hints.
  2908. */
  2909. set hints(hints) {
  2910. this._hints = hints || null;
  2911. }
  2912. /**
  2913. * Sets the hints.
  2914. */
  2915. get hints() {
  2916. return this._hints;
  2917. }
  2918. /**
  2919. * Lists all the available video input devices.
  2920. */
  2921. listVideoInputDevices() {
  2922. return __awaiter(this, void 0, void 0, function* () {
  2923. if (!this.hasNavigator) {
  2924. throw new Error("Can't enumerate devices, navigator is not present.");
  2925. }
  2926. if (!this.canEnumerateDevices) {
  2927. throw new Error("Can't enumerate devices, method not supported.");
  2928. }
  2929. const devices = yield navigator.mediaDevices.enumerateDevices();
  2930. const videoDevices = [];
  2931. for (const device of devices) {
  2932. const kind = device.kind === 'video' ? 'videoinput' : device.kind;
  2933. if (kind !== 'videoinput') {
  2934. continue;
  2935. }
  2936. const deviceId = device.deviceId || device.id;
  2937. const label = device.label || `Video device ${videoDevices.length + 1}`;
  2938. const groupId = device.groupId;
  2939. const videoDevice = { deviceId, label, kind, groupId };
  2940. videoDevices.push(videoDevice);
  2941. }
  2942. return videoDevices;
  2943. });
  2944. }
  2945. /**
  2946. * Obtain the list of available devices with type 'videoinput'.
  2947. *
  2948. * @returns {Promise<VideoInputDevice[]>} an array of available video input devices
  2949. *
  2950. * @memberOf BrowserCodeReader
  2951. *
  2952. * @deprecated Use `listVideoInputDevices` instead.
  2953. */
  2954. getVideoInputDevices() {
  2955. return __awaiter(this, void 0, void 0, function* () {
  2956. const devices = yield this.listVideoInputDevices();
  2957. return devices.map(d => new VideoInputDevice(d.deviceId, d.label));
  2958. });
  2959. }
  2960. /**
  2961. * Let's you find a device using it's Id.
  2962. */
  2963. findDeviceById(deviceId) {
  2964. return __awaiter(this, void 0, void 0, function* () {
  2965. const devices = yield this.listVideoInputDevices();
  2966. if (!devices) {
  2967. return null;
  2968. }
  2969. return devices.find(x => x.deviceId === deviceId);
  2970. });
  2971. }
  2972. /**
  2973. * Decodes the barcode from the device specified by deviceId while showing the video in the specified video element.
  2974. *
  2975. * @param deviceId the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
  2976. * @param video the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  2977. * @returns The decoding result.
  2978. *
  2979. * @memberOf BrowserCodeReader
  2980. *
  2981. * @deprecated Use `decodeOnceFromVideoDevice` instead.
  2982. */
  2983. decodeFromInputVideoDevice(deviceId, videoSource) {
  2984. return __awaiter(this, void 0, void 0, function* () {
  2985. return yield this.decodeOnceFromVideoDevice(deviceId, videoSource);
  2986. });
  2987. }
  2988. /**
  2989. * In one attempt, tries to decode the barcode from the device specified by deviceId while showing the video in the specified video element.
  2990. *
  2991. * @param deviceId the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
  2992. * @param video the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  2993. * @returns The decoding result.
  2994. *
  2995. * @memberOf BrowserCodeReader
  2996. */
  2997. decodeOnceFromVideoDevice(deviceId, videoSource) {
  2998. return __awaiter(this, void 0, void 0, function* () {
  2999. this.reset();
  3000. let videoConstraints;
  3001. if (!deviceId) {
  3002. videoConstraints = { facingMode: 'environment' };
  3003. }
  3004. else {
  3005. videoConstraints = { deviceId: { exact: deviceId } };
  3006. }
  3007. const constraints = { video: videoConstraints };
  3008. return yield this.decodeOnceFromConstraints(constraints, videoSource);
  3009. });
  3010. }
  3011. /**
  3012. * In one attempt, tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
  3013. *
  3014. * @param constraints the media stream constraints to get s valid media stream to decode from
  3015. * @param video the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  3016. * @returns The decoding result.
  3017. *
  3018. * @memberOf BrowserCodeReader
  3019. */
  3020. decodeOnceFromConstraints(constraints, videoSource) {
  3021. return __awaiter(this, void 0, void 0, function* () {
  3022. const stream = yield navigator.mediaDevices.getUserMedia(constraints);
  3023. return yield this.decodeOnceFromStream(stream, videoSource);
  3024. });
  3025. }
  3026. /**
  3027. * In one attempt, tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
  3028. *
  3029. * @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
  3030. * @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  3031. * @returns {Promise<Result>} The decoding result.
  3032. *
  3033. * @memberOf BrowserCodeReader
  3034. */
  3035. decodeOnceFromStream(stream, videoSource) {
  3036. return __awaiter(this, void 0, void 0, function* () {
  3037. this.reset();
  3038. const video = yield this.attachStreamToVideo(stream, videoSource);
  3039. const result = yield this.decodeOnce(video);
  3040. return result;
  3041. });
  3042. }
  3043. /**
  3044. * Continuously decodes the barcode from the device specified by device while showing the video in the specified video element.
  3045. *
  3046. * @param {string|null} [deviceId] the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
  3047. * @param {string|HTMLVideoElement|null} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  3048. * @returns {Promise<void>}
  3049. *
  3050. * @memberOf BrowserCodeReader
  3051. *
  3052. * @deprecated Use `decodeFromVideoDevice` instead.
  3053. */
  3054. decodeFromInputVideoDeviceContinuously(deviceId, videoSource, callbackFn) {
  3055. return __awaiter(this, void 0, void 0, function* () {
  3056. return yield this.decodeFromVideoDevice(deviceId, videoSource, callbackFn);
  3057. });
  3058. }
  3059. /**
  3060. * Continuously tries to decode the barcode from the device specified by device while showing the video in the specified video element.
  3061. *
  3062. * @param {string|null} [deviceId] the id of one of the devices obtained after calling getVideoInputDevices. Can be undefined, in this case it will decode from one of the available devices, preffering the main camera (environment facing) if available.
  3063. * @param {string|HTMLVideoElement|null} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  3064. * @returns {Promise<void>}
  3065. *
  3066. * @memberOf BrowserCodeReader
  3067. */
  3068. decodeFromVideoDevice(deviceId, videoSource, callbackFn) {
  3069. return __awaiter(this, void 0, void 0, function* () {
  3070. let videoConstraints;
  3071. if (!deviceId) {
  3072. videoConstraints = { facingMode: 'environment' };
  3073. }
  3074. else {
  3075. videoConstraints = { deviceId: { exact: deviceId } };
  3076. }
  3077. const constraints = { video: videoConstraints };
  3078. return yield this.decodeFromConstraints(constraints, videoSource, callbackFn);
  3079. });
  3080. }
  3081. /**
  3082. * Continuously tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
  3083. *
  3084. * @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
  3085. * @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  3086. * @returns {Promise<Result>} The decoding result.
  3087. *
  3088. * @memberOf BrowserCodeReader
  3089. */
  3090. decodeFromConstraints(constraints, videoSource, callbackFn) {
  3091. return __awaiter(this, void 0, void 0, function* () {
  3092. const stream = yield navigator.mediaDevices.getUserMedia(constraints);
  3093. return yield this.decodeFromStream(stream, videoSource, callbackFn);
  3094. });
  3095. }
  3096. /**
  3097. * In one attempt, tries to decode the barcode from a stream obtained from the given constraints while showing the video in the specified video element.
  3098. *
  3099. * @param {MediaStream} [constraints] the media stream constraints to get s valid media stream to decode from
  3100. * @param {string|HTMLVideoElement} [video] the video element in page where to show the video while decoding. Can be either an element id or directly an HTMLVideoElement. Can be undefined, in which case no video will be shown.
  3101. * @returns {Promise<Result>} The decoding result.
  3102. *
  3103. * @memberOf BrowserCodeReader
  3104. */
  3105. decodeFromStream(stream, videoSource, callbackFn) {
  3106. return __awaiter(this, void 0, void 0, function* () {
  3107. this.reset();
  3108. const video = yield this.attachStreamToVideo(stream, videoSource);
  3109. return yield this.decodeContinuously(video, callbackFn);
  3110. });
  3111. }
  3112. /**
  3113. * Breaks the decoding loop.
  3114. */
  3115. stopAsyncDecode() {
  3116. this._stopAsyncDecode = true;
  3117. }
  3118. /**
  3119. * Breaks the decoding loop.
  3120. */
  3121. stopContinuousDecode() {
  3122. this._stopContinuousDecode = true;
  3123. }
  3124. /**
  3125. * Sets the new stream and request a new decoding-with-delay.
  3126. *
  3127. * @param stream The stream to be shown in the video element.
  3128. * @param decodeFn A callback for the decode method.
  3129. */
  3130. attachStreamToVideo(stream, videoSource) {
  3131. return __awaiter(this, void 0, void 0, function* () {
  3132. const videoElement = this.prepareVideoElement(videoSource);
  3133. this.addVideoSource(videoElement, stream);
  3134. this.videoElement = videoElement;
  3135. this.stream = stream;
  3136. yield this.playVideoOnLoadAsync(videoElement);
  3137. return videoElement;
  3138. });
  3139. }
  3140. /**
  3141. *
  3142. * @param videoElement
  3143. */
  3144. playVideoOnLoadAsync(videoElement) {
  3145. return new Promise((resolve, reject) => this.playVideoOnLoad(videoElement, () => resolve()));
  3146. }
  3147. /**
  3148. * Binds listeners and callbacks to the videoElement.
  3149. *
  3150. * @param element
  3151. * @param callbackFn
  3152. */
  3153. playVideoOnLoad(element, callbackFn) {
  3154. this.videoEndedListener = () => this.stopStreams();
  3155. this.videoCanPlayListener = () => this.tryPlayVideo(element);
  3156. element.addEventListener('ended', this.videoEndedListener);
  3157. element.addEventListener('canplay', this.videoCanPlayListener);
  3158. element.addEventListener('playing', callbackFn);
  3159. // if canplay was already fired, we won't know when to play, so just give it a try
  3160. this.tryPlayVideo(element);
  3161. }
  3162. /**
  3163. * Checks if the given video element is currently playing.
  3164. */
  3165. isVideoPlaying(video) {
  3166. return (video.currentTime > 0 &&
  3167. !video.paused &&
  3168. !video.ended &&
  3169. video.readyState > 2);
  3170. }
  3171. /**
  3172. * Just tries to play the video and logs any errors.
  3173. * The play call is only made is the video is not already playing.
  3174. */
  3175. tryPlayVideo(videoElement) {
  3176. return __awaiter(this, void 0, void 0, function* () {
  3177. if (this.isVideoPlaying(videoElement)) {
  3178. console.warn('Trying to play video that is already playing.');
  3179. return;
  3180. }
  3181. try {
  3182. yield videoElement.play();
  3183. }
  3184. catch (_a) {
  3185. console.warn('It was not possible to play the video.');
  3186. }
  3187. });
  3188. }
  3189. /**
  3190. * Searches and validates a media element.
  3191. */
  3192. getMediaElement(mediaElementId, type) {
  3193. const mediaElement = document.getElementById(mediaElementId);
  3194. if (!mediaElement) {
  3195. throw new ArgumentException(`element with id '${mediaElementId}' not found`);
  3196. }
  3197. if (mediaElement.nodeName.toLowerCase() !== type.toLowerCase()) {
  3198. throw new ArgumentException(`element with id '${mediaElementId}' must be an ${type} element`);
  3199. }
  3200. return mediaElement;
  3201. }
  3202. /**
  3203. * Decodes the barcode from an image.
  3204. *
  3205. * @param {(string|HTMLImageElement)} [source] The image element that can be either an element id or the element itself. Can be undefined in which case the decoding will be done from the imageUrl parameter.
  3206. * @param {string} [url]
  3207. * @returns {Promise<Result>} The decoding result.
  3208. *
  3209. * @memberOf BrowserCodeReader
  3210. */
  3211. decodeFromImage(source, url) {
  3212. if (!source && !url) {
  3213. throw new ArgumentException('either imageElement with a src set or an url must be provided');
  3214. }
  3215. if (url && !source) {
  3216. return this.decodeFromImageUrl(url);
  3217. }
  3218. return this.decodeFromImageElement(source);
  3219. }
  3220. /**
  3221. * Decodes the barcode from a video.
  3222. *
  3223. * @param {(string|HTMLImageElement)} [source] The image element that can be either an element id or the element itself. Can be undefined in which case the decoding will be done from the imageUrl parameter.
  3224. * @param {string} [url]
  3225. * @returns {Promise<Result>} The decoding result.
  3226. *
  3227. * @memberOf BrowserCodeReader
  3228. */
  3229. decodeFromVideo(source, url) {
  3230. if (!source && !url) {
  3231. throw new ArgumentException('Either an element with a src set or an URL must be provided');
  3232. }
  3233. if (url && !source) {
  3234. return this.decodeFromVideoUrl(url);
  3235. }
  3236. return this.decodeFromVideoElement(source);
  3237. }
  3238. /**
  3239. * Decodes continuously the barcode from a video.
  3240. *
  3241. * @param {(string|HTMLImageElement)} [source] The image element that can be either an element id or the element itself. Can be undefined in which case the decoding will be done from the imageUrl parameter.
  3242. * @param {string} [url]
  3243. * @returns {Promise<Result>} The decoding result.
  3244. *
  3245. * @memberOf BrowserCodeReader
  3246. *
  3247. * @experimental
  3248. */
  3249. decodeFromVideoContinuously(source, url, callbackFn) {
  3250. if (undefined === source && undefined === url) {
  3251. throw new ArgumentException('Either an element with a src set or an URL must be provided');
  3252. }
  3253. if (url && !source) {
  3254. return this.decodeFromVideoUrlContinuously(url, callbackFn);
  3255. }
  3256. return this.decodeFromVideoElementContinuously(source, callbackFn);
  3257. }
  3258. /**
  3259. * Decodes something from an image HTML element.
  3260. */
  3261. decodeFromImageElement(source) {
  3262. if (!source) {
  3263. throw new ArgumentException('An image element must be provided.');
  3264. }
  3265. this.reset();
  3266. const element = this.prepareImageElement(source);
  3267. this.imageElement = element;
  3268. let task;
  3269. if (this.isImageLoaded(element)) {
  3270. task = this.decodeOnce(element, false, true);
  3271. }
  3272. else {
  3273. task = this._decodeOnLoadImage(element);
  3274. }
  3275. return task;
  3276. }
  3277. /**
  3278. * Decodes something from an image HTML element.
  3279. */
  3280. decodeFromVideoElement(source) {
  3281. const element = this._decodeFromVideoElementSetup(source);
  3282. return this._decodeOnLoadVideo(element);
  3283. }
  3284. /**
  3285. * Decodes something from an image HTML element.
  3286. */
  3287. decodeFromVideoElementContinuously(source, callbackFn) {
  3288. const element = this._decodeFromVideoElementSetup(source);
  3289. return this._decodeOnLoadVideoContinuously(element, callbackFn);
  3290. }
  3291. /**
  3292. * Sets up the video source so it can be decoded when loaded.
  3293. *
  3294. * @param source The video source element.
  3295. */
  3296. _decodeFromVideoElementSetup(source) {
  3297. if (!source) {
  3298. throw new ArgumentException('A video element must be provided.');
  3299. }
  3300. this.reset();
  3301. const element = this.prepareVideoElement(source);
  3302. // defines the video element before starts decoding
  3303. this.videoElement = element;
  3304. return element;
  3305. }
  3306. /**
  3307. * Decodes an image from a URL.
  3308. */
  3309. decodeFromImageUrl(url) {
  3310. if (!url) {
  3311. throw new ArgumentException('An URL must be provided.');
  3312. }
  3313. this.reset();
  3314. const element = this.prepareImageElement();
  3315. this.imageElement = element;
  3316. const decodeTask = this._decodeOnLoadImage(element);
  3317. element.src = url;
  3318. return decodeTask;
  3319. }
  3320. /**
  3321. * Decodes an image from a URL.
  3322. */
  3323. decodeFromVideoUrl(url) {
  3324. if (!url) {
  3325. throw new ArgumentException('An URL must be provided.');
  3326. }
  3327. this.reset();
  3328. // creates a new element
  3329. const element = this.prepareVideoElement();
  3330. const decodeTask = this.decodeFromVideoElement(element);
  3331. element.src = url;
  3332. return decodeTask;
  3333. }
  3334. /**
  3335. * Decodes an image from a URL.
  3336. *
  3337. * @experimental
  3338. */
  3339. decodeFromVideoUrlContinuously(url, callbackFn) {
  3340. if (!url) {
  3341. throw new ArgumentException('An URL must be provided.');
  3342. }
  3343. this.reset();
  3344. // creates a new element
  3345. const element = this.prepareVideoElement();
  3346. const decodeTask = this.decodeFromVideoElementContinuously(element, callbackFn);
  3347. element.src = url;
  3348. return decodeTask;
  3349. }
  3350. _decodeOnLoadImage(element) {
  3351. return new Promise((resolve, reject) => {
  3352. this.imageLoadedListener = () => this.decodeOnce(element, false, true).then(resolve, reject);
  3353. element.addEventListener('load', this.imageLoadedListener);
  3354. });
  3355. }
  3356. _decodeOnLoadVideo(videoElement) {
  3357. return __awaiter(this, void 0, void 0, function* () {
  3358. // plays the video
  3359. yield this.playVideoOnLoadAsync(videoElement);
  3360. // starts decoding after played the video
  3361. return yield this.decodeOnce(videoElement);
  3362. });
  3363. }
  3364. _decodeOnLoadVideoContinuously(videoElement, callbackFn) {
  3365. return __awaiter(this, void 0, void 0, function* () {
  3366. // plays the video
  3367. yield this.playVideoOnLoadAsync(videoElement);
  3368. // starts decoding after played the video
  3369. this.decodeContinuously(videoElement, callbackFn);
  3370. });
  3371. }
  3372. isImageLoaded(img) {
  3373. // During the onload event, IE correctly identifies any images that
  3374. // weren’t downloaded as not complete. Others should too. Gecko-based
  3375. // browsers act like NS4 in that they report this incorrectly.
  3376. if (!img.complete) {
  3377. return false;
  3378. }
  3379. // However, they do have two very useful properties: naturalWidth and
  3380. // naturalHeight. These give the true size of the image. If it failed
  3381. // to load, either of these should be zero.
  3382. if (img.naturalWidth === 0) {
  3383. return false;
  3384. }
  3385. // No other way of checking: assume it’s ok.
  3386. return true;
  3387. }
  3388. prepareImageElement(imageSource) {
  3389. let imageElement;
  3390. if (typeof imageSource === 'undefined') {
  3391. imageElement = document.createElement('img');
  3392. imageElement.width = 200;
  3393. imageElement.height = 200;
  3394. }
  3395. if (typeof imageSource === 'string') {
  3396. imageElement = this.getMediaElement(imageSource, 'img');
  3397. }
  3398. if (imageSource instanceof HTMLImageElement) {
  3399. imageElement = imageSource;
  3400. }
  3401. return imageElement;
  3402. }
  3403. /**
  3404. * Sets a HTMLVideoElement for scanning or creates a new one.
  3405. *
  3406. * @param videoSource The HTMLVideoElement to be set.
  3407. */
  3408. prepareVideoElement(videoSource) {
  3409. let videoElement;
  3410. if (!videoSource && typeof document !== 'undefined') {
  3411. videoElement = document.createElement('video');
  3412. videoElement.width = 200;
  3413. videoElement.height = 200;
  3414. }
  3415. if (typeof videoSource === 'string') {
  3416. videoElement = (this.getMediaElement(videoSource, 'video'));
  3417. }
  3418. if (videoSource instanceof HTMLVideoElement) {
  3419. videoElement = videoSource;
  3420. }
  3421. // Needed for iOS 11
  3422. videoElement.setAttribute('autoplay', 'true');
  3423. videoElement.setAttribute('muted', 'true');
  3424. videoElement.setAttribute('playsinline', 'true');
  3425. return videoElement;
  3426. }
  3427. /**
  3428. * Tries to decode from the video input until it finds some value.
  3429. */
  3430. decodeOnce(element, retryIfNotFound = true, retryIfChecksumOrFormatError = true) {
  3431. this._stopAsyncDecode = false;
  3432. const loop = (resolve, reject) => {
  3433. if (this._stopAsyncDecode) {
  3434. reject(new NotFoundException('Video stream has ended before any code could be detected.'));
  3435. this._stopAsyncDecode = undefined;
  3436. return;
  3437. }
  3438. try {
  3439. const result = this.decode(element);
  3440. resolve(result);
  3441. }
  3442. catch (e) {
  3443. const ifNotFound = retryIfNotFound && e instanceof NotFoundException;
  3444. const isChecksumOrFormatError = e instanceof ChecksumException || e instanceof FormatException;
  3445. const ifChecksumOrFormat = isChecksumOrFormatError && retryIfChecksumOrFormatError;
  3446. if (ifNotFound || ifChecksumOrFormat) {
  3447. // trying again
  3448. return setTimeout(loop, this._timeBetweenDecodingAttempts, resolve, reject);
  3449. }
  3450. reject(e);
  3451. }
  3452. };
  3453. return new Promise((resolve, reject) => loop(resolve, reject));
  3454. }
  3455. /**
  3456. * Continuously decodes from video input.
  3457. */
  3458. decodeContinuously(element, callbackFn) {
  3459. this._stopContinuousDecode = false;
  3460. const loop = () => {
  3461. if (this._stopContinuousDecode) {
  3462. this._stopContinuousDecode = undefined;
  3463. return;
  3464. }
  3465. try {
  3466. const result = this.decode(element);
  3467. callbackFn(result, null);
  3468. setTimeout(loop, this.timeBetweenScansMillis);
  3469. }
  3470. catch (e) {
  3471. callbackFn(null, e);
  3472. const isChecksumOrFormatError = e instanceof ChecksumException || e instanceof FormatException;
  3473. const isNotFound = e instanceof NotFoundException;
  3474. if (isChecksumOrFormatError || isNotFound) {
  3475. // trying again
  3476. setTimeout(loop, this._timeBetweenDecodingAttempts);
  3477. }
  3478. }
  3479. };
  3480. loop();
  3481. }
  3482. /**
  3483. * Gets the BinaryBitmap for ya! (and decodes it)
  3484. */
  3485. decode(element) {
  3486. // get binary bitmap for decode function
  3487. const binaryBitmap = this.createBinaryBitmap(element);
  3488. return this.decodeBitmap(binaryBitmap);
  3489. }
  3490. /**
  3491. * Creates a binaryBitmap based in some image source.
  3492. *
  3493. * @param mediaElement HTML element containing drawable image source.
  3494. */
  3495. createBinaryBitmap(mediaElement) {
  3496. const ctx = this.getCaptureCanvasContext(mediaElement);
  3497. if (mediaElement instanceof HTMLVideoElement) {
  3498. this.drawFrameOnCanvas(mediaElement);
  3499. }
  3500. else {
  3501. this.drawImageOnCanvas(mediaElement);
  3502. }
  3503. const canvas = this.getCaptureCanvas(mediaElement);
  3504. const luminanceSource = new HTMLCanvasElementLuminanceSource(canvas);
  3505. const hybridBinarizer = new HybridBinarizer(luminanceSource);
  3506. return new BinaryBitmap(hybridBinarizer);
  3507. }
  3508. /**
  3509. *
  3510. */
  3511. getCaptureCanvasContext(mediaElement) {
  3512. if (!this.captureCanvasContext) {
  3513. const elem = this.getCaptureCanvas(mediaElement);
  3514. let ctx;
  3515. try {
  3516. ctx = elem.getContext('2d', { willReadFrequently: true });
  3517. }
  3518. catch (e) {
  3519. ctx = elem.getContext('2d');
  3520. }
  3521. this.captureCanvasContext = ctx;
  3522. }
  3523. return this.captureCanvasContext;
  3524. }
  3525. /**
  3526. *
  3527. */
  3528. getCaptureCanvas(mediaElement) {
  3529. if (!this.captureCanvas) {
  3530. const elem = this.createCaptureCanvas(mediaElement);
  3531. this.captureCanvas = elem;
  3532. }
  3533. return this.captureCanvas;
  3534. }
  3535. /**
  3536. * Overwriting this allows you to manipulate the next frame in anyway you want before decode.
  3537. */
  3538. drawFrameOnCanvas(srcElement, dimensions = {
  3539. sx: 0,
  3540. sy: 0,
  3541. sWidth: srcElement.videoWidth,
  3542. sHeight: srcElement.videoHeight,
  3543. dx: 0,
  3544. dy: 0,
  3545. dWidth: srcElement.videoWidth,
  3546. dHeight: srcElement.videoHeight,
  3547. }, canvasElementContext = this.captureCanvasContext) {
  3548. canvasElementContext.drawImage(srcElement, dimensions.sx, dimensions.sy, dimensions.sWidth, dimensions.sHeight, dimensions.dx, dimensions.dy, dimensions.dWidth, dimensions.dHeight);
  3549. }
  3550. /**
  3551. * Ovewriting this allows you to manipulate the snapshot image in anyway you want before decode.
  3552. */
  3553. drawImageOnCanvas(srcElement, dimensions = {
  3554. sx: 0,
  3555. sy: 0,
  3556. sWidth: srcElement.naturalWidth,
  3557. sHeight: srcElement.naturalHeight,
  3558. dx: 0,
  3559. dy: 0,
  3560. dWidth: srcElement.naturalWidth,
  3561. dHeight: srcElement.naturalHeight,
  3562. }, canvasElementContext = this.captureCanvasContext) {
  3563. canvasElementContext.drawImage(srcElement, dimensions.sx, dimensions.sy, dimensions.sWidth, dimensions.sHeight, dimensions.dx, dimensions.dy, dimensions.dWidth, dimensions.dHeight);
  3564. }
  3565. /**
  3566. * Call the encapsulated readers decode
  3567. */
  3568. decodeBitmap(binaryBitmap) {
  3569. return this.reader.decode(binaryBitmap, this._hints);
  3570. }
  3571. /**
  3572. * 🖌 Prepares the canvas for capture and scan frames.
  3573. */
  3574. createCaptureCanvas(mediaElement) {
  3575. if (typeof document === 'undefined') {
  3576. this._destroyCaptureCanvas();
  3577. return null;
  3578. }
  3579. const canvasElement = document.createElement('canvas');
  3580. let width;
  3581. let height;
  3582. if (typeof mediaElement !== 'undefined') {
  3583. if (mediaElement instanceof HTMLVideoElement) {
  3584. width = mediaElement.videoWidth;
  3585. height = mediaElement.videoHeight;
  3586. }
  3587. else if (mediaElement instanceof HTMLImageElement) {
  3588. width = mediaElement.naturalWidth || mediaElement.width;
  3589. height = mediaElement.naturalHeight || mediaElement.height;
  3590. }
  3591. }
  3592. canvasElement.style.width = width + 'px';
  3593. canvasElement.style.height = height + 'px';
  3594. canvasElement.width = width;
  3595. canvasElement.height = height;
  3596. return canvasElement;
  3597. }
  3598. /**
  3599. * Stops the continuous scan and cleans the stream.
  3600. */
  3601. stopStreams() {
  3602. if (this.stream) {
  3603. this.stream.getVideoTracks().forEach(t => t.stop());
  3604. this.stream = undefined;
  3605. }
  3606. if (this._stopAsyncDecode === false) {
  3607. this.stopAsyncDecode();
  3608. }
  3609. if (this._stopContinuousDecode === false) {
  3610. this.stopContinuousDecode();
  3611. }
  3612. }
  3613. /**
  3614. * Resets the code reader to the initial state. Cancels any ongoing barcode scanning from video or camera.
  3615. *
  3616. * @memberOf BrowserCodeReader
  3617. */
  3618. reset() {
  3619. // stops the camera, preview and scan 🔴
  3620. this.stopStreams();
  3621. // clean and forget about HTML elements
  3622. this._destroyVideoElement();
  3623. this._destroyImageElement();
  3624. this._destroyCaptureCanvas();
  3625. }
  3626. _destroyVideoElement() {
  3627. if (!this.videoElement) {
  3628. return;
  3629. }
  3630. // first gives freedon to the element 🕊
  3631. if (typeof this.videoEndedListener !== 'undefined') {
  3632. this.videoElement.removeEventListener('ended', this.videoEndedListener);
  3633. }
  3634. if (typeof this.videoPlayingEventListener !== 'undefined') {
  3635. this.videoElement.removeEventListener('playing', this.videoPlayingEventListener);
  3636. }
  3637. if (typeof this.videoCanPlayListener !== 'undefined') {
  3638. this.videoElement.removeEventListener('loadedmetadata', this.videoCanPlayListener);
  3639. }
  3640. // then forgets about that element 😢
  3641. this.cleanVideoSource(this.videoElement);
  3642. this.videoElement = undefined;
  3643. }
  3644. _destroyImageElement() {
  3645. if (!this.imageElement) {
  3646. return;
  3647. }
  3648. // first gives freedon to the element 🕊
  3649. if (undefined !== this.imageLoadedListener) {
  3650. this.imageElement.removeEventListener('load', this.imageLoadedListener);
  3651. }
  3652. // then forget about that element 😢
  3653. this.imageElement.src = undefined;
  3654. this.imageElement.removeAttribute('src');
  3655. this.imageElement = undefined;
  3656. }
  3657. /**
  3658. * Cleans canvas references 🖌
  3659. */
  3660. _destroyCaptureCanvas() {
  3661. // then forget about that element 😢
  3662. this.captureCanvasContext = undefined;
  3663. this.captureCanvas = undefined;
  3664. }
  3665. /**
  3666. * Defines what the videoElement src will be.
  3667. *
  3668. * @param videoElement
  3669. * @param stream
  3670. */
  3671. addVideoSource(videoElement, stream) {
  3672. // Older browsers may not have `srcObject`
  3673. try {
  3674. // @note Throws Exception if interrupted by a new loaded request
  3675. videoElement.srcObject = stream;
  3676. }
  3677. catch (err) {
  3678. // @note Avoid using this in new browsers, as it is going away.
  3679. // @ts-ignore
  3680. videoElement.src = URL.createObjectURL(stream);
  3681. }
  3682. }
  3683. /**
  3684. * Unbinds a HTML video src property.
  3685. *
  3686. * @param videoElement
  3687. */
  3688. cleanVideoSource(videoElement) {
  3689. try {
  3690. videoElement.srcObject = null;
  3691. }
  3692. catch (err) {
  3693. videoElement.src = '';
  3694. }
  3695. this.videoElement.removeAttribute('src');
  3696. }
  3697. }
  3698. /*
  3699. * Copyright 2007 ZXing authors
  3700. *
  3701. * Licensed under the Apache License, Version 2.0 (the "License");
  3702. * you may not use this file except in compliance with the License.
  3703. * You may obtain a copy of the License at
  3704. *
  3705. * http://www.apache.org/licenses/LICENSE-2.0
  3706. *
  3707. * Unless required by applicable law or agreed to in writing, software
  3708. * distributed under the License is distributed on an "AS IS" BASIS,
  3709. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3710. * See the License for the specific language governing permissions and
  3711. * limitations under the License.
  3712. */
  3713. /**
  3714. * <p>Encapsulates the result of decoding a barcode within an image.</p>
  3715. *
  3716. * @author Sean Owen
  3717. */
  3718. class Result {
  3719. // public constructor(private text: string,
  3720. // Uint8Array rawBytes,
  3721. // ResultPoconst resultPoints: Int32Array,
  3722. // BarcodeFormat format) {
  3723. // this(text, rawBytes, resultPoints, format, System.currentTimeMillis())
  3724. // }
  3725. // public constructor(text: string,
  3726. // Uint8Array rawBytes,
  3727. // ResultPoconst resultPoints: Int32Array,
  3728. // BarcodeFormat format,
  3729. // long timestamp) {
  3730. // this(text, rawBytes, rawBytes == null ? 0 : 8 * rawBytes.length,
  3731. // resultPoints, format, timestamp)
  3732. // }
  3733. constructor(text, rawBytes, numBits = rawBytes == null ? 0 : 8 * rawBytes.length, resultPoints, format, timestamp = System.currentTimeMillis()) {
  3734. this.text = text;
  3735. this.rawBytes = rawBytes;
  3736. this.numBits = numBits;
  3737. this.resultPoints = resultPoints;
  3738. this.format = format;
  3739. this.timestamp = timestamp;
  3740. this.text = text;
  3741. this.rawBytes = rawBytes;
  3742. if (undefined === numBits || null === numBits) {
  3743. this.numBits = (rawBytes === null || rawBytes === undefined) ? 0 : 8 * rawBytes.length;
  3744. }
  3745. else {
  3746. this.numBits = numBits;
  3747. }
  3748. this.resultPoints = resultPoints;
  3749. this.format = format;
  3750. this.resultMetadata = null;
  3751. if (undefined === timestamp || null === timestamp) {
  3752. this.timestamp = System.currentTimeMillis();
  3753. }
  3754. else {
  3755. this.timestamp = timestamp;
  3756. }
  3757. }
  3758. /**
  3759. * @return raw text encoded by the barcode
  3760. */
  3761. getText() {
  3762. return this.text;
  3763. }
  3764. /**
  3765. * @return raw bytes encoded by the barcode, if applicable, otherwise {@code null}
  3766. */
  3767. getRawBytes() {
  3768. return this.rawBytes;
  3769. }
  3770. /**
  3771. * @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length
  3772. * @since 3.3.0
  3773. */
  3774. getNumBits() {
  3775. return this.numBits;
  3776. }
  3777. /**
  3778. * @return points related to the barcode in the image. These are typically points
  3779. * identifying finder patterns or the corners of the barcode. The exact meaning is
  3780. * specific to the type of barcode that was decoded.
  3781. */
  3782. getResultPoints() {
  3783. return this.resultPoints;
  3784. }
  3785. /**
  3786. * @return {@link BarcodeFormat} representing the format of the barcode that was decoded
  3787. */
  3788. getBarcodeFormat() {
  3789. return this.format;
  3790. }
  3791. /**
  3792. * @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be
  3793. * {@code null}. This contains optional metadata about what was detected about the barcode,
  3794. * like orientation.
  3795. */
  3796. getResultMetadata() {
  3797. return this.resultMetadata;
  3798. }
  3799. putMetadata(type, value) {
  3800. if (this.resultMetadata === null) {
  3801. this.resultMetadata = new Map();
  3802. }
  3803. this.resultMetadata.set(type, value);
  3804. }
  3805. putAllMetadata(metadata) {
  3806. if (metadata !== null) {
  3807. if (this.resultMetadata === null) {
  3808. this.resultMetadata = metadata;
  3809. }
  3810. else {
  3811. this.resultMetadata = new Map(metadata);
  3812. }
  3813. }
  3814. }
  3815. addResultPoints(newPoints) {
  3816. const oldPoints = this.resultPoints;
  3817. if (oldPoints === null) {
  3818. this.resultPoints = newPoints;
  3819. }
  3820. else if (newPoints !== null && newPoints.length > 0) {
  3821. const allPoints = new Array(oldPoints.length + newPoints.length);
  3822. System.arraycopy(oldPoints, 0, allPoints, 0, oldPoints.length);
  3823. System.arraycopy(newPoints, 0, allPoints, oldPoints.length, newPoints.length);
  3824. this.resultPoints = allPoints;
  3825. }
  3826. }
  3827. getTimestamp() {
  3828. return this.timestamp;
  3829. }
  3830. /*@Override*/
  3831. toString() {
  3832. return this.text;
  3833. }
  3834. }
  3835. /*
  3836. * Direct port to TypeScript of ZXing by Adrian Toșcă
  3837. */
  3838. /*
  3839. * Copyright 2009 ZXing authors
  3840. *
  3841. * Licensed under the Apache License, Version 2.0 (the "License");
  3842. * you may not use this file except in compliance with the License.
  3843. * You may obtain a copy of the License at
  3844. *
  3845. * http://www.apache.org/licenses/LICENSE-2.0
  3846. *
  3847. * Unless required by applicable law or agreed to in writing, software
  3848. * distributed under the License is distributed on an "AS IS" BASIS,
  3849. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3850. * See the License for the specific language governing permissions and
  3851. * limitations under the License.
  3852. */
  3853. /*namespace com.google.zxing {*/
  3854. /**
  3855. * Enumerates barcode formats known to this package. Please keep alphabetized.
  3856. *
  3857. * @author Sean Owen
  3858. */
  3859. var BarcodeFormat;
  3860. (function (BarcodeFormat) {
  3861. /** Aztec 2D barcode format. */
  3862. BarcodeFormat[BarcodeFormat["AZTEC"] = 0] = "AZTEC";
  3863. /** CODABAR 1D format. */
  3864. BarcodeFormat[BarcodeFormat["CODABAR"] = 1] = "CODABAR";
  3865. /** Code 39 1D format. */
  3866. BarcodeFormat[BarcodeFormat["CODE_39"] = 2] = "CODE_39";
  3867. /** Code 93 1D format. */
  3868. BarcodeFormat[BarcodeFormat["CODE_93"] = 3] = "CODE_93";
  3869. /** Code 128 1D format. */
  3870. BarcodeFormat[BarcodeFormat["CODE_128"] = 4] = "CODE_128";
  3871. /** Data Matrix 2D barcode format. */
  3872. BarcodeFormat[BarcodeFormat["DATA_MATRIX"] = 5] = "DATA_MATRIX";
  3873. /** EAN-8 1D format. */
  3874. BarcodeFormat[BarcodeFormat["EAN_8"] = 6] = "EAN_8";
  3875. /** EAN-13 1D format. */
  3876. BarcodeFormat[BarcodeFormat["EAN_13"] = 7] = "EAN_13";
  3877. /** ITF (Interleaved Two of Five) 1D format. */
  3878. BarcodeFormat[BarcodeFormat["ITF"] = 8] = "ITF";
  3879. /** MaxiCode 2D barcode format. */
  3880. BarcodeFormat[BarcodeFormat["MAXICODE"] = 9] = "MAXICODE";
  3881. /** PDF417 format. */
  3882. BarcodeFormat[BarcodeFormat["PDF_417"] = 10] = "PDF_417";
  3883. /** QR Code 2D barcode format. */
  3884. BarcodeFormat[BarcodeFormat["QR_CODE"] = 11] = "QR_CODE";
  3885. /** RSS 14 */
  3886. BarcodeFormat[BarcodeFormat["RSS_14"] = 12] = "RSS_14";
  3887. /** RSS EXPANDED */
  3888. BarcodeFormat[BarcodeFormat["RSS_EXPANDED"] = 13] = "RSS_EXPANDED";
  3889. /** UPC-A 1D format. */
  3890. BarcodeFormat[BarcodeFormat["UPC_A"] = 14] = "UPC_A";
  3891. /** UPC-E 1D format. */
  3892. BarcodeFormat[BarcodeFormat["UPC_E"] = 15] = "UPC_E";
  3893. /** UPC/EAN extension format. Not a stand-alone format. */
  3894. BarcodeFormat[BarcodeFormat["UPC_EAN_EXTENSION"] = 16] = "UPC_EAN_EXTENSION";
  3895. })(BarcodeFormat || (BarcodeFormat = {}));
  3896. var BarcodeFormat$1 = BarcodeFormat;
  3897. /*
  3898. * Copyright 2008 ZXing authors
  3899. *
  3900. * Licensed under the Apache License, Version 2.0 (the "License");
  3901. * you may not use this file except in compliance with the License.
  3902. * You may obtain a copy of the License at
  3903. *
  3904. * http://www.apache.org/licenses/LICENSE-2.0
  3905. *
  3906. * Unless required by applicable law or agreed to in writing, software
  3907. * distributed under the License is distributed on an "AS IS" BASIS,
  3908. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3909. * See the License for the specific language governing permissions and
  3910. * limitations under the License.
  3911. */
  3912. /*namespace com.google.zxing {*/
  3913. /**
  3914. * Represents some type of metadata about the result of the decoding that the decoder
  3915. * wishes to communicate back to the caller.
  3916. *
  3917. * @author Sean Owen
  3918. */
  3919. var ResultMetadataType;
  3920. (function (ResultMetadataType) {
  3921. /**
  3922. * Unspecified, application-specific metadata. Maps to an unspecified {@link Object}.
  3923. */
  3924. ResultMetadataType[ResultMetadataType["OTHER"] = 0] = "OTHER";
  3925. /**
  3926. * Denotes the likely approximate orientation of the barcode in the image. This value
  3927. * is given as degrees rotated clockwise from the normal, upright orientation.
  3928. * For example a 1D barcode which was found by reading top-to-bottom would be
  3929. * said to have orientation "90". This key maps to an {@link Integer} whose
  3930. * value is in the range [0,360).
  3931. */
  3932. ResultMetadataType[ResultMetadataType["ORIENTATION"] = 1] = "ORIENTATION";
  3933. /**
  3934. * <p>2D barcode formats typically encode text, but allow for a sort of 'byte mode'
  3935. * which is sometimes used to encode binary data. While {@link Result} makes available
  3936. * the complete raw bytes in the barcode for these formats, it does not offer the bytes
  3937. * from the byte segments alone.</p>
  3938. *
  3939. * <p>This maps to a {@link java.util.List} of byte arrays corresponding to the
  3940. * raw bytes in the byte segments in the barcode, in order.</p>
  3941. */
  3942. ResultMetadataType[ResultMetadataType["BYTE_SEGMENTS"] = 2] = "BYTE_SEGMENTS";
  3943. /**
  3944. * Error correction level used, if applicable. The value type depends on the
  3945. * format, but is typically a String.
  3946. */
  3947. ResultMetadataType[ResultMetadataType["ERROR_CORRECTION_LEVEL"] = 3] = "ERROR_CORRECTION_LEVEL";
  3948. /**
  3949. * For some periodicals, indicates the issue number as an {@link Integer}.
  3950. */
  3951. ResultMetadataType[ResultMetadataType["ISSUE_NUMBER"] = 4] = "ISSUE_NUMBER";
  3952. /**
  3953. * For some products, indicates the suggested retail price in the barcode as a
  3954. * formatted {@link String}.
  3955. */
  3956. ResultMetadataType[ResultMetadataType["SUGGESTED_PRICE"] = 5] = "SUGGESTED_PRICE";
  3957. /**
  3958. * For some products, the possible country of manufacture as a {@link String} denoting the
  3959. * ISO country code. Some map to multiple possible countries, like "US/CA".
  3960. */
  3961. ResultMetadataType[ResultMetadataType["POSSIBLE_COUNTRY"] = 6] = "POSSIBLE_COUNTRY";
  3962. /**
  3963. * For some products, the extension text
  3964. */
  3965. ResultMetadataType[ResultMetadataType["UPC_EAN_EXTENSION"] = 7] = "UPC_EAN_EXTENSION";
  3966. /**
  3967. * PDF417-specific metadata
  3968. */
  3969. ResultMetadataType[ResultMetadataType["PDF417_EXTRA_METADATA"] = 8] = "PDF417_EXTRA_METADATA";
  3970. /**
  3971. * If the code format supports structured append and the current scanned code is part of one then the
  3972. * sequence number is given with it.
  3973. */
  3974. ResultMetadataType[ResultMetadataType["STRUCTURED_APPEND_SEQUENCE"] = 9] = "STRUCTURED_APPEND_SEQUENCE";
  3975. /**
  3976. * If the code format supports structured append and the current scanned code is part of one then the
  3977. * parity is given with it.
  3978. */
  3979. ResultMetadataType[ResultMetadataType["STRUCTURED_APPEND_PARITY"] = 10] = "STRUCTURED_APPEND_PARITY";
  3980. })(ResultMetadataType || (ResultMetadataType = {}));
  3981. var ResultMetadataType$1 = ResultMetadataType;
  3982. /*
  3983. * Copyright 2007 ZXing authors
  3984. *
  3985. * Licensed under the Apache License, Version 2.0 (the "License");
  3986. * you may not use this file except in compliance with the License.
  3987. * You may obtain a copy of the License at
  3988. *
  3989. * http://www.apache.org/licenses/LICENSE-2.0
  3990. *
  3991. * Unless required by applicable law or agreed to in writing, software
  3992. * distributed under the License is distributed on an "AS IS" BASIS,
  3993. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3994. * See the License for the specific language governing permissions and
  3995. * limitations under the License.
  3996. */
  3997. /*namespace com.google.zxing.common {*/
  3998. /*import java.util.List;*/
  3999. /**
  4000. * <p>Encapsulates the result of decoding a matrix of bits. This typically
  4001. * applies to 2D barcode formats. For now it contains the raw bytes obtained,
  4002. * as well as a String interpretation of those bytes, if applicable.</p>
  4003. *
  4004. * @author Sean Owen
  4005. */
  4006. class DecoderResult {
  4007. // public constructor(rawBytes: Uint8Array,
  4008. // text: string,
  4009. // List<Uint8Array> byteSegments,
  4010. // String ecLevel) {
  4011. // this(rawBytes, text, byteSegments, ecLevel, -1, -1)
  4012. // }
  4013. constructor(rawBytes, text, byteSegments, ecLevel, structuredAppendSequenceNumber = -1, structuredAppendParity = -1) {
  4014. this.rawBytes = rawBytes;
  4015. this.text = text;
  4016. this.byteSegments = byteSegments;
  4017. this.ecLevel = ecLevel;
  4018. this.structuredAppendSequenceNumber = structuredAppendSequenceNumber;
  4019. this.structuredAppendParity = structuredAppendParity;
  4020. this.numBits = (rawBytes === undefined || rawBytes === null) ? 0 : 8 * rawBytes.length;
  4021. }
  4022. /**
  4023. * @return raw bytes representing the result, or {@code null} if not applicable
  4024. */
  4025. getRawBytes() {
  4026. return this.rawBytes;
  4027. }
  4028. /**
  4029. * @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length
  4030. * @since 3.3.0
  4031. */
  4032. getNumBits() {
  4033. return this.numBits;
  4034. }
  4035. /**
  4036. * @param numBits overrides the number of bits that are valid in {@link #getRawBytes()}
  4037. * @since 3.3.0
  4038. */
  4039. setNumBits(numBits /*int*/) {
  4040. this.numBits = numBits;
  4041. }
  4042. /**
  4043. * @return text representation of the result
  4044. */
  4045. getText() {
  4046. return this.text;
  4047. }
  4048. /**
  4049. * @return list of byte segments in the result, or {@code null} if not applicable
  4050. */
  4051. getByteSegments() {
  4052. return this.byteSegments;
  4053. }
  4054. /**
  4055. * @return name of error correction level used, or {@code null} if not applicable
  4056. */
  4057. getECLevel() {
  4058. return this.ecLevel;
  4059. }
  4060. /**
  4061. * @return number of errors corrected, or {@code null} if not applicable
  4062. */
  4063. getErrorsCorrected() {
  4064. return this.errorsCorrected;
  4065. }
  4066. setErrorsCorrected(errorsCorrected /*Integer*/) {
  4067. this.errorsCorrected = errorsCorrected;
  4068. }
  4069. /**
  4070. * @return number of erasures corrected, or {@code null} if not applicable
  4071. */
  4072. getErasures() {
  4073. return this.erasures;
  4074. }
  4075. setErasures(erasures /*Integer*/) {
  4076. this.erasures = erasures;
  4077. }
  4078. /**
  4079. * @return arbitrary additional metadata
  4080. */
  4081. getOther() {
  4082. return this.other;
  4083. }
  4084. setOther(other) {
  4085. this.other = other;
  4086. }
  4087. hasStructuredAppend() {
  4088. return this.structuredAppendParity >= 0 && this.structuredAppendSequenceNumber >= 0;
  4089. }
  4090. getStructuredAppendParity() {
  4091. return this.structuredAppendParity;
  4092. }
  4093. getStructuredAppendSequenceNumber() {
  4094. return this.structuredAppendSequenceNumber;
  4095. }
  4096. }
  4097. /*
  4098. * Copyright 2007 ZXing authors
  4099. *
  4100. * Licensed under the Apache License, Version 2.0 (the "License");
  4101. * you may not use this file except in compliance with the License.
  4102. * You may obtain a copy of the License at
  4103. *
  4104. * http://www.apache.org/licenses/LICENSE-2.0
  4105. *
  4106. * Unless required by applicable law or agreed to in writing, software
  4107. * distributed under the License is distributed on an "AS IS" BASIS,
  4108. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4109. * See the License for the specific language governing permissions and
  4110. * limitations under the License.
  4111. */
  4112. /**
  4113. * <p>This class contains utility methods for performing mathematical operations over
  4114. * the Galois Fields. Operations use a given primitive polynomial in calculations.</p>
  4115. *
  4116. * <p>Throughout this package, elements of the GF are represented as an {@code int}
  4117. * for convenience and speed (but at the cost of memory).
  4118. * </p>
  4119. *
  4120. * @author Sean Owen
  4121. * @author David Olivier
  4122. */
  4123. class AbstractGenericGF {
  4124. /**
  4125. * @return 2 to the power of a in GF(size)
  4126. */
  4127. exp(a) {
  4128. return this.expTable[a];
  4129. }
  4130. /**
  4131. * @return base 2 log of a in GF(size)
  4132. */
  4133. log(a /*int*/) {
  4134. if (a === 0) {
  4135. throw new IllegalArgumentException();
  4136. }
  4137. return this.logTable[a];
  4138. }
  4139. /**
  4140. * Implements both addition and subtraction -- they are the same in GF(size).
  4141. *
  4142. * @return sum/difference of a and b
  4143. */
  4144. static addOrSubtract(a /*int*/, b /*int*/) {
  4145. return a ^ b;
  4146. }
  4147. }
  4148. /*
  4149. * Copyright 2007 ZXing authors
  4150. *
  4151. * Licensed under the Apache License, Version 2.0 (the "License");
  4152. * you may not use this file except in compliance with the License.
  4153. * You may obtain a copy of the License at
  4154. *
  4155. * http://www.apache.org/licenses/LICENSE-2.0
  4156. *
  4157. * Unless required by applicable law or agreed to in writing, software
  4158. * distributed under the License is distributed on an "AS IS" BASIS,
  4159. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4160. * See the License for the specific language governing permissions and
  4161. * limitations under the License.
  4162. */
  4163. /**
  4164. * <p>Represents a polynomial whose coefficients are elements of a GF.
  4165. * Instances of this class are immutable.</p>
  4166. *
  4167. * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
  4168. * port of his C++ Reed-Solomon implementation.</p>
  4169. *
  4170. * @author Sean Owen
  4171. */
  4172. class GenericGFPoly {
  4173. /**
  4174. * @param field the {@link GenericGF} instance representing the field to use
  4175. * to perform computations
  4176. * @param coefficients coefficients as ints representing elements of GF(size), arranged
  4177. * from most significant (highest-power term) coefficient to least significant
  4178. * @throws IllegalArgumentException if argument is null or empty,
  4179. * or if leading coefficient is 0 and this is not a
  4180. * constant polynomial (that is, it is not the monomial "0")
  4181. */
  4182. constructor(field, coefficients) {
  4183. if (coefficients.length === 0) {
  4184. throw new IllegalArgumentException();
  4185. }
  4186. this.field = field;
  4187. const coefficientsLength = coefficients.length;
  4188. if (coefficientsLength > 1 && coefficients[0] === 0) {
  4189. // Leading term must be non-zero for anything except the constant polynomial "0"
  4190. let firstNonZero = 1;
  4191. while (firstNonZero < coefficientsLength && coefficients[firstNonZero] === 0) {
  4192. firstNonZero++;
  4193. }
  4194. if (firstNonZero === coefficientsLength) {
  4195. this.coefficients = Int32Array.from([0]);
  4196. }
  4197. else {
  4198. this.coefficients = new Int32Array(coefficientsLength - firstNonZero);
  4199. System.arraycopy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length);
  4200. }
  4201. }
  4202. else {
  4203. this.coefficients = coefficients;
  4204. }
  4205. }
  4206. getCoefficients() {
  4207. return this.coefficients;
  4208. }
  4209. /**
  4210. * @return degree of this polynomial
  4211. */
  4212. getDegree() {
  4213. return this.coefficients.length - 1;
  4214. }
  4215. /**
  4216. * @return true iff this polynomial is the monomial "0"
  4217. */
  4218. isZero() {
  4219. return this.coefficients[0] === 0;
  4220. }
  4221. /**
  4222. * @return coefficient of x^degree term in this polynomial
  4223. */
  4224. getCoefficient(degree /*int*/) {
  4225. return this.coefficients[this.coefficients.length - 1 - degree];
  4226. }
  4227. /**
  4228. * @return evaluation of this polynomial at a given point
  4229. */
  4230. evaluateAt(a /*int*/) {
  4231. if (a === 0) {
  4232. // Just return the x^0 coefficient
  4233. return this.getCoefficient(0);
  4234. }
  4235. const coefficients = this.coefficients;
  4236. let result;
  4237. if (a === 1) {
  4238. // Just the sum of the coefficients
  4239. result = 0;
  4240. for (let i = 0, length = coefficients.length; i !== length; i++) {
  4241. const coefficient = coefficients[i];
  4242. result = AbstractGenericGF.addOrSubtract(result, coefficient);
  4243. }
  4244. return result;
  4245. }
  4246. result = coefficients[0];
  4247. const size = coefficients.length;
  4248. const field = this.field;
  4249. for (let i = 1; i < size; i++) {
  4250. result = AbstractGenericGF.addOrSubtract(field.multiply(a, result), coefficients[i]);
  4251. }
  4252. return result;
  4253. }
  4254. addOrSubtract(other) {
  4255. if (!this.field.equals(other.field)) {
  4256. throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');
  4257. }
  4258. if (this.isZero()) {
  4259. return other;
  4260. }
  4261. if (other.isZero()) {
  4262. return this;
  4263. }
  4264. let smallerCoefficients = this.coefficients;
  4265. let largerCoefficients = other.coefficients;
  4266. if (smallerCoefficients.length > largerCoefficients.length) {
  4267. const temp = smallerCoefficients;
  4268. smallerCoefficients = largerCoefficients;
  4269. largerCoefficients = temp;
  4270. }
  4271. let sumDiff = new Int32Array(largerCoefficients.length);
  4272. const lengthDiff = largerCoefficients.length - smallerCoefficients.length;
  4273. // Copy high-order terms only found in higher-degree polynomial's coefficients
  4274. System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
  4275. for (let i = lengthDiff; i < largerCoefficients.length; i++) {
  4276. sumDiff[i] = AbstractGenericGF.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
  4277. }
  4278. return new GenericGFPoly(this.field, sumDiff);
  4279. }
  4280. multiply(other) {
  4281. if (!this.field.equals(other.field)) {
  4282. throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');
  4283. }
  4284. if (this.isZero() || other.isZero()) {
  4285. return this.field.getZero();
  4286. }
  4287. const aCoefficients = this.coefficients;
  4288. const aLength = aCoefficients.length;
  4289. const bCoefficients = other.coefficients;
  4290. const bLength = bCoefficients.length;
  4291. const product = new Int32Array(aLength + bLength - 1);
  4292. const field = this.field;
  4293. for (let i = 0; i < aLength; i++) {
  4294. const aCoeff = aCoefficients[i];
  4295. for (let j = 0; j < bLength; j++) {
  4296. product[i + j] = AbstractGenericGF.addOrSubtract(product[i + j], field.multiply(aCoeff, bCoefficients[j]));
  4297. }
  4298. }
  4299. return new GenericGFPoly(field, product);
  4300. }
  4301. multiplyScalar(scalar /*int*/) {
  4302. if (scalar === 0) {
  4303. return this.field.getZero();
  4304. }
  4305. if (scalar === 1) {
  4306. return this;
  4307. }
  4308. const size = this.coefficients.length;
  4309. const field = this.field;
  4310. const product = new Int32Array(size);
  4311. const coefficients = this.coefficients;
  4312. for (let i = 0; i < size; i++) {
  4313. product[i] = field.multiply(coefficients[i], scalar);
  4314. }
  4315. return new GenericGFPoly(field, product);
  4316. }
  4317. multiplyByMonomial(degree /*int*/, coefficient /*int*/) {
  4318. if (degree < 0) {
  4319. throw new IllegalArgumentException();
  4320. }
  4321. if (coefficient === 0) {
  4322. return this.field.getZero();
  4323. }
  4324. const coefficients = this.coefficients;
  4325. const size = coefficients.length;
  4326. const product = new Int32Array(size + degree);
  4327. const field = this.field;
  4328. for (let i = 0; i < size; i++) {
  4329. product[i] = field.multiply(coefficients[i], coefficient);
  4330. }
  4331. return new GenericGFPoly(field, product);
  4332. }
  4333. divide(other) {
  4334. if (!this.field.equals(other.field)) {
  4335. throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');
  4336. }
  4337. if (other.isZero()) {
  4338. throw new IllegalArgumentException('Divide by 0');
  4339. }
  4340. const field = this.field;
  4341. let quotient = field.getZero();
  4342. let remainder = this;
  4343. const denominatorLeadingTerm = other.getCoefficient(other.getDegree());
  4344. const inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm);
  4345. while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) {
  4346. const degreeDifference = remainder.getDegree() - other.getDegree();
  4347. const scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm);
  4348. const term = other.multiplyByMonomial(degreeDifference, scale);
  4349. const iterationQuotient = field.buildMonomial(degreeDifference, scale);
  4350. quotient = quotient.addOrSubtract(iterationQuotient);
  4351. remainder = remainder.addOrSubtract(term);
  4352. }
  4353. return [quotient, remainder];
  4354. }
  4355. /*@Override*/
  4356. toString() {
  4357. let result = '';
  4358. for (let degree = this.getDegree(); degree >= 0; degree--) {
  4359. let coefficient = this.getCoefficient(degree);
  4360. if (coefficient !== 0) {
  4361. if (coefficient < 0) {
  4362. result += ' - ';
  4363. coefficient = -coefficient;
  4364. }
  4365. else {
  4366. if (result.length > 0) {
  4367. result += ' + ';
  4368. }
  4369. }
  4370. if (degree === 0 || coefficient !== 1) {
  4371. const alphaPower = this.field.log(coefficient);
  4372. if (alphaPower === 0) {
  4373. result += '1';
  4374. }
  4375. else if (alphaPower === 1) {
  4376. result += 'a';
  4377. }
  4378. else {
  4379. result += 'a^';
  4380. result += alphaPower;
  4381. }
  4382. }
  4383. if (degree !== 0) {
  4384. if (degree === 1) {
  4385. result += 'x';
  4386. }
  4387. else {
  4388. result += 'x^';
  4389. result += degree;
  4390. }
  4391. }
  4392. }
  4393. }
  4394. return result;
  4395. }
  4396. }
  4397. /**
  4398. * Custom Error class of type Exception.
  4399. */
  4400. class ArithmeticException extends Exception {
  4401. }
  4402. ArithmeticException.kind = 'ArithmeticException';
  4403. /*
  4404. * Copyright 2007 ZXing authors
  4405. *
  4406. * Licensed under the Apache License, Version 2.0 (the "License");
  4407. * you may not use this file except in compliance with the License.
  4408. * You may obtain a copy of the License at
  4409. *
  4410. * http://www.apache.org/licenses/LICENSE-2.0
  4411. *
  4412. * Unless required by applicable law or agreed to in writing, software
  4413. * distributed under the License is distributed on an "AS IS" BASIS,
  4414. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4415. * See the License for the specific language governing permissions and
  4416. * limitations under the License.
  4417. */
  4418. /**
  4419. * <p>This class contains utility methods for performing mathematical operations over
  4420. * the Galois Fields. Operations use a given primitive polynomial in calculations.</p>
  4421. *
  4422. * <p>Throughout this package, elements of the GF are represented as an {@code int}
  4423. * for convenience and speed (but at the cost of memory).
  4424. * </p>
  4425. *
  4426. * @author Sean Owen
  4427. * @author David Olivier
  4428. */
  4429. class GenericGF extends AbstractGenericGF {
  4430. /**
  4431. * Create a representation of GF(size) using the given primitive polynomial.
  4432. *
  4433. * @param primitive irreducible polynomial whose coefficients are represented by
  4434. * the bits of an int, where the least-significant bit represents the constant
  4435. * coefficient
  4436. * @param size the size of the field
  4437. * @param b the factor b in the generator polynomial can be 0- or 1-based
  4438. * (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))).
  4439. * In most cases it should be 1, but for QR code it is 0.
  4440. */
  4441. constructor(primitive /*int*/, size /*int*/, generatorBase /*int*/) {
  4442. super();
  4443. this.primitive = primitive;
  4444. this.size = size;
  4445. this.generatorBase = generatorBase;
  4446. const expTable = new Int32Array(size);
  4447. let x = 1;
  4448. for (let i = 0; i < size; i++) {
  4449. expTable[i] = x;
  4450. x *= 2; // we're assuming the generator alpha is 2
  4451. if (x >= size) {
  4452. x ^= primitive;
  4453. x &= size - 1;
  4454. }
  4455. }
  4456. this.expTable = expTable;
  4457. const logTable = new Int32Array(size);
  4458. for (let i = 0; i < size - 1; i++) {
  4459. logTable[expTable[i]] = i;
  4460. }
  4461. this.logTable = logTable;
  4462. // logTable[0] == 0 but this should never be used
  4463. this.zero = new GenericGFPoly(this, Int32Array.from([0]));
  4464. this.one = new GenericGFPoly(this, Int32Array.from([1]));
  4465. }
  4466. getZero() {
  4467. return this.zero;
  4468. }
  4469. getOne() {
  4470. return this.one;
  4471. }
  4472. /**
  4473. * @return the monomial representing coefficient * x^degree
  4474. */
  4475. buildMonomial(degree /*int*/, coefficient /*int*/) {
  4476. if (degree < 0) {
  4477. throw new IllegalArgumentException();
  4478. }
  4479. if (coefficient === 0) {
  4480. return this.zero;
  4481. }
  4482. const coefficients = new Int32Array(degree + 1);
  4483. coefficients[0] = coefficient;
  4484. return new GenericGFPoly(this, coefficients);
  4485. }
  4486. /**
  4487. * @return multiplicative inverse of a
  4488. */
  4489. inverse(a /*int*/) {
  4490. if (a === 0) {
  4491. throw new ArithmeticException();
  4492. }
  4493. return this.expTable[this.size - this.logTable[a] - 1];
  4494. }
  4495. /**
  4496. * @return product of a and b in GF(size)
  4497. */
  4498. multiply(a /*int*/, b /*int*/) {
  4499. if (a === 0 || b === 0) {
  4500. return 0;
  4501. }
  4502. return this.expTable[(this.logTable[a] + this.logTable[b]) % (this.size - 1)];
  4503. }
  4504. getSize() {
  4505. return this.size;
  4506. }
  4507. getGeneratorBase() {
  4508. return this.generatorBase;
  4509. }
  4510. /*@Override*/
  4511. toString() {
  4512. return ('GF(0x' + Integer.toHexString(this.primitive) + ',' + this.size + ')');
  4513. }
  4514. equals(o) {
  4515. return o === this;
  4516. }
  4517. }
  4518. GenericGF.AZTEC_DATA_12 = new GenericGF(0x1069, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1
  4519. GenericGF.AZTEC_DATA_10 = new GenericGF(0x409, 1024, 1); // x^10 + x^3 + 1
  4520. GenericGF.AZTEC_DATA_6 = new GenericGF(0x43, 64, 1); // x^6 + x + 1
  4521. GenericGF.AZTEC_PARAM = new GenericGF(0x13, 16, 1); // x^4 + x + 1
  4522. GenericGF.QR_CODE_FIELD_256 = new GenericGF(0x011d, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1
  4523. GenericGF.DATA_MATRIX_FIELD_256 = new GenericGF(0x012d, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1
  4524. GenericGF.AZTEC_DATA_8 = GenericGF.DATA_MATRIX_FIELD_256;
  4525. GenericGF.MAXICODE_FIELD_64 = GenericGF.AZTEC_DATA_6;
  4526. /**
  4527. * Custom Error class of type Exception.
  4528. */
  4529. class ReedSolomonException extends Exception {
  4530. }
  4531. ReedSolomonException.kind = 'ReedSolomonException';
  4532. /**
  4533. * Custom Error class of type Exception.
  4534. */
  4535. class IllegalStateException extends Exception {
  4536. }
  4537. IllegalStateException.kind = 'IllegalStateException';
  4538. /*
  4539. * Copyright 2007 ZXing authors
  4540. *
  4541. * Licensed under the Apache License, Version 2.0 (the "License");
  4542. * you may not use this file except in compliance with the License.
  4543. * You may obtain a copy of the License at
  4544. *
  4545. * http://www.apache.org/licenses/LICENSE-2.0
  4546. *
  4547. * Unless required by applicable law or agreed to in writing, software
  4548. * distributed under the License is distributed on an "AS IS" BASIS,
  4549. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4550. * See the License for the specific language governing permissions and
  4551. * limitations under the License.
  4552. */
  4553. /**
  4554. * <p>Implements Reed-Solomon decoding, as the name implies.</p>
  4555. *
  4556. * <p>The algorithm will not be explained here, but the following references were helpful
  4557. * in creating this implementation:</p>
  4558. *
  4559. * <ul>
  4560. * <li>Bruce Maggs.
  4561. * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
  4562. * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
  4563. * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
  4564. * "Chapter 5. Generalized Reed-Solomon Codes"</a>
  4565. * (see discussion of Euclidean algorithm)</li>
  4566. * </ul>
  4567. *
  4568. * <p>Much credit is due to William Rucklidge since portions of this code are an indirect
  4569. * port of his C++ Reed-Solomon implementation.</p>
  4570. *
  4571. * @author Sean Owen
  4572. * @author William Rucklidge
  4573. * @author sanfordsquires
  4574. */
  4575. class ReedSolomonDecoder {
  4576. constructor(field) {
  4577. this.field = field;
  4578. }
  4579. /**
  4580. * <p>Decodes given set of received codewords, which include both data and error-correction
  4581. * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
  4582. * in the input.</p>
  4583. *
  4584. * @param received data and error-correction codewords
  4585. * @param twoS number of error-correction codewords available
  4586. * @throws ReedSolomonException if decoding fails for any reason
  4587. */
  4588. decode(received, twoS /*int*/) {
  4589. const field = this.field;
  4590. const poly = new GenericGFPoly(field, received);
  4591. const syndromeCoefficients = new Int32Array(twoS);
  4592. let noError = true;
  4593. for (let i = 0; i < twoS; i++) {
  4594. const evalResult = poly.evaluateAt(field.exp(i + field.getGeneratorBase()));
  4595. syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evalResult;
  4596. if (evalResult !== 0) {
  4597. noError = false;
  4598. }
  4599. }
  4600. if (noError) {
  4601. return;
  4602. }
  4603. const syndrome = new GenericGFPoly(field, syndromeCoefficients);
  4604. const sigmaOmega = this.runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
  4605. const sigma = sigmaOmega[0];
  4606. const omega = sigmaOmega[1];
  4607. const errorLocations = this.findErrorLocations(sigma);
  4608. const errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations);
  4609. for (let i = 0; i < errorLocations.length; i++) {
  4610. const position = received.length - 1 - field.log(errorLocations[i]);
  4611. if (position < 0) {
  4612. throw new ReedSolomonException('Bad error location');
  4613. }
  4614. received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
  4615. }
  4616. }
  4617. runEuclideanAlgorithm(a, b, R /*int*/) {
  4618. // Assume a's degree is >= b's
  4619. if (a.getDegree() < b.getDegree()) {
  4620. const temp = a;
  4621. a = b;
  4622. b = temp;
  4623. }
  4624. const field = this.field;
  4625. let rLast = a;
  4626. let r = b;
  4627. let tLast = field.getZero();
  4628. let t = field.getOne();
  4629. // Run Euclidean algorithm until r's degree is less than R/2
  4630. while (r.getDegree() >= (R / 2 | 0)) {
  4631. let rLastLast = rLast;
  4632. let tLastLast = tLast;
  4633. rLast = r;
  4634. tLast = t;
  4635. // Divide rLastLast by rLast, with quotient in q and remainder in r
  4636. if (rLast.isZero()) {
  4637. // Oops, Euclidean algorithm already terminated?
  4638. throw new ReedSolomonException('r_{i-1} was zero');
  4639. }
  4640. r = rLastLast;
  4641. let q = field.getZero();
  4642. const denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
  4643. const dltInverse = field.inverse(denominatorLeadingTerm);
  4644. while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
  4645. const degreeDiff = r.getDegree() - rLast.getDegree();
  4646. const scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
  4647. q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
  4648. r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
  4649. }
  4650. t = q.multiply(tLast).addOrSubtract(tLastLast);
  4651. if (r.getDegree() >= rLast.getDegree()) {
  4652. throw new IllegalStateException('Division algorithm failed to reduce polynomial?');
  4653. }
  4654. }
  4655. const sigmaTildeAtZero = t.getCoefficient(0);
  4656. if (sigmaTildeAtZero === 0) {
  4657. throw new ReedSolomonException('sigmaTilde(0) was zero');
  4658. }
  4659. const inverse = field.inverse(sigmaTildeAtZero);
  4660. const sigma = t.multiplyScalar(inverse);
  4661. const omega = r.multiplyScalar(inverse);
  4662. return [sigma, omega];
  4663. }
  4664. findErrorLocations(errorLocator) {
  4665. // This is a direct application of Chien's search
  4666. const numErrors = errorLocator.getDegree();
  4667. if (numErrors === 1) { // shortcut
  4668. return Int32Array.from([errorLocator.getCoefficient(1)]);
  4669. }
  4670. const result = new Int32Array(numErrors);
  4671. let e = 0;
  4672. const field = this.field;
  4673. for (let i = 1; i < field.getSize() && e < numErrors; i++) {
  4674. if (errorLocator.evaluateAt(i) === 0) {
  4675. result[e] = field.inverse(i);
  4676. e++;
  4677. }
  4678. }
  4679. if (e !== numErrors) {
  4680. throw new ReedSolomonException('Error locator degree does not match number of roots');
  4681. }
  4682. return result;
  4683. }
  4684. findErrorMagnitudes(errorEvaluator, errorLocations) {
  4685. // This is directly applying Forney's Formula
  4686. const s = errorLocations.length;
  4687. const result = new Int32Array(s);
  4688. const field = this.field;
  4689. for (let i = 0; i < s; i++) {
  4690. const xiInverse = field.inverse(errorLocations[i]);
  4691. let denominator = 1;
  4692. for (let j = 0; j < s; j++) {
  4693. if (i !== j) {
  4694. // denominator = field.multiply(denominator,
  4695. // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)))
  4696. // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
  4697. // Below is a funny-looking workaround from Steven Parkes
  4698. const term = field.multiply(errorLocations[j], xiInverse);
  4699. const termPlus1 = (term & 0x1) === 0 ? term | 1 : term & ~1;
  4700. denominator = field.multiply(denominator, termPlus1);
  4701. }
  4702. }
  4703. result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator));
  4704. if (field.getGeneratorBase() !== 0) {
  4705. result[i] = field.multiply(result[i], xiInverse);
  4706. }
  4707. }
  4708. return result;
  4709. }
  4710. }
  4711. /*
  4712. * Copyright 2010 ZXing authors
  4713. *
  4714. * Licensed under the Apache License, Version 2.0 (the "License");
  4715. * you may not use this file except in compliance with the License.
  4716. * You may obtain a copy of the License at
  4717. *
  4718. * http://www.apache.org/licenses/LICENSE-2.0
  4719. *
  4720. * Unless required by applicable law or agreed to in writing, software
  4721. * distributed under the License is distributed on an "AS IS" BASIS,
  4722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4723. * See the License for the specific language governing permissions and
  4724. * limitations under the License.
  4725. */
  4726. // import java.util.Arrays;
  4727. var Table;
  4728. (function (Table) {
  4729. Table[Table["UPPER"] = 0] = "UPPER";
  4730. Table[Table["LOWER"] = 1] = "LOWER";
  4731. Table[Table["MIXED"] = 2] = "MIXED";
  4732. Table[Table["DIGIT"] = 3] = "DIGIT";
  4733. Table[Table["PUNCT"] = 4] = "PUNCT";
  4734. Table[Table["BINARY"] = 5] = "BINARY";
  4735. })(Table || (Table = {}));
  4736. /**
  4737. * <p>The main class which implements Aztec Code decoding -- as opposed to locating and extracting
  4738. * the Aztec Code from an image.</p>
  4739. *
  4740. * @author David Olivier
  4741. */
  4742. class Decoder {
  4743. decode(detectorResult) {
  4744. this.ddata = detectorResult;
  4745. let matrix = detectorResult.getBits();
  4746. let rawbits = this.extractBits(matrix);
  4747. let correctedBits = this.correctBits(rawbits);
  4748. let rawBytes = Decoder.convertBoolArrayToByteArray(correctedBits);
  4749. let result = Decoder.getEncodedData(correctedBits);
  4750. let decoderResult = new DecoderResult(rawBytes, result, null, null);
  4751. decoderResult.setNumBits(correctedBits.length);
  4752. return decoderResult;
  4753. }
  4754. // This method is used for testing the high-level encoder
  4755. static highLevelDecode(correctedBits) {
  4756. return this.getEncodedData(correctedBits);
  4757. }
  4758. /**
  4759. * Gets the string encoded in the aztec code bits
  4760. *
  4761. * @return the decoded string
  4762. */
  4763. static getEncodedData(correctedBits) {
  4764. let endIndex = correctedBits.length;
  4765. let latchTable = Table.UPPER; // table most recently latched to
  4766. let shiftTable = Table.UPPER; // table to use for the next read
  4767. let result = '';
  4768. let index = 0;
  4769. while (index < endIndex) {
  4770. if (shiftTable === Table.BINARY) {
  4771. if (endIndex - index < 5) {
  4772. break;
  4773. }
  4774. let length = Decoder.readCode(correctedBits, index, 5);
  4775. index += 5;
  4776. if (length === 0) {
  4777. if (endIndex - index < 11) {
  4778. break;
  4779. }
  4780. length = Decoder.readCode(correctedBits, index, 11) + 31;
  4781. index += 11;
  4782. }
  4783. for (let charCount = 0; charCount < length; charCount++) {
  4784. if (endIndex - index < 8) {
  4785. index = endIndex; // Force outer loop to exit
  4786. break;
  4787. }
  4788. const code = Decoder.readCode(correctedBits, index, 8);
  4789. result += /*(char)*/ StringUtils.castAsNonUtf8Char(code);
  4790. index += 8;
  4791. }
  4792. // Go back to whatever mode we had been in
  4793. shiftTable = latchTable;
  4794. }
  4795. else {
  4796. let size = shiftTable === Table.DIGIT ? 4 : 5;
  4797. if (endIndex - index < size) {
  4798. break;
  4799. }
  4800. let code = Decoder.readCode(correctedBits, index, size);
  4801. index += size;
  4802. let str = Decoder.getCharacter(shiftTable, code);
  4803. if (str.startsWith('CTRL_')) {
  4804. // Table changes
  4805. // ISO/IEC 24778:2008 prescribes ending a shift sequence in the mode from which it was invoked.
  4806. // That's including when that mode is a shift.
  4807. // Our test case dlusbs.png for issue #642 exercises that.
  4808. latchTable = shiftTable; // Latch the current mode, so as to return to Upper after U/S B/S
  4809. shiftTable = Decoder.getTable(str.charAt(5));
  4810. if (str.charAt(6) === 'L') {
  4811. latchTable = shiftTable;
  4812. }
  4813. }
  4814. else {
  4815. result += str;
  4816. // Go back to whatever mode we had been in
  4817. shiftTable = latchTable;
  4818. }
  4819. }
  4820. }
  4821. return result;
  4822. }
  4823. /**
  4824. * gets the table corresponding to the char passed
  4825. */
  4826. static getTable(t) {
  4827. switch (t) {
  4828. case 'L':
  4829. return Table.LOWER;
  4830. case 'P':
  4831. return Table.PUNCT;
  4832. case 'M':
  4833. return Table.MIXED;
  4834. case 'D':
  4835. return Table.DIGIT;
  4836. case 'B':
  4837. return Table.BINARY;
  4838. case 'U':
  4839. default:
  4840. return Table.UPPER;
  4841. }
  4842. }
  4843. /**
  4844. * Gets the character (or string) corresponding to the passed code in the given table
  4845. *
  4846. * @param table the table used
  4847. * @param code the code of the character
  4848. */
  4849. static getCharacter(table, code) {
  4850. switch (table) {
  4851. case Table.UPPER:
  4852. return Decoder.UPPER_TABLE[code];
  4853. case Table.LOWER:
  4854. return Decoder.LOWER_TABLE[code];
  4855. case Table.MIXED:
  4856. return Decoder.MIXED_TABLE[code];
  4857. case Table.PUNCT:
  4858. return Decoder.PUNCT_TABLE[code];
  4859. case Table.DIGIT:
  4860. return Decoder.DIGIT_TABLE[code];
  4861. default:
  4862. // Should not reach here.
  4863. throw new IllegalStateException('Bad table');
  4864. }
  4865. }
  4866. /**
  4867. * <p>Performs RS error correction on an array of bits.</p>
  4868. *
  4869. * @return the corrected array
  4870. * @throws FormatException if the input contains too many errors
  4871. */
  4872. correctBits(rawbits) {
  4873. let gf;
  4874. let codewordSize;
  4875. if (this.ddata.getNbLayers() <= 2) {
  4876. codewordSize = 6;
  4877. gf = GenericGF.AZTEC_DATA_6;
  4878. }
  4879. else if (this.ddata.getNbLayers() <= 8) {
  4880. codewordSize = 8;
  4881. gf = GenericGF.AZTEC_DATA_8;
  4882. }
  4883. else if (this.ddata.getNbLayers() <= 22) {
  4884. codewordSize = 10;
  4885. gf = GenericGF.AZTEC_DATA_10;
  4886. }
  4887. else {
  4888. codewordSize = 12;
  4889. gf = GenericGF.AZTEC_DATA_12;
  4890. }
  4891. let numDataCodewords = this.ddata.getNbDatablocks();
  4892. let numCodewords = rawbits.length / codewordSize;
  4893. if (numCodewords < numDataCodewords) {
  4894. throw new FormatException();
  4895. }
  4896. let offset = rawbits.length % codewordSize;
  4897. let dataWords = new Int32Array(numCodewords);
  4898. for (let i = 0; i < numCodewords; i++, offset += codewordSize) {
  4899. dataWords[i] = Decoder.readCode(rawbits, offset, codewordSize);
  4900. }
  4901. try {
  4902. let rsDecoder = new ReedSolomonDecoder(gf);
  4903. rsDecoder.decode(dataWords, numCodewords - numDataCodewords);
  4904. }
  4905. catch (ex) {
  4906. throw new FormatException(ex);
  4907. }
  4908. // Now perform the unstuffing operation.
  4909. // First, count how many bits are going to be thrown out as stuffing
  4910. let mask = (1 << codewordSize) - 1;
  4911. let stuffedBits = 0;
  4912. for (let i = 0; i < numDataCodewords; i++) {
  4913. let dataWord = dataWords[i];
  4914. if (dataWord === 0 || dataWord === mask) {
  4915. throw new FormatException();
  4916. }
  4917. else if (dataWord === 1 || dataWord === mask - 1) {
  4918. stuffedBits++;
  4919. }
  4920. }
  4921. // Now, actually unpack the bits and remove the stuffing
  4922. let correctedBits = new Array(numDataCodewords * codewordSize - stuffedBits);
  4923. let index = 0;
  4924. for (let i = 0; i < numDataCodewords; i++) {
  4925. let dataWord = dataWords[i];
  4926. if (dataWord === 1 || dataWord === mask - 1) {
  4927. // next codewordSize-1 bits are all zeros or all ones
  4928. correctedBits.fill(dataWord > 1, index, index + codewordSize - 1);
  4929. // Arrays.fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);
  4930. index += codewordSize - 1;
  4931. }
  4932. else {
  4933. for (let bit = codewordSize - 1; bit >= 0; --bit) {
  4934. correctedBits[index++] = (dataWord & (1 << bit)) !== 0;
  4935. }
  4936. }
  4937. }
  4938. return correctedBits;
  4939. }
  4940. /**
  4941. * Gets the array of bits from an Aztec Code matrix
  4942. *
  4943. * @return the array of bits
  4944. */
  4945. extractBits(matrix) {
  4946. let compact = this.ddata.isCompact();
  4947. let layers = this.ddata.getNbLayers();
  4948. let baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines
  4949. let alignmentMap = new Int32Array(baseMatrixSize);
  4950. let rawbits = new Array(this.totalBitsInLayer(layers, compact));
  4951. if (compact) {
  4952. for (let i = 0; i < alignmentMap.length; i++) {
  4953. alignmentMap[i] = i;
  4954. }
  4955. }
  4956. else {
  4957. let matrixSize = baseMatrixSize + 1 + 2 * Integer.truncDivision((Integer.truncDivision(baseMatrixSize, 2) - 1), 15);
  4958. let origCenter = baseMatrixSize / 2;
  4959. let center = Integer.truncDivision(matrixSize, 2);
  4960. for (let i = 0; i < origCenter; i++) {
  4961. let newOffset = i + Integer.truncDivision(i, 15);
  4962. alignmentMap[origCenter - i - 1] = center - newOffset - 1;
  4963. alignmentMap[origCenter + i] = center + newOffset + 1;
  4964. }
  4965. }
  4966. for (let i = 0, rowOffset = 0; i < layers; i++) {
  4967. let rowSize = (layers - i) * 4 + (compact ? 9 : 12);
  4968. // The top-left most point of this layer is <low, low> (not including alignment lines)
  4969. let low = i * 2;
  4970. // The bottom-right most point of this layer is <high, high> (not including alignment lines)
  4971. let high = baseMatrixSize - 1 - low;
  4972. // We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows
  4973. for (let j = 0; j < rowSize; j++) {
  4974. let columnOffset = j * 2;
  4975. for (let k = 0; k < 2; k++) {
  4976. // left column
  4977. rawbits[rowOffset + columnOffset + k] =
  4978. matrix.get(alignmentMap[low + k], alignmentMap[low + j]);
  4979. // bottom row
  4980. rawbits[rowOffset + 2 * rowSize + columnOffset + k] =
  4981. matrix.get(alignmentMap[low + j], alignmentMap[high - k]);
  4982. // right column
  4983. rawbits[rowOffset + 4 * rowSize + columnOffset + k] =
  4984. matrix.get(alignmentMap[high - k], alignmentMap[high - j]);
  4985. // top row
  4986. rawbits[rowOffset + 6 * rowSize + columnOffset + k] =
  4987. matrix.get(alignmentMap[high - j], alignmentMap[low + k]);
  4988. }
  4989. }
  4990. rowOffset += rowSize * 8;
  4991. }
  4992. return rawbits;
  4993. }
  4994. /**
  4995. * Reads a code of given length and at given index in an array of bits
  4996. */
  4997. static readCode(rawbits, startIndex, length) {
  4998. let res = 0;
  4999. for (let i = startIndex; i < startIndex + length; i++) {
  5000. res <<= 1;
  5001. if (rawbits[i]) {
  5002. res |= 0x01;
  5003. }
  5004. }
  5005. return res;
  5006. }
  5007. /**
  5008. * Reads a code of length 8 in an array of bits, padding with zeros
  5009. */
  5010. static readByte(rawbits, startIndex) {
  5011. let n = rawbits.length - startIndex;
  5012. if (n >= 8) {
  5013. return Decoder.readCode(rawbits, startIndex, 8);
  5014. }
  5015. return Decoder.readCode(rawbits, startIndex, n) << (8 - n);
  5016. }
  5017. /**
  5018. * Packs a bit array into bytes, most significant bit first
  5019. */
  5020. static convertBoolArrayToByteArray(boolArr) {
  5021. let byteArr = new Uint8Array((boolArr.length + 7) / 8);
  5022. for (let i = 0; i < byteArr.length; i++) {
  5023. byteArr[i] = Decoder.readByte(boolArr, 8 * i);
  5024. }
  5025. return byteArr;
  5026. }
  5027. totalBitsInLayer(layers, compact) {
  5028. return ((compact ? 88 : 112) + 16 * layers) * layers;
  5029. }
  5030. }
  5031. Decoder.UPPER_TABLE = [
  5032. 'CTRL_PS', ' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  5033. 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'CTRL_LL', 'CTRL_ML', 'CTRL_DL', 'CTRL_BS'
  5034. ];
  5035. Decoder.LOWER_TABLE = [
  5036. 'CTRL_PS', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
  5037. 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'CTRL_US', 'CTRL_ML', 'CTRL_DL', 'CTRL_BS'
  5038. ];
  5039. Decoder.MIXED_TABLE = [
  5040. // Module parse failed: Octal literal in strict mode (50:29)
  5041. // so number string were scaped
  5042. 'CTRL_PS', ' ', '\\1', '\\2', '\\3', '\\4', '\\5', '\\6', '\\7', '\b', '\t', '\n',
  5043. '\\13', '\f', '\r', '\\33', '\\34', '\\35', '\\36', '\\37', '@', '\\', '^', '_',
  5044. '`', '|', '~', '\\177', 'CTRL_LL', 'CTRL_UL', 'CTRL_PL', 'CTRL_BS'
  5045. ];
  5046. Decoder.PUNCT_TABLE = [
  5047. '', '\r', '\r\n', '. ', ', ', ': ', '!', '"', '#', '$', '%', '&', '\'', '(', ')',
  5048. '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}', 'CTRL_UL'
  5049. ];
  5050. Decoder.DIGIT_TABLE = [
  5051. 'CTRL_PS', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '.', 'CTRL_UL', 'CTRL_US'
  5052. ];
  5053. /*
  5054. * Copyright 2012 ZXing authors
  5055. *
  5056. * Licensed under the Apache License, Version 2.0 (the "License");
  5057. * you may not use this file except in compliance with the License.
  5058. * You may obtain a copy of the License at
  5059. *
  5060. * http://www.apache.org/licenses/LICENSE-2.0
  5061. *
  5062. * Unless required by applicable law or agreed to in writing, software
  5063. * distributed under the License is distributed on an "AS IS" BASIS,
  5064. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5065. * See the License for the specific language governing permissions and
  5066. * limitations under the License.
  5067. */
  5068. /*namespace com.google.zxing.common.detector {*/
  5069. /**
  5070. * General math-related and numeric utility functions.
  5071. */
  5072. class MathUtils {
  5073. constructor() { }
  5074. /**
  5075. * Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its
  5076. * argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut
  5077. * differ slightly from {@link Math#round(float)} in that half rounds down for negative
  5078. * values. -2.5 rounds to -3, not -2. For purposes here it makes no difference.
  5079. *
  5080. * @param d real value to round
  5081. * @return nearest {@code int}
  5082. */
  5083. static round(d /*float*/) {
  5084. if (isNaN(d))
  5085. return 0;
  5086. if (d <= Number.MIN_SAFE_INTEGER)
  5087. return Number.MIN_SAFE_INTEGER;
  5088. if (d >= Number.MAX_SAFE_INTEGER)
  5089. return Number.MAX_SAFE_INTEGER;
  5090. return /*(int) */ (d + (d < 0.0 ? -0.5 : 0.5)) | 0;
  5091. }
  5092. // TYPESCRIPTPORT: maybe remove round method and call directly Math.round, it looks like it doesn't make sense for js
  5093. /**
  5094. * @param aX point A x coordinate
  5095. * @param aY point A y coordinate
  5096. * @param bX point B x coordinate
  5097. * @param bY point B y coordinate
  5098. * @return Euclidean distance between points A and B
  5099. */
  5100. static distance(aX /*float|int*/, aY /*float|int*/, bX /*float|int*/, bY /*float|int*/) {
  5101. const xDiff = aX - bX;
  5102. const yDiff = aY - bY;
  5103. return /*(float) */ Math.sqrt(xDiff * xDiff + yDiff * yDiff);
  5104. }
  5105. /**
  5106. * @param aX point A x coordinate
  5107. * @param aY point A y coordinate
  5108. * @param bX point B x coordinate
  5109. * @param bY point B y coordinate
  5110. * @return Euclidean distance between points A and B
  5111. */
  5112. // public static distance(aX: number /*int*/, aY: number /*int*/, bX: number /*int*/, bY: number /*int*/): float {
  5113. // const xDiff = aX - bX
  5114. // const yDiff = aY - bY
  5115. // return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
  5116. // }
  5117. /**
  5118. * @param array values to sum
  5119. * @return sum of values in array
  5120. */
  5121. static sum(array) {
  5122. let count = 0;
  5123. for (let i = 0, length = array.length; i !== length; i++) {
  5124. const a = array[i];
  5125. count += a;
  5126. }
  5127. return count;
  5128. }
  5129. }
  5130. /**
  5131. * Ponyfill for Java's Float class.
  5132. */
  5133. class Float {
  5134. /**
  5135. * SincTS has no difference between int and float, there's all numbers,
  5136. * this is used only to polyfill Java code.
  5137. */
  5138. static floatToIntBits(f) {
  5139. return f;
  5140. }
  5141. }
  5142. /**
  5143. * The float max value in JS is the number max value.
  5144. */
  5145. Float.MAX_VALUE = Number.MAX_SAFE_INTEGER;
  5146. /*
  5147. * Copyright 2007 ZXing authors
  5148. *
  5149. * Licensed under the Apache License, Version 2.0 (the "License");
  5150. * you may not use this file except in compliance with the License.
  5151. * You may obtain a copy of the License at
  5152. *
  5153. * http://www.apache.org/licenses/LICENSE-2.0
  5154. *
  5155. * Unless required by applicable law or agreed to in writing, software
  5156. * distributed under the License is distributed on an "AS IS" BASIS,
  5157. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5158. * See the License for the specific language governing permissions and
  5159. * limitations under the License.
  5160. */
  5161. /**
  5162. * <p>Encapsulates a point of interest in an image containing a barcode. Typically, this
  5163. * would be the location of a finder pattern or the corner of the barcode, for example.</p>
  5164. *
  5165. * @author Sean Owen
  5166. */
  5167. class ResultPoint {
  5168. constructor(x, y) {
  5169. this.x = x;
  5170. this.y = y;
  5171. }
  5172. getX() {
  5173. return this.x;
  5174. }
  5175. getY() {
  5176. return this.y;
  5177. }
  5178. /*@Override*/
  5179. equals(other) {
  5180. if (other instanceof ResultPoint) {
  5181. const otherPoint = other;
  5182. return this.x === otherPoint.x && this.y === otherPoint.y;
  5183. }
  5184. return false;
  5185. }
  5186. /*@Override*/
  5187. hashCode() {
  5188. return 31 * Float.floatToIntBits(this.x) + Float.floatToIntBits(this.y);
  5189. }
  5190. /*@Override*/
  5191. toString() {
  5192. return '(' + this.x + ',' + this.y + ')';
  5193. }
  5194. /**
  5195. * Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC
  5196. * and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
  5197. *
  5198. * @param patterns array of three {@code ResultPoint} to order
  5199. */
  5200. static orderBestPatterns(patterns) {
  5201. // Find distances between pattern centers
  5202. const zeroOneDistance = this.distance(patterns[0], patterns[1]);
  5203. const oneTwoDistance = this.distance(patterns[1], patterns[2]);
  5204. const zeroTwoDistance = this.distance(patterns[0], patterns[2]);
  5205. let pointA;
  5206. let pointB;
  5207. let pointC;
  5208. // Assume one closest to other two is B; A and C will just be guesses at first
  5209. if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) {
  5210. pointB = patterns[0];
  5211. pointA = patterns[1];
  5212. pointC = patterns[2];
  5213. }
  5214. else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) {
  5215. pointB = patterns[1];
  5216. pointA = patterns[0];
  5217. pointC = patterns[2];
  5218. }
  5219. else {
  5220. pointB = patterns[2];
  5221. pointA = patterns[0];
  5222. pointC = patterns[1];
  5223. }
  5224. // Use cross product to figure out whether A and C are correct or flipped.
  5225. // This asks whether BC x BA has a positive z component, which is the arrangement
  5226. // we want for A, B, C. If it's negative, then we've got it flipped around and
  5227. // should swap A and C.
  5228. if (this.crossProductZ(pointA, pointB, pointC) < 0.0) {
  5229. const temp = pointA;
  5230. pointA = pointC;
  5231. pointC = temp;
  5232. }
  5233. patterns[0] = pointA;
  5234. patterns[1] = pointB;
  5235. patterns[2] = pointC;
  5236. }
  5237. /**
  5238. * @param pattern1 first pattern
  5239. * @param pattern2 second pattern
  5240. * @return distance between two points
  5241. */
  5242. static distance(pattern1, pattern2) {
  5243. return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y);
  5244. }
  5245. /**
  5246. * Returns the z component of the cross product between vectors BC and BA.
  5247. */
  5248. static crossProductZ(pointA, pointB, pointC) {
  5249. const bX = pointB.x;
  5250. const bY = pointB.y;
  5251. return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
  5252. }
  5253. }
  5254. /*
  5255. * Copyright 2007 ZXing authors
  5256. *
  5257. * Licensed under the Apache License, Version 2.0 (the "License");
  5258. * you may not use this file except in compliance with the License.
  5259. * You may obtain a copy of the License at
  5260. *
  5261. * http://www.apache.org/licenses/LICENSE-2.0
  5262. *
  5263. * Unless required by applicable law or agreed to in writing, software
  5264. * distributed under the License is distributed on an "AS IS" BASIS,
  5265. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5266. * See the License for the specific language governing permissions and
  5267. * limitations under the License.
  5268. */
  5269. /**
  5270. * <p>Encapsulates the result of detecting a barcode in an image. This includes the raw
  5271. * matrix of black/white pixels corresponding to the barcode, and possibly points of interest
  5272. * in the image, like the location of finder patterns or corners of the barcode in the image.</p>
  5273. *
  5274. * @author Sean Owen
  5275. */
  5276. class DetectorResult {
  5277. constructor(bits, points) {
  5278. this.bits = bits;
  5279. this.points = points;
  5280. }
  5281. getBits() {
  5282. return this.bits;
  5283. }
  5284. getPoints() {
  5285. return this.points;
  5286. }
  5287. }
  5288. /*
  5289. * Copyright 2010 ZXing authors
  5290. *
  5291. * Licensed under the Apache License, Version 2.0 (the "License");
  5292. * you may not use this file except in compliance with the License.
  5293. * You may obtain a copy of the License at
  5294. *
  5295. * http://www.apache.org/licenses/LICENSE-2.0
  5296. *
  5297. * Unless required by applicable law or agreed to in writing, software
  5298. * distributed under the License is distributed on an "AS IS" BASIS,
  5299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5300. * See the License for the specific language governing permissions and
  5301. * limitations under the License.
  5302. */
  5303. /**
  5304. * <p>Extends {@link DetectorResult} with more information specific to the Aztec format,
  5305. * like the number of layers and whether it's compact.</p>
  5306. *
  5307. * @author Sean Owen
  5308. */
  5309. class AztecDetectorResult extends DetectorResult {
  5310. constructor(bits, points, compact, nbDatablocks, nbLayers) {
  5311. super(bits, points);
  5312. this.compact = compact;
  5313. this.nbDatablocks = nbDatablocks;
  5314. this.nbLayers = nbLayers;
  5315. }
  5316. getNbLayers() {
  5317. return this.nbLayers;
  5318. }
  5319. getNbDatablocks() {
  5320. return this.nbDatablocks;
  5321. }
  5322. isCompact() {
  5323. return this.compact;
  5324. }
  5325. }
  5326. /*
  5327. * Copyright 2010 ZXing authors
  5328. *
  5329. * Licensed under the Apache License, Version 2.0 (the "License");
  5330. * you may not use this file except in compliance with the License.
  5331. * You may obtain a copy of the License at
  5332. *
  5333. * http://www.apache.org/licenses/LICENSE-2.0
  5334. *
  5335. * Unless required by applicable law or agreed to in writing, software
  5336. * distributed under the License is distributed on an "AS IS" BASIS,
  5337. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5338. * See the License for the specific language governing permissions and
  5339. * limitations under the License.
  5340. */
  5341. /**
  5342. * <p>
  5343. * Detects a candidate barcode-like rectangular region within an image. It
  5344. * starts around the center of the image, increases the size of the candidate
  5345. * region until it finds a white rectangular region. By keeping track of the
  5346. * last black points it encountered, it determines the corners of the barcode.
  5347. * </p>
  5348. *
  5349. * @author David Olivier
  5350. */
  5351. class WhiteRectangleDetector {
  5352. // public constructor(private image: BitMatrix) /*throws NotFoundException*/ {
  5353. // this(image, INIT_SIZE, image.getWidth() / 2, image.getHeight() / 2)
  5354. // }
  5355. /**
  5356. * @param image barcode image to find a rectangle in
  5357. * @param initSize initial size of search area around center
  5358. * @param x x position of search center
  5359. * @param y y position of search center
  5360. * @throws NotFoundException if image is too small to accommodate {@code initSize}
  5361. */
  5362. constructor(image, initSize /*int*/, x /*int*/, y /*int*/) {
  5363. this.image = image;
  5364. this.height = image.getHeight();
  5365. this.width = image.getWidth();
  5366. if (undefined === initSize || null === initSize) {
  5367. initSize = WhiteRectangleDetector.INIT_SIZE;
  5368. }
  5369. if (undefined === x || null === x) {
  5370. x = image.getWidth() / 2 | 0;
  5371. }
  5372. if (undefined === y || null === y) {
  5373. y = image.getHeight() / 2 | 0;
  5374. }
  5375. const halfsize = initSize / 2 | 0;
  5376. this.leftInit = x - halfsize;
  5377. this.rightInit = x + halfsize;
  5378. this.upInit = y - halfsize;
  5379. this.downInit = y + halfsize;
  5380. if (this.upInit < 0 || this.leftInit < 0 || this.downInit >= this.height || this.rightInit >= this.width) {
  5381. throw new NotFoundException();
  5382. }
  5383. }
  5384. /**
  5385. * <p>
  5386. * Detects a candidate barcode-like rectangular region within an image. It
  5387. * starts around the center of the image, increases the size of the candidate
  5388. * region until it finds a white rectangular region.
  5389. * </p>
  5390. *
  5391. * @return {@link ResultPoint}[] describing the corners of the rectangular
  5392. * region. The first and last points are opposed on the diagonal, as
  5393. * are the second and third. The first point will be the topmost
  5394. * point and the last, the bottommost. The second point will be
  5395. * leftmost and the third, the rightmost
  5396. * @throws NotFoundException if no Data Matrix Code can be found
  5397. */
  5398. detect() {
  5399. let left = this.leftInit;
  5400. let right = this.rightInit;
  5401. let up = this.upInit;
  5402. let down = this.downInit;
  5403. let sizeExceeded = false;
  5404. let aBlackPointFoundOnBorder = true;
  5405. let atLeastOneBlackPointFoundOnBorder = false;
  5406. let atLeastOneBlackPointFoundOnRight = false;
  5407. let atLeastOneBlackPointFoundOnBottom = false;
  5408. let atLeastOneBlackPointFoundOnLeft = false;
  5409. let atLeastOneBlackPointFoundOnTop = false;
  5410. const width = this.width;
  5411. const height = this.height;
  5412. while (aBlackPointFoundOnBorder) {
  5413. aBlackPointFoundOnBorder = false;
  5414. // .....
  5415. // . |
  5416. // .....
  5417. let rightBorderNotWhite = true;
  5418. while ((rightBorderNotWhite || !atLeastOneBlackPointFoundOnRight) && right < width) {
  5419. rightBorderNotWhite = this.containsBlackPoint(up, down, right, false);
  5420. if (rightBorderNotWhite) {
  5421. right++;
  5422. aBlackPointFoundOnBorder = true;
  5423. atLeastOneBlackPointFoundOnRight = true;
  5424. }
  5425. else if (!atLeastOneBlackPointFoundOnRight) {
  5426. right++;
  5427. }
  5428. }
  5429. if (right >= width) {
  5430. sizeExceeded = true;
  5431. break;
  5432. }
  5433. // .....
  5434. // . .
  5435. // .___.
  5436. let bottomBorderNotWhite = true;
  5437. while ((bottomBorderNotWhite || !atLeastOneBlackPointFoundOnBottom) && down < height) {
  5438. bottomBorderNotWhite = this.containsBlackPoint(left, right, down, true);
  5439. if (bottomBorderNotWhite) {
  5440. down++;
  5441. aBlackPointFoundOnBorder = true;
  5442. atLeastOneBlackPointFoundOnBottom = true;
  5443. }
  5444. else if (!atLeastOneBlackPointFoundOnBottom) {
  5445. down++;
  5446. }
  5447. }
  5448. if (down >= height) {
  5449. sizeExceeded = true;
  5450. break;
  5451. }
  5452. // .....
  5453. // | .
  5454. // .....
  5455. let leftBorderNotWhite = true;
  5456. while ((leftBorderNotWhite || !atLeastOneBlackPointFoundOnLeft) && left >= 0) {
  5457. leftBorderNotWhite = this.containsBlackPoint(up, down, left, false);
  5458. if (leftBorderNotWhite) {
  5459. left--;
  5460. aBlackPointFoundOnBorder = true;
  5461. atLeastOneBlackPointFoundOnLeft = true;
  5462. }
  5463. else if (!atLeastOneBlackPointFoundOnLeft) {
  5464. left--;
  5465. }
  5466. }
  5467. if (left < 0) {
  5468. sizeExceeded = true;
  5469. break;
  5470. }
  5471. // .___.
  5472. // . .
  5473. // .....
  5474. let topBorderNotWhite = true;
  5475. while ((topBorderNotWhite || !atLeastOneBlackPointFoundOnTop) && up >= 0) {
  5476. topBorderNotWhite = this.containsBlackPoint(left, right, up, true);
  5477. if (topBorderNotWhite) {
  5478. up--;
  5479. aBlackPointFoundOnBorder = true;
  5480. atLeastOneBlackPointFoundOnTop = true;
  5481. }
  5482. else if (!atLeastOneBlackPointFoundOnTop) {
  5483. up--;
  5484. }
  5485. }
  5486. if (up < 0) {
  5487. sizeExceeded = true;
  5488. break;
  5489. }
  5490. if (aBlackPointFoundOnBorder) {
  5491. atLeastOneBlackPointFoundOnBorder = true;
  5492. }
  5493. }
  5494. if (!sizeExceeded && atLeastOneBlackPointFoundOnBorder) {
  5495. const maxSize = right - left;
  5496. let z = null;
  5497. for (let i = 1; z === null && i < maxSize; i++) {
  5498. z = this.getBlackPointOnSegment(left, down - i, left + i, down);
  5499. }
  5500. if (z == null) {
  5501. throw new NotFoundException();
  5502. }
  5503. let t = null;
  5504. // go down right
  5505. for (let i = 1; t === null && i < maxSize; i++) {
  5506. t = this.getBlackPointOnSegment(left, up + i, left + i, up);
  5507. }
  5508. if (t == null) {
  5509. throw new NotFoundException();
  5510. }
  5511. let x = null;
  5512. // go down left
  5513. for (let i = 1; x === null && i < maxSize; i++) {
  5514. x = this.getBlackPointOnSegment(right, up + i, right - i, up);
  5515. }
  5516. if (x == null) {
  5517. throw new NotFoundException();
  5518. }
  5519. let y = null;
  5520. // go up left
  5521. for (let i = 1; y === null && i < maxSize; i++) {
  5522. y = this.getBlackPointOnSegment(right, down - i, right - i, down);
  5523. }
  5524. if (y == null) {
  5525. throw new NotFoundException();
  5526. }
  5527. return this.centerEdges(y, z, x, t);
  5528. }
  5529. else {
  5530. throw new NotFoundException();
  5531. }
  5532. }
  5533. getBlackPointOnSegment(aX /*float*/, aY /*float*/, bX /*float*/, bY /*float*/) {
  5534. const dist = MathUtils.round(MathUtils.distance(aX, aY, bX, bY));
  5535. const xStep = (bX - aX) / dist;
  5536. const yStep = (bY - aY) / dist;
  5537. const image = this.image;
  5538. for (let i = 0; i < dist; i++) {
  5539. const x = MathUtils.round(aX + i * xStep);
  5540. const y = MathUtils.round(aY + i * yStep);
  5541. if (image.get(x, y)) {
  5542. return new ResultPoint(x, y);
  5543. }
  5544. }
  5545. return null;
  5546. }
  5547. /**
  5548. * recenters the points of a constant distance towards the center
  5549. *
  5550. * @param y bottom most point
  5551. * @param z left most point
  5552. * @param x right most point
  5553. * @param t top most point
  5554. * @return {@link ResultPoint}[] describing the corners of the rectangular
  5555. * region. The first and last points are opposed on the diagonal, as
  5556. * are the second and third. The first point will be the topmost
  5557. * point and the last, the bottommost. The second point will be
  5558. * leftmost and the third, the rightmost
  5559. */
  5560. centerEdges(y, z, x, t) {
  5561. //
  5562. // t t
  5563. // z x
  5564. // x OR z
  5565. // y y
  5566. //
  5567. const yi = y.getX();
  5568. const yj = y.getY();
  5569. const zi = z.getX();
  5570. const zj = z.getY();
  5571. const xi = x.getX();
  5572. const xj = x.getY();
  5573. const ti = t.getX();
  5574. const tj = t.getY();
  5575. const CORR = WhiteRectangleDetector.CORR;
  5576. if (yi < this.width / 2.0) {
  5577. return [
  5578. new ResultPoint(ti - CORR, tj + CORR),
  5579. new ResultPoint(zi + CORR, zj + CORR),
  5580. new ResultPoint(xi - CORR, xj - CORR),
  5581. new ResultPoint(yi + CORR, yj - CORR)
  5582. ];
  5583. }
  5584. else {
  5585. return [
  5586. new ResultPoint(ti + CORR, tj + CORR),
  5587. new ResultPoint(zi + CORR, zj - CORR),
  5588. new ResultPoint(xi - CORR, xj + CORR),
  5589. new ResultPoint(yi - CORR, yj - CORR)
  5590. ];
  5591. }
  5592. }
  5593. /**
  5594. * Determines whether a segment contains a black point
  5595. *
  5596. * @param a min value of the scanned coordinate
  5597. * @param b max value of the scanned coordinate
  5598. * @param fixed value of fixed coordinate
  5599. * @param horizontal set to true if scan must be horizontal, false if vertical
  5600. * @return true if a black point has been found, else false.
  5601. */
  5602. containsBlackPoint(a /*int*/, b /*int*/, fixed /*int*/, horizontal) {
  5603. const image = this.image;
  5604. if (horizontal) {
  5605. for (let x = a; x <= b; x++) {
  5606. if (image.get(x, fixed)) {
  5607. return true;
  5608. }
  5609. }
  5610. }
  5611. else {
  5612. for (let y = a; y <= b; y++) {
  5613. if (image.get(fixed, y)) {
  5614. return true;
  5615. }
  5616. }
  5617. }
  5618. return false;
  5619. }
  5620. }
  5621. WhiteRectangleDetector.INIT_SIZE = 10;
  5622. WhiteRectangleDetector.CORR = 1;
  5623. /*
  5624. * Copyright 2007 ZXing authors
  5625. *
  5626. * Licensed under the Apache License, Version 2.0 (the "License");
  5627. * you may not use this file except in compliance with the License.
  5628. * You may obtain a copy of the License at
  5629. *
  5630. * http://www.apache.org/licenses/LICENSE-2.0
  5631. *
  5632. * Unless required by applicable law or agreed to in writing, software
  5633. * distributed under the License is distributed on an "AS IS" BASIS,
  5634. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5635. * See the License for the specific language governing permissions and
  5636. * limitations under the License.
  5637. */
  5638. /**
  5639. * Implementations of this class can, given locations of finder patterns for a QR code in an
  5640. * image, sample the right points in the image to reconstruct the QR code, accounting for
  5641. * perspective distortion. It is abstracted since it is relatively expensive and should be allowed
  5642. * to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
  5643. * Imaging library, but which may not be available in other environments such as J2ME, and vice
  5644. * versa.
  5645. *
  5646. * The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
  5647. * with an instance of a class which implements this interface.
  5648. *
  5649. * @author Sean Owen
  5650. */
  5651. class GridSampler {
  5652. /**
  5653. * <p>Checks a set of points that have been transformed to sample points on an image against
  5654. * the image's dimensions to see if the point are even within the image.</p>
  5655. *
  5656. * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
  5657. * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
  5658. * patterns in an image where the QR Code runs all the way to the image border.</p>
  5659. *
  5660. * <p>For efficiency, the method will check points from either end of the line until one is found
  5661. * to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
  5662. *
  5663. * @param image image into which the points should map
  5664. * @param points actual points in x1,y1,...,xn,yn form
  5665. * @throws NotFoundException if an endpoint is lies outside the image boundaries
  5666. */
  5667. static checkAndNudgePoints(image, points) {
  5668. const width = image.getWidth();
  5669. const height = image.getHeight();
  5670. // Check and nudge points from start until we see some that are OK:
  5671. let nudged = true;
  5672. for (let offset = 0; offset < points.length && nudged; offset += 2) {
  5673. const x = Math.floor(points[offset]);
  5674. const y = Math.floor(points[offset + 1]);
  5675. if (x < -1 || x > width || y < -1 || y > height) {
  5676. throw new NotFoundException();
  5677. }
  5678. nudged = false;
  5679. if (x === -1) {
  5680. points[offset] = 0.0;
  5681. nudged = true;
  5682. }
  5683. else if (x === width) {
  5684. points[offset] = width - 1;
  5685. nudged = true;
  5686. }
  5687. if (y === -1) {
  5688. points[offset + 1] = 0.0;
  5689. nudged = true;
  5690. }
  5691. else if (y === height) {
  5692. points[offset + 1] = height - 1;
  5693. nudged = true;
  5694. }
  5695. }
  5696. // Check and nudge points from end:
  5697. nudged = true;
  5698. for (let offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {
  5699. const x = Math.floor(points[offset]);
  5700. const y = Math.floor(points[offset + 1]);
  5701. if (x < -1 || x > width || y < -1 || y > height) {
  5702. throw new NotFoundException();
  5703. }
  5704. nudged = false;
  5705. if (x === -1) {
  5706. points[offset] = 0.0;
  5707. nudged = true;
  5708. }
  5709. else if (x === width) {
  5710. points[offset] = width - 1;
  5711. nudged = true;
  5712. }
  5713. if (y === -1) {
  5714. points[offset + 1] = 0.0;
  5715. nudged = true;
  5716. }
  5717. else if (y === height) {
  5718. points[offset + 1] = height - 1;
  5719. nudged = true;
  5720. }
  5721. }
  5722. }
  5723. }
  5724. /*
  5725. * Copyright 2007 ZXing authors
  5726. *
  5727. * Licensed under the Apache License, Version 2.0 (the "License");
  5728. * you may not use this file except in compliance with the License.
  5729. * You may obtain a copy of the License at
  5730. *
  5731. * http://www.apache.org/licenses/LICENSE-2.0
  5732. *
  5733. * Unless required by applicable law or agreed to in writing, software
  5734. * distributed under the License is distributed on an "AS IS" BASIS,
  5735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5736. * See the License for the specific language governing permissions and
  5737. * limitations under the License.
  5738. */
  5739. /*namespace com.google.zxing.common {*/
  5740. /**
  5741. * <p>This class implements a perspective transform in two dimensions. Given four source and four
  5742. * destination points, it will compute the transformation implied between them. The code is based
  5743. * directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p>
  5744. *
  5745. * @author Sean Owen
  5746. */
  5747. class PerspectiveTransform {
  5748. constructor(a11 /*float*/, a21 /*float*/, a31 /*float*/, a12 /*float*/, a22 /*float*/, a32 /*float*/, a13 /*float*/, a23 /*float*/, a33 /*float*/) {
  5749. this.a11 = a11;
  5750. this.a21 = a21;
  5751. this.a31 = a31;
  5752. this.a12 = a12;
  5753. this.a22 = a22;
  5754. this.a32 = a32;
  5755. this.a13 = a13;
  5756. this.a23 = a23;
  5757. this.a33 = a33;
  5758. }
  5759. static quadrilateralToQuadrilateral(x0 /*float*/, y0 /*float*/, x1 /*float*/, y1 /*float*/, x2 /*float*/, y2 /*float*/, x3 /*float*/, y3 /*float*/, x0p /*float*/, y0p /*float*/, x1p /*float*/, y1p /*float*/, x2p /*float*/, y2p /*float*/, x3p /*float*/, y3p /*float*/) {
  5760. const qToS = PerspectiveTransform.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
  5761. const sToQ = PerspectiveTransform.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
  5762. return sToQ.times(qToS);
  5763. }
  5764. transformPoints(points) {
  5765. const max = points.length;
  5766. const a11 = this.a11;
  5767. const a12 = this.a12;
  5768. const a13 = this.a13;
  5769. const a21 = this.a21;
  5770. const a22 = this.a22;
  5771. const a23 = this.a23;
  5772. const a31 = this.a31;
  5773. const a32 = this.a32;
  5774. const a33 = this.a33;
  5775. for (let i = 0; i < max; i += 2) {
  5776. const x = points[i];
  5777. const y = points[i + 1];
  5778. const denominator = a13 * x + a23 * y + a33;
  5779. points[i] = (a11 * x + a21 * y + a31) / denominator;
  5780. points[i + 1] = (a12 * x + a22 * y + a32) / denominator;
  5781. }
  5782. }
  5783. transformPointsWithValues(xValues, yValues) {
  5784. const a11 = this.a11;
  5785. const a12 = this.a12;
  5786. const a13 = this.a13;
  5787. const a21 = this.a21;
  5788. const a22 = this.a22;
  5789. const a23 = this.a23;
  5790. const a31 = this.a31;
  5791. const a32 = this.a32;
  5792. const a33 = this.a33;
  5793. const n = xValues.length;
  5794. for (let i = 0; i < n; i++) {
  5795. const x = xValues[i];
  5796. const y = yValues[i];
  5797. const denominator = a13 * x + a23 * y + a33;
  5798. xValues[i] = (a11 * x + a21 * y + a31) / denominator;
  5799. yValues[i] = (a12 * x + a22 * y + a32) / denominator;
  5800. }
  5801. }
  5802. static squareToQuadrilateral(x0 /*float*/, y0 /*float*/, x1 /*float*/, y1 /*float*/, x2 /*float*/, y2 /*float*/, x3 /*float*/, y3 /*float*/) {
  5803. const dx3 = x0 - x1 + x2 - x3;
  5804. const dy3 = y0 - y1 + y2 - y3;
  5805. if (dx3 === 0.0 && dy3 === 0.0) {
  5806. // Affine
  5807. return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0);
  5808. }
  5809. else {
  5810. const dx1 = x1 - x2;
  5811. const dx2 = x3 - x2;
  5812. const dy1 = y1 - y2;
  5813. const dy2 = y3 - y2;
  5814. const denominator = dx1 * dy2 - dx2 * dy1;
  5815. const a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
  5816. const a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
  5817. return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0);
  5818. }
  5819. }
  5820. static quadrilateralToSquare(x0 /*float*/, y0 /*float*/, x1 /*float*/, y1 /*float*/, x2 /*float*/, y2 /*float*/, x3 /*float*/, y3 /*float*/) {
  5821. // Here, the adjoint serves as the inverse:
  5822. return PerspectiveTransform.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint();
  5823. }
  5824. buildAdjoint() {
  5825. // Adjoint is the transpose of the cofactor matrix:
  5826. return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21);
  5827. }
  5828. times(other) {
  5829. return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 + this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33);
  5830. }
  5831. }
  5832. /*
  5833. * Copyright 2007 ZXing authors
  5834. *
  5835. * Licensed under the Apache License, Version 2.0 (the "License");
  5836. * you may not use this file except in compliance with the License.
  5837. * You may obtain a copy of the License at
  5838. *
  5839. * http://www.apache.org/licenses/LICENSE-2.0
  5840. *
  5841. * Unless required by applicable law or agreed to in writing, software
  5842. * distributed under the License is distributed on an "AS IS" BASIS,
  5843. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5844. * See the License for the specific language governing permissions and
  5845. * limitations under the License.
  5846. */
  5847. /**
  5848. * @author Sean Owen
  5849. */
  5850. class DefaultGridSampler extends GridSampler {
  5851. /*@Override*/
  5852. sampleGrid(image, dimensionX /*int*/, dimensionY /*int*/, p1ToX /*float*/, p1ToY /*float*/, p2ToX /*float*/, p2ToY /*float*/, p3ToX /*float*/, p3ToY /*float*/, p4ToX /*float*/, p4ToY /*float*/, p1FromX /*float*/, p1FromY /*float*/, p2FromX /*float*/, p2FromY /*float*/, p3FromX /*float*/, p3FromY /*float*/, p4FromX /*float*/, p4FromY /*float*/) {
  5853. const transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);
  5854. return this.sampleGridWithTransform(image, dimensionX, dimensionY, transform);
  5855. }
  5856. /*@Override*/
  5857. sampleGridWithTransform(image, dimensionX /*int*/, dimensionY /*int*/, transform) {
  5858. if (dimensionX <= 0 || dimensionY <= 0) {
  5859. throw new NotFoundException();
  5860. }
  5861. const bits = new BitMatrix(dimensionX, dimensionY);
  5862. const points = new Float32Array(2 * dimensionX);
  5863. for (let y = 0; y < dimensionY; y++) {
  5864. const max = points.length;
  5865. const iValue = y + 0.5;
  5866. for (let x = 0; x < max; x += 2) {
  5867. points[x] = (x / 2) + 0.5;
  5868. points[x + 1] = iValue;
  5869. }
  5870. transform.transformPoints(points);
  5871. // Quick check to see if points transformed to something inside the image
  5872. // sufficient to check the endpoints
  5873. GridSampler.checkAndNudgePoints(image, points);
  5874. try {
  5875. for (let x = 0; x < max; x += 2) {
  5876. if (image.get(Math.floor(points[x]), Math.floor(points[x + 1]))) {
  5877. // Black(-ish) pixel
  5878. bits.set(x / 2, y);
  5879. }
  5880. }
  5881. }
  5882. catch (aioobe /*: ArrayIndexOutOfBoundsException*/) {
  5883. // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
  5884. // transform gets "twisted" such that it maps a straight line of points to a set of points
  5885. // whose endpoints are in bounds, but others are not. There is probably some mathematical
  5886. // way to detect this about the transformation that I don't know yet.
  5887. // This results in an ugly runtime exception despite our clever checks above -- can't have
  5888. // that. We could check each point's coordinates but that feels duplicative. We settle for
  5889. // catching and wrapping ArrayIndexOutOfBoundsException.
  5890. throw new NotFoundException();
  5891. }
  5892. }
  5893. return bits;
  5894. }
  5895. }
  5896. class GridSamplerInstance {
  5897. /**
  5898. * Sets the implementation of GridSampler used by the library. One global
  5899. * instance is stored, which may sound problematic. But, the implementation provided
  5900. * ought to be appropriate for the entire platform, and all uses of this library
  5901. * in the whole lifetime of the JVM. For instance, an Android activity can swap in
  5902. * an implementation that takes advantage of native platform libraries.
  5903. *
  5904. * @param newGridSampler The platform-specific object to install.
  5905. */
  5906. static setGridSampler(newGridSampler) {
  5907. GridSamplerInstance.gridSampler = newGridSampler;
  5908. }
  5909. /**
  5910. * @return the current implementation of GridSampler
  5911. */
  5912. static getInstance() {
  5913. return GridSamplerInstance.gridSampler;
  5914. }
  5915. }
  5916. GridSamplerInstance.gridSampler = new DefaultGridSampler();
  5917. /*
  5918. * Copyright 2010 ZXing authors
  5919. *
  5920. * Licensed under the Apache License, Version 2.0 (the "License");
  5921. * you may not use this file except in compliance with the License.
  5922. * You may obtain a copy of the License at
  5923. *
  5924. * http://www.apache.org/licenses/LICENSE-2.0
  5925. *
  5926. * Unless required by applicable law or agreed to in writing, software
  5927. * distributed under the License is distributed on an "AS IS" BASIS,
  5928. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5929. * See the License for the specific language governing permissions and
  5930. * limitations under the License.
  5931. */
  5932. class Point {
  5933. constructor(x, y) {
  5934. this.x = x;
  5935. this.y = y;
  5936. }
  5937. toResultPoint() {
  5938. return new ResultPoint(this.getX(), this.getY());
  5939. }
  5940. getX() {
  5941. return this.x;
  5942. }
  5943. getY() {
  5944. return this.y;
  5945. }
  5946. }
  5947. /**
  5948. * Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
  5949. * is rotated or skewed, or partially obscured.
  5950. *
  5951. * @author David Olivier
  5952. * @author Frank Yellin
  5953. */
  5954. class Detector {
  5955. constructor(image) {
  5956. this.EXPECTED_CORNER_BITS = new Int32Array([
  5957. 0xee0,
  5958. 0x1dc,
  5959. 0x83b,
  5960. 0x707,
  5961. ]);
  5962. this.image = image;
  5963. }
  5964. detect() {
  5965. return this.detectMirror(false);
  5966. }
  5967. /**
  5968. * Detects an Aztec Code in an image.
  5969. *
  5970. * @param isMirror if true, image is a mirror-image of original
  5971. * @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code
  5972. * @throws NotFoundException if no Aztec Code can be found
  5973. */
  5974. detectMirror(isMirror) {
  5975. // 1. Get the center of the aztec matrix
  5976. let pCenter = this.getMatrixCenter();
  5977. // 2. Get the center points of the four diagonal points just outside the bull's eye
  5978. // [topRight, bottomRight, bottomLeft, topLeft]
  5979. let bullsEyeCorners = this.getBullsEyeCorners(pCenter);
  5980. if (isMirror) {
  5981. let temp = bullsEyeCorners[0];
  5982. bullsEyeCorners[0] = bullsEyeCorners[2];
  5983. bullsEyeCorners[2] = temp;
  5984. }
  5985. // 3. Get the size of the matrix and other parameters from the bull's eye
  5986. this.extractParameters(bullsEyeCorners);
  5987. // 4. Sample the grid
  5988. let bits = this.sampleGrid(this.image, bullsEyeCorners[this.shift % 4], bullsEyeCorners[(this.shift + 1) % 4], bullsEyeCorners[(this.shift + 2) % 4], bullsEyeCorners[(this.shift + 3) % 4]);
  5989. // 5. Get the corners of the matrix.
  5990. let corners = this.getMatrixCornerPoints(bullsEyeCorners);
  5991. return new AztecDetectorResult(bits, corners, this.compact, this.nbDataBlocks, this.nbLayers);
  5992. }
  5993. /**
  5994. * Extracts the number of data layers and data blocks from the layer around the bull's eye.
  5995. *
  5996. * @param bullsEyeCorners the array of bull's eye corners
  5997. * @throws NotFoundException in case of too many errors or invalid parameters
  5998. */
  5999. extractParameters(bullsEyeCorners) {
  6000. if (!this.isValidPoint(bullsEyeCorners[0]) || !this.isValidPoint(bullsEyeCorners[1]) ||
  6001. !this.isValidPoint(bullsEyeCorners[2]) || !this.isValidPoint(bullsEyeCorners[3])) {
  6002. throw new NotFoundException();
  6003. }
  6004. let length = 2 * this.nbCenterLayers;
  6005. // Get the bits around the bull's eye
  6006. let sides = new Int32Array([
  6007. this.sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length),
  6008. this.sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length),
  6009. this.sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length),
  6010. this.sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
  6011. ]);
  6012. // bullsEyeCorners[shift] is the corner of the bulls'eye that has three
  6013. // orientation marks.
  6014. // sides[shift] is the row/column that goes from the corner with three
  6015. // orientation marks to the corner with two.
  6016. this.shift = this.getRotation(sides, length);
  6017. // Flatten the parameter bits into a single 28- or 40-bit long
  6018. let parameterData = 0;
  6019. for (let i = 0; i < 4; i++) {
  6020. let side = sides[(this.shift + i) % 4];
  6021. if (this.compact) {
  6022. // Each side of the form ..XXXXXXX. where Xs are parameter data
  6023. parameterData <<= 7;
  6024. parameterData += (side >> 1) & 0x7F;
  6025. }
  6026. else {
  6027. // Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
  6028. parameterData <<= 10;
  6029. parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
  6030. }
  6031. }
  6032. // Corrects parameter data using RS. Returns just the data portion
  6033. // without the error correction.
  6034. let correctedData = this.getCorrectedParameterData(parameterData, this.compact);
  6035. if (this.compact) {
  6036. // 8 bits: 2 bits layers and 6 bits data blocks
  6037. this.nbLayers = (correctedData >> 6) + 1;
  6038. this.nbDataBlocks = (correctedData & 0x3F) + 1;
  6039. }
  6040. else {
  6041. // 16 bits: 5 bits layers and 11 bits data blocks
  6042. this.nbLayers = (correctedData >> 11) + 1;
  6043. this.nbDataBlocks = (correctedData & 0x7FF) + 1;
  6044. }
  6045. }
  6046. getRotation(sides, length) {
  6047. // In a normal pattern, we expect to See
  6048. // ** .* D A
  6049. // * *
  6050. //
  6051. // . *
  6052. // .. .. C B
  6053. //
  6054. // Grab the 3 bits from each of the sides the form the locator pattern and concatenate
  6055. // into a 12-bit integer. Start with the bit at A
  6056. let cornerBits = 0;
  6057. sides.forEach((side, idx, arr) => {
  6058. // XX......X where X's are orientation marks
  6059. let t = ((side >> (length - 2)) << 1) + (side & 1);
  6060. cornerBits = (cornerBits << 3) + t;
  6061. });
  6062. // for (var side in sides) {
  6063. // // XX......X where X's are orientation marks
  6064. // var t = ((side >> (length - 2)) << 1) + (side & 1);
  6065. // cornerBits = (cornerBits << 3) + t;
  6066. // }
  6067. // Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
  6068. // together. cornerBits is now:
  6069. // 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
  6070. cornerBits = ((cornerBits & 1) << 11) + (cornerBits >> 1);
  6071. // The result shift indicates which element of BullsEyeCorners[] goes into the top-left
  6072. // corner. Since the four rotation values have a Hamming distance of 8, we
  6073. // can easily tolerate two errors.
  6074. for (let shift = 0; shift < 4; shift++) {
  6075. if (Integer.bitCount(cornerBits ^ this.EXPECTED_CORNER_BITS[shift]) <= 2) {
  6076. return shift;
  6077. }
  6078. }
  6079. throw new NotFoundException();
  6080. }
  6081. /**
  6082. * Corrects the parameter bits using Reed-Solomon algorithm.
  6083. *
  6084. * @param parameterData parameter bits
  6085. * @param compact true if this is a compact Aztec code
  6086. * @throws NotFoundException if the array contains too many errors
  6087. */
  6088. getCorrectedParameterData(parameterData, compact) {
  6089. let numCodewords;
  6090. let numDataCodewords;
  6091. if (compact) {
  6092. numCodewords = 7;
  6093. numDataCodewords = 2;
  6094. }
  6095. else {
  6096. numCodewords = 10;
  6097. numDataCodewords = 4;
  6098. }
  6099. let numECCodewords = numCodewords - numDataCodewords;
  6100. let parameterWords = new Int32Array(numCodewords);
  6101. for (let i = numCodewords - 1; i >= 0; --i) {
  6102. parameterWords[i] = parameterData & 0xF;
  6103. parameterData >>= 4;
  6104. }
  6105. try {
  6106. let rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);
  6107. rsDecoder.decode(parameterWords, numECCodewords);
  6108. }
  6109. catch (ignored) {
  6110. throw new NotFoundException();
  6111. }
  6112. // Toss the error correction. Just return the data as an integer
  6113. let result = 0;
  6114. for (let i = 0; i < numDataCodewords; i++) {
  6115. result = (result << 4) + parameterWords[i];
  6116. }
  6117. return result;
  6118. }
  6119. /**
  6120. * Finds the corners of a bull-eye centered on the passed point.
  6121. * This returns the centers of the diagonal points just outside the bull's eye
  6122. * Returns [topRight, bottomRight, bottomLeft, topLeft]
  6123. *
  6124. * @param pCenter Center point
  6125. * @return The corners of the bull-eye
  6126. * @throws NotFoundException If no valid bull-eye can be found
  6127. */
  6128. getBullsEyeCorners(pCenter) {
  6129. let pina = pCenter;
  6130. let pinb = pCenter;
  6131. let pinc = pCenter;
  6132. let pind = pCenter;
  6133. let color = true;
  6134. for (this.nbCenterLayers = 1; this.nbCenterLayers < 9; this.nbCenterLayers++) {
  6135. let pouta = this.getFirstDifferent(pina, color, 1, -1);
  6136. let poutb = this.getFirstDifferent(pinb, color, 1, 1);
  6137. let poutc = this.getFirstDifferent(pinc, color, -1, 1);
  6138. let poutd = this.getFirstDifferent(pind, color, -1, -1);
  6139. // d a
  6140. //
  6141. // c b
  6142. if (this.nbCenterLayers > 2) {
  6143. let q = (this.distancePoint(poutd, pouta) * this.nbCenterLayers) / (this.distancePoint(pind, pina) * (this.nbCenterLayers + 2));
  6144. if (q < 0.75 || q > 1.25 || !this.isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd)) {
  6145. break;
  6146. }
  6147. }
  6148. pina = pouta;
  6149. pinb = poutb;
  6150. pinc = poutc;
  6151. pind = poutd;
  6152. color = !color;
  6153. }
  6154. if (this.nbCenterLayers !== 5 && this.nbCenterLayers !== 7) {
  6155. throw new NotFoundException();
  6156. }
  6157. this.compact = this.nbCenterLayers === 5;
  6158. // Expand the square by .5 pixel in each direction so that we're on the border
  6159. // between the white square and the black square
  6160. let pinax = new ResultPoint(pina.getX() + 0.5, pina.getY() - 0.5);
  6161. let pinbx = new ResultPoint(pinb.getX() + 0.5, pinb.getY() + 0.5);
  6162. let pincx = new ResultPoint(pinc.getX() - 0.5, pinc.getY() + 0.5);
  6163. let pindx = new ResultPoint(pind.getX() - 0.5, pind.getY() - 0.5);
  6164. // Expand the square so that its corners are the centers of the points
  6165. // just outside the bull's eye.
  6166. return this.expandSquare([pinax, pinbx, pincx, pindx], 2 * this.nbCenterLayers - 3, 2 * this.nbCenterLayers);
  6167. }
  6168. /**
  6169. * Finds a candidate center point of an Aztec code from an image
  6170. *
  6171. * @return the center point
  6172. */
  6173. getMatrixCenter() {
  6174. let pointA;
  6175. let pointB;
  6176. let pointC;
  6177. let pointD;
  6178. // Get a white rectangle that can be the border of the matrix in center bull's eye or
  6179. try {
  6180. let cornerPoints = new WhiteRectangleDetector(this.image).detect();
  6181. pointA = cornerPoints[0];
  6182. pointB = cornerPoints[1];
  6183. pointC = cornerPoints[2];
  6184. pointD = cornerPoints[3];
  6185. }
  6186. catch (e) {
  6187. // This exception can be in case the initial rectangle is white
  6188. // In that case, surely in the bull's eye, we try to expand the rectangle.
  6189. let cx = this.image.getWidth() / 2;
  6190. let cy = this.image.getHeight() / 2;
  6191. pointA = this.getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
  6192. pointB = this.getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
  6193. pointC = this.getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
  6194. pointD = this.getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
  6195. }
  6196. // Compute the center of the rectangle
  6197. let cx = MathUtils.round((pointA.getX() + pointD.getX() + pointB.getX() + pointC.getX()) / 4.0);
  6198. let cy = MathUtils.round((pointA.getY() + pointD.getY() + pointB.getY() + pointC.getY()) / 4.0);
  6199. // Redetermine the white rectangle starting from previously computed center.
  6200. // This will ensure that we end up with a white rectangle in center bull's eye
  6201. // in order to compute a more accurate center.
  6202. try {
  6203. let cornerPoints = new WhiteRectangleDetector(this.image, 15, cx, cy).detect();
  6204. pointA = cornerPoints[0];
  6205. pointB = cornerPoints[1];
  6206. pointC = cornerPoints[2];
  6207. pointD = cornerPoints[3];
  6208. }
  6209. catch (e) {
  6210. // This exception can be in case the initial rectangle is white
  6211. // In that case we try to expand the rectangle.
  6212. pointA = this.getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
  6213. pointB = this.getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
  6214. pointC = this.getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
  6215. pointD = this.getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
  6216. }
  6217. // Recompute the center of the rectangle
  6218. cx = MathUtils.round((pointA.getX() + pointD.getX() + pointB.getX() + pointC.getX()) / 4.0);
  6219. cy = MathUtils.round((pointA.getY() + pointD.getY() + pointB.getY() + pointC.getY()) / 4.0);
  6220. return new Point(cx, cy);
  6221. }
  6222. /**
  6223. * Gets the Aztec code corners from the bull's eye corners and the parameters.
  6224. *
  6225. * @param bullsEyeCorners the array of bull's eye corners
  6226. * @return the array of aztec code corners
  6227. */
  6228. getMatrixCornerPoints(bullsEyeCorners) {
  6229. return this.expandSquare(bullsEyeCorners, 2 * this.nbCenterLayers, this.getDimension());
  6230. }
  6231. /**
  6232. * Creates a BitMatrix by sampling the provided image.
  6233. * topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
  6234. * diagonal just outside the bull's eye.
  6235. */
  6236. sampleGrid(image, topLeft, topRight, bottomRight, bottomLeft) {
  6237. let sampler = GridSamplerInstance.getInstance();
  6238. let dimension = this.getDimension();
  6239. let low = dimension / 2 - this.nbCenterLayers;
  6240. let high = dimension / 2 + this.nbCenterLayers;
  6241. return sampler.sampleGrid(image, dimension, dimension, low, low, // topleft
  6242. high, low, // topright
  6243. high, high, // bottomright
  6244. low, high, // bottomleft
  6245. topLeft.getX(), topLeft.getY(), topRight.getX(), topRight.getY(), bottomRight.getX(), bottomRight.getY(), bottomLeft.getX(), bottomLeft.getY());
  6246. }
  6247. /**
  6248. * Samples a line.
  6249. *
  6250. * @param p1 start point (inclusive)
  6251. * @param p2 end point (exclusive)
  6252. * @param size number of bits
  6253. * @return the array of bits as an int (first bit is high-order bit of result)
  6254. */
  6255. sampleLine(p1, p2, size) {
  6256. let result = 0;
  6257. let d = this.distanceResultPoint(p1, p2);
  6258. let moduleSize = d / size;
  6259. let px = p1.getX();
  6260. let py = p1.getY();
  6261. let dx = moduleSize * (p2.getX() - p1.getX()) / d;
  6262. let dy = moduleSize * (p2.getY() - p1.getY()) / d;
  6263. for (let i = 0; i < size; i++) {
  6264. if (this.image.get(MathUtils.round(px + i * dx), MathUtils.round(py + i * dy))) {
  6265. result |= 1 << (size - i - 1);
  6266. }
  6267. }
  6268. return result;
  6269. }
  6270. /**
  6271. * @return true if the border of the rectangle passed in parameter is compound of white points only
  6272. * or black points only
  6273. */
  6274. isWhiteOrBlackRectangle(p1, p2, p3, p4) {
  6275. let corr = 3;
  6276. p1 = new Point(p1.getX() - corr, p1.getY() + corr);
  6277. p2 = new Point(p2.getX() - corr, p2.getY() - corr);
  6278. p3 = new Point(p3.getX() + corr, p3.getY() - corr);
  6279. p4 = new Point(p4.getX() + corr, p4.getY() + corr);
  6280. let cInit = this.getColor(p4, p1);
  6281. if (cInit === 0) {
  6282. return false;
  6283. }
  6284. let c = this.getColor(p1, p2);
  6285. if (c !== cInit) {
  6286. return false;
  6287. }
  6288. c = this.getColor(p2, p3);
  6289. if (c !== cInit) {
  6290. return false;
  6291. }
  6292. c = this.getColor(p3, p4);
  6293. return c === cInit;
  6294. }
  6295. /**
  6296. * Gets the color of a segment
  6297. *
  6298. * @return 1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else
  6299. */
  6300. getColor(p1, p2) {
  6301. let d = this.distancePoint(p1, p2);
  6302. let dx = (p2.getX() - p1.getX()) / d;
  6303. let dy = (p2.getY() - p1.getY()) / d;
  6304. let error = 0;
  6305. let px = p1.getX();
  6306. let py = p1.getY();
  6307. let colorModel = this.image.get(p1.getX(), p1.getY());
  6308. let iMax = Math.ceil(d);
  6309. for (let i = 0; i < iMax; i++) {
  6310. px += dx;
  6311. py += dy;
  6312. if (this.image.get(MathUtils.round(px), MathUtils.round(py)) !== colorModel) {
  6313. error++;
  6314. }
  6315. }
  6316. let errRatio = error / d;
  6317. if (errRatio > 0.1 && errRatio < 0.9) {
  6318. return 0;
  6319. }
  6320. return (errRatio <= 0.1) === colorModel ? 1 : -1;
  6321. }
  6322. /**
  6323. * Gets the coordinate of the first point with a different color in the given direction
  6324. */
  6325. getFirstDifferent(init, color, dx, dy) {
  6326. let x = init.getX() + dx;
  6327. let y = init.getY() + dy;
  6328. while (this.isValid(x, y) && this.image.get(x, y) === color) {
  6329. x += dx;
  6330. y += dy;
  6331. }
  6332. x -= dx;
  6333. y -= dy;
  6334. while (this.isValid(x, y) && this.image.get(x, y) === color) {
  6335. x += dx;
  6336. }
  6337. x -= dx;
  6338. while (this.isValid(x, y) && this.image.get(x, y) === color) {
  6339. y += dy;
  6340. }
  6341. y -= dy;
  6342. return new Point(x, y);
  6343. }
  6344. /**
  6345. * Expand the square represented by the corner points by pushing out equally in all directions
  6346. *
  6347. * @param cornerPoints the corners of the square, which has the bull's eye at its center
  6348. * @param oldSide the original length of the side of the square in the target bit matrix
  6349. * @param newSide the new length of the size of the square in the target bit matrix
  6350. * @return the corners of the expanded square
  6351. */
  6352. expandSquare(cornerPoints, oldSide, newSide) {
  6353. let ratio = newSide / (2.0 * oldSide);
  6354. let dx = cornerPoints[0].getX() - cornerPoints[2].getX();
  6355. let dy = cornerPoints[0].getY() - cornerPoints[2].getY();
  6356. let centerx = (cornerPoints[0].getX() + cornerPoints[2].getX()) / 2.0;
  6357. let centery = (cornerPoints[0].getY() + cornerPoints[2].getY()) / 2.0;
  6358. let result0 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
  6359. let result2 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
  6360. dx = cornerPoints[1].getX() - cornerPoints[3].getX();
  6361. dy = cornerPoints[1].getY() - cornerPoints[3].getY();
  6362. centerx = (cornerPoints[1].getX() + cornerPoints[3].getX()) / 2.0;
  6363. centery = (cornerPoints[1].getY() + cornerPoints[3].getY()) / 2.0;
  6364. let result1 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
  6365. let result3 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
  6366. let results = [result0, result1, result2, result3];
  6367. return results;
  6368. }
  6369. isValid(x, y) {
  6370. return x >= 0 && x < this.image.getWidth() && y > 0 && y < this.image.getHeight();
  6371. }
  6372. isValidPoint(point) {
  6373. let x = MathUtils.round(point.getX());
  6374. let y = MathUtils.round(point.getY());
  6375. return this.isValid(x, y);
  6376. }
  6377. distancePoint(a, b) {
  6378. return MathUtils.distance(a.getX(), a.getY(), b.getX(), b.getY());
  6379. }
  6380. distanceResultPoint(a, b) {
  6381. return MathUtils.distance(a.getX(), a.getY(), b.getX(), b.getY());
  6382. }
  6383. getDimension() {
  6384. if (this.compact) {
  6385. return 4 * this.nbLayers + 11;
  6386. }
  6387. if (this.nbLayers <= 4) {
  6388. return 4 * this.nbLayers + 15;
  6389. }
  6390. return 4 * this.nbLayers + 2 * (Integer.truncDivision((this.nbLayers - 4), 8) + 1) + 15;
  6391. }
  6392. }
  6393. /*
  6394. * Copyright 2010 ZXing authors
  6395. *
  6396. * Licensed under the Apache License, Version 2.0 (the "License");
  6397. * you may not use this file except in compliance with the License.
  6398. * You may obtain a copy of the License at
  6399. *
  6400. * http://www.apache.org/licenses/LICENSE-2.0
  6401. *
  6402. * Unless required by applicable law or agreed to in writing, software
  6403. * distributed under the License is distributed on an "AS IS" BASIS,
  6404. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6405. * See the License for the specific language governing permissions and
  6406. * limitations under the License.
  6407. */
  6408. // import java.util.List;
  6409. // import java.util.Map;
  6410. /**
  6411. * This implementation can detect and decode Aztec codes in an image.
  6412. *
  6413. * @author David Olivier
  6414. */
  6415. class AztecReader {
  6416. /**
  6417. * Locates and decodes a Data Matrix code in an image.
  6418. *
  6419. * @return a String representing the content encoded by the Data Matrix code
  6420. * @throws NotFoundException if a Data Matrix code cannot be found
  6421. * @throws FormatException if a Data Matrix code cannot be decoded
  6422. */
  6423. decode(image, hints = null) {
  6424. let exception = null;
  6425. let detector = new Detector(image.getBlackMatrix());
  6426. let points = null;
  6427. let decoderResult = null;
  6428. try {
  6429. let detectorResult = detector.detectMirror(false);
  6430. points = detectorResult.getPoints();
  6431. this.reportFoundResultPoints(hints, points);
  6432. decoderResult = new Decoder().decode(detectorResult);
  6433. }
  6434. catch (e) {
  6435. exception = e;
  6436. }
  6437. if (decoderResult == null) {
  6438. try {
  6439. let detectorResult = detector.detectMirror(true);
  6440. points = detectorResult.getPoints();
  6441. this.reportFoundResultPoints(hints, points);
  6442. decoderResult = new Decoder().decode(detectorResult);
  6443. }
  6444. catch (e) {
  6445. if (exception != null) {
  6446. throw exception;
  6447. }
  6448. throw e;
  6449. }
  6450. }
  6451. let result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), decoderResult.getNumBits(), points, BarcodeFormat$1.AZTEC, System.currentTimeMillis());
  6452. let byteSegments = decoderResult.getByteSegments();
  6453. if (byteSegments != null) {
  6454. result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS, byteSegments);
  6455. }
  6456. let ecLevel = decoderResult.getECLevel();
  6457. if (ecLevel != null) {
  6458. result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL, ecLevel);
  6459. }
  6460. return result;
  6461. }
  6462. reportFoundResultPoints(hints, points) {
  6463. if (hints != null) {
  6464. let rpcb = hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);
  6465. if (rpcb != null) {
  6466. points.forEach((point, idx, arr) => {
  6467. rpcb.foundPossibleResultPoint(point);
  6468. });
  6469. }
  6470. }
  6471. }
  6472. // @Override
  6473. reset() {
  6474. // do nothing
  6475. }
  6476. }
  6477. /**
  6478. * Aztec Code reader to use from browser.
  6479. *
  6480. * @class BrowserAztecCodeReader
  6481. * @extends {BrowserCodeReader}
  6482. */
  6483. class BrowserAztecCodeReader extends BrowserCodeReader {
  6484. /**
  6485. * Creates an instance of BrowserAztecCodeReader.
  6486. * @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
  6487. *
  6488. * @memberOf BrowserAztecCodeReader
  6489. */
  6490. constructor(timeBetweenScansMillis = 500) {
  6491. super(new AztecReader(), timeBetweenScansMillis);
  6492. }
  6493. }
  6494. /*
  6495. * Copyright 2008 ZXing authors
  6496. *
  6497. * Licensed under the Apache License, Version 2.0 (the "License");
  6498. * you may not use this file except in compliance with the License.
  6499. * You may obtain a copy of the License at
  6500. *
  6501. * http://www.apache.org/licenses/LICENSE-2.0
  6502. *
  6503. * Unless required by applicable law or agreed to in writing, software
  6504. * distributed under the License is distributed on an "AS IS" BASIS,
  6505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6506. * See the License for the specific language governing permissions and
  6507. * limitations under the License.
  6508. */
  6509. /**
  6510. * Encapsulates functionality and implementation that is common to all families
  6511. * of one-dimensional barcodes.
  6512. *
  6513. * @author dswitkin@google.com (Daniel Switkin)
  6514. * @author Sean Owen
  6515. */
  6516. class OneDReader {
  6517. /*
  6518. @Override
  6519. public Result decode(BinaryBitmap image) throws NotFoundException, FormatException {
  6520. return decode(image, null);
  6521. }
  6522. */
  6523. // Note that we don't try rotation without the try harder flag, even if rotation was supported.
  6524. // @Override
  6525. decode(image, hints) {
  6526. try {
  6527. return this.doDecode(image, hints);
  6528. }
  6529. catch (nfe) {
  6530. const tryHarder = hints && (hints.get(DecodeHintType$1.TRY_HARDER) === true);
  6531. if (tryHarder && image.isRotateSupported()) {
  6532. const rotatedImage = image.rotateCounterClockwise();
  6533. const result = this.doDecode(rotatedImage, hints);
  6534. // Record that we found it rotated 90 degrees CCW / 270 degrees CW
  6535. const metadata = result.getResultMetadata();
  6536. let orientation = 270;
  6537. if (metadata !== null && (metadata.get(ResultMetadataType$1.ORIENTATION) === true)) {
  6538. // But if we found it reversed in doDecode(), add in that result here:
  6539. orientation = (orientation + metadata.get(ResultMetadataType$1.ORIENTATION) % 360);
  6540. }
  6541. result.putMetadata(ResultMetadataType$1.ORIENTATION, orientation);
  6542. // Update result points
  6543. const points = result.getResultPoints();
  6544. if (points !== null) {
  6545. const height = rotatedImage.getHeight();
  6546. for (let i = 0; i < points.length; i++) {
  6547. points[i] = new ResultPoint(height - points[i].getY() - 1, points[i].getX());
  6548. }
  6549. }
  6550. return result;
  6551. }
  6552. else {
  6553. throw new NotFoundException();
  6554. }
  6555. }
  6556. }
  6557. // @Override
  6558. reset() {
  6559. // do nothing
  6560. }
  6561. /**
  6562. * We're going to examine rows from the middle outward, searching alternately above and below the
  6563. * middle, and farther out each time. rowStep is the number of rows between each successive
  6564. * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
  6565. * middle + rowStep, then middle - (2 * rowStep), etc.
  6566. * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
  6567. * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
  6568. * image if "trying harder".
  6569. *
  6570. * @param image The image to decode
  6571. * @param hints Any hints that were requested
  6572. * @return The contents of the decoded barcode
  6573. * @throws NotFoundException Any spontaneous errors which occur
  6574. */
  6575. doDecode(image, hints) {
  6576. const width = image.getWidth();
  6577. const height = image.getHeight();
  6578. let row = new BitArray(width);
  6579. const tryHarder = hints && (hints.get(DecodeHintType$1.TRY_HARDER) === true);
  6580. const rowStep = Math.max(1, height >> (tryHarder ? 8 : 5));
  6581. let maxLines;
  6582. if (tryHarder) {
  6583. maxLines = height; // Look at the whole image, not just the center
  6584. }
  6585. else {
  6586. maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image
  6587. }
  6588. const middle = Math.trunc(height / 2);
  6589. for (let x = 0; x < maxLines; x++) {
  6590. // Scanning from the middle out. Determine which row we're looking at next:
  6591. const rowStepsAboveOrBelow = Math.trunc((x + 1) / 2);
  6592. const isAbove = (x & 0x01) === 0; // i.e. is x even?
  6593. const rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
  6594. if (rowNumber < 0 || rowNumber >= height) {
  6595. // Oops, if we run off the top or bottom, stop
  6596. break;
  6597. }
  6598. // Estimate black point for this row and load it:
  6599. try {
  6600. row = image.getBlackRow(rowNumber, row);
  6601. }
  6602. catch (ignored) {
  6603. continue;
  6604. }
  6605. // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
  6606. // handle decoding upside down barcodes.
  6607. for (let attempt = 0; attempt < 2; attempt++) {
  6608. if (attempt === 1) { // trying again?
  6609. row.reverse(); // reverse the row and continue
  6610. // This means we will only ever draw result points *once* in the life of this method
  6611. // since we want to avoid drawing the wrong points after flipping the row, and,
  6612. // don't want to clutter with noise from every single row scan -- just the scans
  6613. // that start on the center line.
  6614. if (hints && (hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK) === true)) {
  6615. const newHints = new Map();
  6616. hints.forEach((hint, key) => newHints.set(key, hint));
  6617. newHints.delete(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);
  6618. hints = newHints;
  6619. }
  6620. }
  6621. try {
  6622. // Look for a barcode
  6623. const result = this.decodeRow(rowNumber, row, hints);
  6624. // We found our barcode
  6625. if (attempt === 1) {
  6626. // But it was upside down, so note that
  6627. result.putMetadata(ResultMetadataType$1.ORIENTATION, 180);
  6628. // And remember to flip the result points horizontally.
  6629. const points = result.getResultPoints();
  6630. if (points !== null) {
  6631. points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());
  6632. points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());
  6633. }
  6634. }
  6635. return result;
  6636. }
  6637. catch (re) {
  6638. // continue -- just couldn't decode this row
  6639. }
  6640. }
  6641. }
  6642. throw new NotFoundException();
  6643. }
  6644. /**
  6645. * Records the size of successive runs of white and black pixels in a row, starting at a given point.
  6646. * The values are recorded in the given array, and the number of runs recorded is equal to the size
  6647. * of the array. If the row starts on a white pixel at the given start point, then the first count
  6648. * recorded is the run of white pixels starting from that point; likewise it is the count of a run
  6649. * of black pixels if the row begin on a black pixels at that point.
  6650. *
  6651. * @param row row to count from
  6652. * @param start offset into row to start at
  6653. * @param counters array into which to record counts
  6654. * @throws NotFoundException if counters cannot be filled entirely from row before running out
  6655. * of pixels
  6656. */
  6657. static recordPattern(row, start, counters) {
  6658. const numCounters = counters.length;
  6659. for (let index = 0; index < numCounters; index++)
  6660. counters[index] = 0;
  6661. const end = row.getSize();
  6662. if (start >= end) {
  6663. throw new NotFoundException();
  6664. }
  6665. let isWhite = !row.get(start);
  6666. let counterPosition = 0;
  6667. let i = start;
  6668. while (i < end) {
  6669. if (row.get(i) !== isWhite) {
  6670. counters[counterPosition]++;
  6671. }
  6672. else {
  6673. if (++counterPosition === numCounters) {
  6674. break;
  6675. }
  6676. else {
  6677. counters[counterPosition] = 1;
  6678. isWhite = !isWhite;
  6679. }
  6680. }
  6681. i++;
  6682. }
  6683. // If we read fully the last section of pixels and filled up our counters -- or filled
  6684. // the last counter but ran off the side of the image, OK. Otherwise, a problem.
  6685. if (!(counterPosition === numCounters || (counterPosition === numCounters - 1 && i === end))) {
  6686. throw new NotFoundException();
  6687. }
  6688. }
  6689. static recordPatternInReverse(row, start, counters) {
  6690. // This could be more efficient I guess
  6691. let numTransitionsLeft = counters.length;
  6692. let last = row.get(start);
  6693. while (start > 0 && numTransitionsLeft >= 0) {
  6694. if (row.get(--start) !== last) {
  6695. numTransitionsLeft--;
  6696. last = !last;
  6697. }
  6698. }
  6699. if (numTransitionsLeft >= 0) {
  6700. throw new NotFoundException();
  6701. }
  6702. OneDReader.recordPattern(row, start + 1, counters);
  6703. }
  6704. /**
  6705. * Determines how closely a set of observed counts of runs of black/white values matches a given
  6706. * target pattern. This is reported as the ratio of the total variance from the expected pattern
  6707. * proportions across all pattern elements, to the length of the pattern.
  6708. *
  6709. * @param counters observed counters
  6710. * @param pattern expected pattern
  6711. * @param maxIndividualVariance The most any counter can differ before we give up
  6712. * @return ratio of total variance between counters and pattern compared to total pattern size
  6713. */
  6714. static patternMatchVariance(counters, pattern, maxIndividualVariance) {
  6715. const numCounters = counters.length;
  6716. let total = 0;
  6717. let patternLength = 0;
  6718. for (let i = 0; i < numCounters; i++) {
  6719. total += counters[i];
  6720. patternLength += pattern[i];
  6721. }
  6722. if (total < patternLength) {
  6723. // If we don't even have one pixel per unit of bar width, assume this is too small
  6724. // to reliably match, so fail:
  6725. return Number.POSITIVE_INFINITY;
  6726. }
  6727. const unitBarWidth = total / patternLength;
  6728. maxIndividualVariance *= unitBarWidth;
  6729. let totalVariance = 0.0;
  6730. for (let x = 0; x < numCounters; x++) {
  6731. const counter = counters[x];
  6732. const scaledPattern = pattern[x] * unitBarWidth;
  6733. const variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
  6734. if (variance > maxIndividualVariance) {
  6735. return Number.POSITIVE_INFINITY;
  6736. }
  6737. totalVariance += variance;
  6738. }
  6739. return totalVariance / total;
  6740. }
  6741. }
  6742. /*
  6743. * Copyright 2008 ZXing authors
  6744. *
  6745. * Licensed under the Apache License, Version 2.0 (the "License");
  6746. * you may not use this file except in compliance with the License.
  6747. * You may obtain a copy of the License at
  6748. *
  6749. * http://www.apache.org/licenses/LICENSE-2.0
  6750. *
  6751. * Unless required by applicable law or agreed to in writing, software
  6752. * distributed under the License is distributed on an "AS IS" BASIS,
  6753. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6754. * See the License for the specific language governing permissions and
  6755. * limitations under the License.
  6756. */
  6757. /**
  6758. * <p>Decodes Code 128 barcodes.</p>
  6759. *
  6760. * @author Sean Owen
  6761. */
  6762. class Code128Reader extends OneDReader {
  6763. static findStartPattern(row) {
  6764. const width = row.getSize();
  6765. const rowOffset = row.getNextSet(0);
  6766. let counterPosition = 0;
  6767. let counters = Int32Array.from([0, 0, 0, 0, 0, 0]);
  6768. let patternStart = rowOffset;
  6769. let isWhite = false;
  6770. const patternLength = 6;
  6771. for (let i = rowOffset; i < width; i++) {
  6772. if (row.get(i) !== isWhite) {
  6773. counters[counterPosition]++;
  6774. }
  6775. else {
  6776. if (counterPosition === (patternLength - 1)) {
  6777. let bestVariance = Code128Reader.MAX_AVG_VARIANCE;
  6778. let bestMatch = -1;
  6779. for (let startCode = Code128Reader.CODE_START_A; startCode <= Code128Reader.CODE_START_C; startCode++) {
  6780. const variance = OneDReader.patternMatchVariance(counters, Code128Reader.CODE_PATTERNS[startCode], Code128Reader.MAX_INDIVIDUAL_VARIANCE);
  6781. if (variance < bestVariance) {
  6782. bestVariance = variance;
  6783. bestMatch = startCode;
  6784. }
  6785. }
  6786. // Look for whitespace before start pattern, >= 50% of width of start pattern
  6787. if (bestMatch >= 0 &&
  6788. row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
  6789. return Int32Array.from([patternStart, i, bestMatch]);
  6790. }
  6791. patternStart += counters[0] + counters[1];
  6792. counters = counters.slice(2, counters.length - 1);
  6793. counters[counterPosition - 1] = 0;
  6794. counters[counterPosition] = 0;
  6795. counterPosition--;
  6796. }
  6797. else {
  6798. counterPosition++;
  6799. }
  6800. counters[counterPosition] = 1;
  6801. isWhite = !isWhite;
  6802. }
  6803. }
  6804. throw new NotFoundException();
  6805. }
  6806. static decodeCode(row, counters, rowOffset) {
  6807. OneDReader.recordPattern(row, rowOffset, counters);
  6808. let bestVariance = Code128Reader.MAX_AVG_VARIANCE; // worst variance we'll accept
  6809. let bestMatch = -1;
  6810. for (let d = 0; d < Code128Reader.CODE_PATTERNS.length; d++) {
  6811. const pattern = Code128Reader.CODE_PATTERNS[d];
  6812. const variance = this.patternMatchVariance(counters, pattern, Code128Reader.MAX_INDIVIDUAL_VARIANCE);
  6813. if (variance < bestVariance) {
  6814. bestVariance = variance;
  6815. bestMatch = d;
  6816. }
  6817. }
  6818. // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6.
  6819. if (bestMatch >= 0) {
  6820. return bestMatch;
  6821. }
  6822. else {
  6823. throw new NotFoundException();
  6824. }
  6825. }
  6826. decodeRow(rowNumber, row, hints) {
  6827. const convertFNC1 = hints && (hints.get(DecodeHintType$1.ASSUME_GS1) === true);
  6828. const startPatternInfo = Code128Reader.findStartPattern(row);
  6829. const startCode = startPatternInfo[2];
  6830. let currentRawCodesIndex = 0;
  6831. const rawCodes = new Uint8Array(20);
  6832. rawCodes[currentRawCodesIndex++] = startCode;
  6833. let codeSet;
  6834. switch (startCode) {
  6835. case Code128Reader.CODE_START_A:
  6836. codeSet = Code128Reader.CODE_CODE_A;
  6837. break;
  6838. case Code128Reader.CODE_START_B:
  6839. codeSet = Code128Reader.CODE_CODE_B;
  6840. break;
  6841. case Code128Reader.CODE_START_C:
  6842. codeSet = Code128Reader.CODE_CODE_C;
  6843. break;
  6844. default:
  6845. throw new FormatException();
  6846. }
  6847. let done = false;
  6848. let isNextShifted = false;
  6849. let result = '';
  6850. let lastStart = startPatternInfo[0];
  6851. let nextStart = startPatternInfo[1];
  6852. const counters = Int32Array.from([0, 0, 0, 0, 0, 0]);
  6853. let lastCode = 0;
  6854. let code = 0;
  6855. let checksumTotal = startCode;
  6856. let multiplier = 0;
  6857. let lastCharacterWasPrintable = true;
  6858. let upperMode = false;
  6859. let shiftUpperMode = false;
  6860. while (!done) {
  6861. const unshift = isNextShifted;
  6862. isNextShifted = false;
  6863. // Save off last code
  6864. lastCode = code;
  6865. // Decode another code from image
  6866. code = Code128Reader.decodeCode(row, counters, nextStart);
  6867. rawCodes[currentRawCodesIndex++] = code;
  6868. // Remember whether the last code was printable or not (excluding CODE_STOP)
  6869. if (code !== Code128Reader.CODE_STOP) {
  6870. lastCharacterWasPrintable = true;
  6871. }
  6872. // Add to checksum computation (if not CODE_STOP of course)
  6873. if (code !== Code128Reader.CODE_STOP) {
  6874. multiplier++;
  6875. checksumTotal += multiplier * code;
  6876. }
  6877. // Advance to where the next code will to start
  6878. lastStart = nextStart;
  6879. nextStart += counters.reduce((previous, current) => previous + current, 0);
  6880. // Take care of illegal start codes
  6881. switch (code) {
  6882. case Code128Reader.CODE_START_A:
  6883. case Code128Reader.CODE_START_B:
  6884. case Code128Reader.CODE_START_C:
  6885. throw new FormatException();
  6886. }
  6887. switch (codeSet) {
  6888. case Code128Reader.CODE_CODE_A:
  6889. if (code < 64) {
  6890. if (shiftUpperMode === upperMode) {
  6891. result += String.fromCharCode((' '.charCodeAt(0) + code));
  6892. }
  6893. else {
  6894. result += String.fromCharCode((' '.charCodeAt(0) + code + 128));
  6895. }
  6896. shiftUpperMode = false;
  6897. }
  6898. else if (code < 96) {
  6899. if (shiftUpperMode === upperMode) {
  6900. result += String.fromCharCode((code - 64));
  6901. }
  6902. else {
  6903. result += String.fromCharCode((code + 64));
  6904. }
  6905. shiftUpperMode = false;
  6906. }
  6907. else {
  6908. // Don't let CODE_STOP, which always appears, affect whether whether we think the last
  6909. // code was printable or not.
  6910. if (code !== Code128Reader.CODE_STOP) {
  6911. lastCharacterWasPrintable = false;
  6912. }
  6913. switch (code) {
  6914. case Code128Reader.CODE_FNC_1:
  6915. if (convertFNC1) {
  6916. if (result.length === 0) {
  6917. // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
  6918. // is FNC1 then this is GS1-128. We add the symbology identifier.
  6919. result += ']C1';
  6920. }
  6921. else {
  6922. // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
  6923. result += String.fromCharCode(29);
  6924. }
  6925. }
  6926. break;
  6927. case Code128Reader.CODE_FNC_2:
  6928. case Code128Reader.CODE_FNC_3:
  6929. // do nothing?
  6930. break;
  6931. case Code128Reader.CODE_FNC_4_A:
  6932. if (!upperMode && shiftUpperMode) {
  6933. upperMode = true;
  6934. shiftUpperMode = false;
  6935. }
  6936. else if (upperMode && shiftUpperMode) {
  6937. upperMode = false;
  6938. shiftUpperMode = false;
  6939. }
  6940. else {
  6941. shiftUpperMode = true;
  6942. }
  6943. break;
  6944. case Code128Reader.CODE_SHIFT:
  6945. isNextShifted = true;
  6946. codeSet = Code128Reader.CODE_CODE_B;
  6947. break;
  6948. case Code128Reader.CODE_CODE_B:
  6949. codeSet = Code128Reader.CODE_CODE_B;
  6950. break;
  6951. case Code128Reader.CODE_CODE_C:
  6952. codeSet = Code128Reader.CODE_CODE_C;
  6953. break;
  6954. case Code128Reader.CODE_STOP:
  6955. done = true;
  6956. break;
  6957. }
  6958. }
  6959. break;
  6960. case Code128Reader.CODE_CODE_B:
  6961. if (code < 96) {
  6962. if (shiftUpperMode === upperMode) {
  6963. result += String.fromCharCode((' '.charCodeAt(0) + code));
  6964. }
  6965. else {
  6966. result += String.fromCharCode((' '.charCodeAt(0) + code + 128));
  6967. }
  6968. shiftUpperMode = false;
  6969. }
  6970. else {
  6971. if (code !== Code128Reader.CODE_STOP) {
  6972. lastCharacterWasPrintable = false;
  6973. }
  6974. switch (code) {
  6975. case Code128Reader.CODE_FNC_1:
  6976. if (convertFNC1) {
  6977. if (result.length === 0) {
  6978. // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
  6979. // is FNC1 then this is GS1-128. We add the symbology identifier.
  6980. result += ']C1';
  6981. }
  6982. else {
  6983. // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
  6984. result += String.fromCharCode(29);
  6985. }
  6986. }
  6987. break;
  6988. case Code128Reader.CODE_FNC_2:
  6989. case Code128Reader.CODE_FNC_3:
  6990. // do nothing?
  6991. break;
  6992. case Code128Reader.CODE_FNC_4_B:
  6993. if (!upperMode && shiftUpperMode) {
  6994. upperMode = true;
  6995. shiftUpperMode = false;
  6996. }
  6997. else if (upperMode && shiftUpperMode) {
  6998. upperMode = false;
  6999. shiftUpperMode = false;
  7000. }
  7001. else {
  7002. shiftUpperMode = true;
  7003. }
  7004. break;
  7005. case Code128Reader.CODE_SHIFT:
  7006. isNextShifted = true;
  7007. codeSet = Code128Reader.CODE_CODE_A;
  7008. break;
  7009. case Code128Reader.CODE_CODE_A:
  7010. codeSet = Code128Reader.CODE_CODE_A;
  7011. break;
  7012. case Code128Reader.CODE_CODE_C:
  7013. codeSet = Code128Reader.CODE_CODE_C;
  7014. break;
  7015. case Code128Reader.CODE_STOP:
  7016. done = true;
  7017. break;
  7018. }
  7019. }
  7020. break;
  7021. case Code128Reader.CODE_CODE_C:
  7022. if (code < 100) {
  7023. if (code < 10) {
  7024. result += '0';
  7025. }
  7026. result += code;
  7027. }
  7028. else {
  7029. if (code !== Code128Reader.CODE_STOP) {
  7030. lastCharacterWasPrintable = false;
  7031. }
  7032. switch (code) {
  7033. case Code128Reader.CODE_FNC_1:
  7034. if (convertFNC1) {
  7035. if (result.length === 0) {
  7036. // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
  7037. // is FNC1 then this is GS1-128. We add the symbology identifier.
  7038. result += ']C1';
  7039. }
  7040. else {
  7041. // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
  7042. result += String.fromCharCode(29);
  7043. }
  7044. }
  7045. break;
  7046. case Code128Reader.CODE_CODE_A:
  7047. codeSet = Code128Reader.CODE_CODE_A;
  7048. break;
  7049. case Code128Reader.CODE_CODE_B:
  7050. codeSet = Code128Reader.CODE_CODE_B;
  7051. break;
  7052. case Code128Reader.CODE_STOP:
  7053. done = true;
  7054. break;
  7055. }
  7056. }
  7057. break;
  7058. }
  7059. // Unshift back to another code set if we were shifted
  7060. if (unshift) {
  7061. codeSet = codeSet === Code128Reader.CODE_CODE_A ? Code128Reader.CODE_CODE_B : Code128Reader.CODE_CODE_A;
  7062. }
  7063. }
  7064. const lastPatternSize = nextStart - lastStart;
  7065. // Check for ample whitespace following pattern, but, to do this we first need to remember that
  7066. // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left
  7067. // to read off. Would be slightly better to properly read. Here we just skip it:
  7068. nextStart = row.getNextUnset(nextStart);
  7069. if (!row.isRange(nextStart, Math.min(row.getSize(), nextStart + (nextStart - lastStart) / 2), false)) {
  7070. throw new NotFoundException();
  7071. }
  7072. // Pull out from sum the value of the penultimate check code
  7073. checksumTotal -= multiplier * lastCode;
  7074. // lastCode is the checksum then:
  7075. if (checksumTotal % 103 !== lastCode) {
  7076. throw new ChecksumException();
  7077. }
  7078. // Need to pull out the check digits from string
  7079. const resultLength = result.length;
  7080. if (resultLength === 0) {
  7081. // false positive
  7082. throw new NotFoundException();
  7083. }
  7084. // Only bother if the result had at least one character, and if the checksum digit happened to
  7085. // be a printable character. If it was just interpreted as a control code, nothing to remove.
  7086. if (resultLength > 0 && lastCharacterWasPrintable) {
  7087. if (codeSet === Code128Reader.CODE_CODE_C) {
  7088. result = result.substring(0, resultLength - 2);
  7089. }
  7090. else {
  7091. result = result.substring(0, resultLength - 1);
  7092. }
  7093. }
  7094. const left = (startPatternInfo[1] + startPatternInfo[0]) / 2.0;
  7095. const right = lastStart + lastPatternSize / 2.0;
  7096. const rawCodesSize = rawCodes.length;
  7097. const rawBytes = new Uint8Array(rawCodesSize);
  7098. for (let i = 0; i < rawCodesSize; i++) {
  7099. rawBytes[i] = rawCodes[i];
  7100. }
  7101. const points = [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)];
  7102. return new Result(result, rawBytes, 0, points, BarcodeFormat$1.CODE_128, new Date().getTime());
  7103. }
  7104. }
  7105. Code128Reader.CODE_PATTERNS = [
  7106. Int32Array.from([2, 1, 2, 2, 2, 2]),
  7107. Int32Array.from([2, 2, 2, 1, 2, 2]),
  7108. Int32Array.from([2, 2, 2, 2, 2, 1]),
  7109. Int32Array.from([1, 2, 1, 2, 2, 3]),
  7110. Int32Array.from([1, 2, 1, 3, 2, 2]),
  7111. Int32Array.from([1, 3, 1, 2, 2, 2]),
  7112. Int32Array.from([1, 2, 2, 2, 1, 3]),
  7113. Int32Array.from([1, 2, 2, 3, 1, 2]),
  7114. Int32Array.from([1, 3, 2, 2, 1, 2]),
  7115. Int32Array.from([2, 2, 1, 2, 1, 3]),
  7116. Int32Array.from([2, 2, 1, 3, 1, 2]),
  7117. Int32Array.from([2, 3, 1, 2, 1, 2]),
  7118. Int32Array.from([1, 1, 2, 2, 3, 2]),
  7119. Int32Array.from([1, 2, 2, 1, 3, 2]),
  7120. Int32Array.from([1, 2, 2, 2, 3, 1]),
  7121. Int32Array.from([1, 1, 3, 2, 2, 2]),
  7122. Int32Array.from([1, 2, 3, 1, 2, 2]),
  7123. Int32Array.from([1, 2, 3, 2, 2, 1]),
  7124. Int32Array.from([2, 2, 3, 2, 1, 1]),
  7125. Int32Array.from([2, 2, 1, 1, 3, 2]),
  7126. Int32Array.from([2, 2, 1, 2, 3, 1]),
  7127. Int32Array.from([2, 1, 3, 2, 1, 2]),
  7128. Int32Array.from([2, 2, 3, 1, 1, 2]),
  7129. Int32Array.from([3, 1, 2, 1, 3, 1]),
  7130. Int32Array.from([3, 1, 1, 2, 2, 2]),
  7131. Int32Array.from([3, 2, 1, 1, 2, 2]),
  7132. Int32Array.from([3, 2, 1, 2, 2, 1]),
  7133. Int32Array.from([3, 1, 2, 2, 1, 2]),
  7134. Int32Array.from([3, 2, 2, 1, 1, 2]),
  7135. Int32Array.from([3, 2, 2, 2, 1, 1]),
  7136. Int32Array.from([2, 1, 2, 1, 2, 3]),
  7137. Int32Array.from([2, 1, 2, 3, 2, 1]),
  7138. Int32Array.from([2, 3, 2, 1, 2, 1]),
  7139. Int32Array.from([1, 1, 1, 3, 2, 3]),
  7140. Int32Array.from([1, 3, 1, 1, 2, 3]),
  7141. Int32Array.from([1, 3, 1, 3, 2, 1]),
  7142. Int32Array.from([1, 1, 2, 3, 1, 3]),
  7143. Int32Array.from([1, 3, 2, 1, 1, 3]),
  7144. Int32Array.from([1, 3, 2, 3, 1, 1]),
  7145. Int32Array.from([2, 1, 1, 3, 1, 3]),
  7146. Int32Array.from([2, 3, 1, 1, 1, 3]),
  7147. Int32Array.from([2, 3, 1, 3, 1, 1]),
  7148. Int32Array.from([1, 1, 2, 1, 3, 3]),
  7149. Int32Array.from([1, 1, 2, 3, 3, 1]),
  7150. Int32Array.from([1, 3, 2, 1, 3, 1]),
  7151. Int32Array.from([1, 1, 3, 1, 2, 3]),
  7152. Int32Array.from([1, 1, 3, 3, 2, 1]),
  7153. Int32Array.from([1, 3, 3, 1, 2, 1]),
  7154. Int32Array.from([3, 1, 3, 1, 2, 1]),
  7155. Int32Array.from([2, 1, 1, 3, 3, 1]),
  7156. Int32Array.from([2, 3, 1, 1, 3, 1]),
  7157. Int32Array.from([2, 1, 3, 1, 1, 3]),
  7158. Int32Array.from([2, 1, 3, 3, 1, 1]),
  7159. Int32Array.from([2, 1, 3, 1, 3, 1]),
  7160. Int32Array.from([3, 1, 1, 1, 2, 3]),
  7161. Int32Array.from([3, 1, 1, 3, 2, 1]),
  7162. Int32Array.from([3, 3, 1, 1, 2, 1]),
  7163. Int32Array.from([3, 1, 2, 1, 1, 3]),
  7164. Int32Array.from([3, 1, 2, 3, 1, 1]),
  7165. Int32Array.from([3, 3, 2, 1, 1, 1]),
  7166. Int32Array.from([3, 1, 4, 1, 1, 1]),
  7167. Int32Array.from([2, 2, 1, 4, 1, 1]),
  7168. Int32Array.from([4, 3, 1, 1, 1, 1]),
  7169. Int32Array.from([1, 1, 1, 2, 2, 4]),
  7170. Int32Array.from([1, 1, 1, 4, 2, 2]),
  7171. Int32Array.from([1, 2, 1, 1, 2, 4]),
  7172. Int32Array.from([1, 2, 1, 4, 2, 1]),
  7173. Int32Array.from([1, 4, 1, 1, 2, 2]),
  7174. Int32Array.from([1, 4, 1, 2, 2, 1]),
  7175. Int32Array.from([1, 1, 2, 2, 1, 4]),
  7176. Int32Array.from([1, 1, 2, 4, 1, 2]),
  7177. Int32Array.from([1, 2, 2, 1, 1, 4]),
  7178. Int32Array.from([1, 2, 2, 4, 1, 1]),
  7179. Int32Array.from([1, 4, 2, 1, 1, 2]),
  7180. Int32Array.from([1, 4, 2, 2, 1, 1]),
  7181. Int32Array.from([2, 4, 1, 2, 1, 1]),
  7182. Int32Array.from([2, 2, 1, 1, 1, 4]),
  7183. Int32Array.from([4, 1, 3, 1, 1, 1]),
  7184. Int32Array.from([2, 4, 1, 1, 1, 2]),
  7185. Int32Array.from([1, 3, 4, 1, 1, 1]),
  7186. Int32Array.from([1, 1, 1, 2, 4, 2]),
  7187. Int32Array.from([1, 2, 1, 1, 4, 2]),
  7188. Int32Array.from([1, 2, 1, 2, 4, 1]),
  7189. Int32Array.from([1, 1, 4, 2, 1, 2]),
  7190. Int32Array.from([1, 2, 4, 1, 1, 2]),
  7191. Int32Array.from([1, 2, 4, 2, 1, 1]),
  7192. Int32Array.from([4, 1, 1, 2, 1, 2]),
  7193. Int32Array.from([4, 2, 1, 1, 1, 2]),
  7194. Int32Array.from([4, 2, 1, 2, 1, 1]),
  7195. Int32Array.from([2, 1, 2, 1, 4, 1]),
  7196. Int32Array.from([2, 1, 4, 1, 2, 1]),
  7197. Int32Array.from([4, 1, 2, 1, 2, 1]),
  7198. Int32Array.from([1, 1, 1, 1, 4, 3]),
  7199. Int32Array.from([1, 1, 1, 3, 4, 1]),
  7200. Int32Array.from([1, 3, 1, 1, 4, 1]),
  7201. Int32Array.from([1, 1, 4, 1, 1, 3]),
  7202. Int32Array.from([1, 1, 4, 3, 1, 1]),
  7203. Int32Array.from([4, 1, 1, 1, 1, 3]),
  7204. Int32Array.from([4, 1, 1, 3, 1, 1]),
  7205. Int32Array.from([1, 1, 3, 1, 4, 1]),
  7206. Int32Array.from([1, 1, 4, 1, 3, 1]),
  7207. Int32Array.from([3, 1, 1, 1, 4, 1]),
  7208. Int32Array.from([4, 1, 1, 1, 3, 1]),
  7209. Int32Array.from([2, 1, 1, 4, 1, 2]),
  7210. Int32Array.from([2, 1, 1, 2, 1, 4]),
  7211. Int32Array.from([2, 1, 1, 2, 3, 2]),
  7212. Int32Array.from([2, 3, 3, 1, 1, 1, 2]),
  7213. ];
  7214. Code128Reader.MAX_AVG_VARIANCE = 0.25;
  7215. Code128Reader.MAX_INDIVIDUAL_VARIANCE = 0.7;
  7216. Code128Reader.CODE_SHIFT = 98;
  7217. Code128Reader.CODE_CODE_C = 99;
  7218. Code128Reader.CODE_CODE_B = 100;
  7219. Code128Reader.CODE_CODE_A = 101;
  7220. Code128Reader.CODE_FNC_1 = 102;
  7221. Code128Reader.CODE_FNC_2 = 97;
  7222. Code128Reader.CODE_FNC_3 = 96;
  7223. Code128Reader.CODE_FNC_4_A = 101;
  7224. Code128Reader.CODE_FNC_4_B = 100;
  7225. Code128Reader.CODE_START_A = 103;
  7226. Code128Reader.CODE_START_B = 104;
  7227. Code128Reader.CODE_START_C = 105;
  7228. Code128Reader.CODE_STOP = 106;
  7229. /*
  7230. * Copyright 2008 ZXing authors
  7231. *
  7232. * Licensed under the Apache License, Version 2.0 (the "License");
  7233. * you may not use this file except in compliance with the License.
  7234. * You may obtain a copy of the License at
  7235. *
  7236. * http://www.apache.org/licenses/LICENSE-2.0
  7237. *
  7238. * Unless required by applicable law or agreed to in writing, software
  7239. * distributed under the License is distributed on an "AS IS" BASIS,
  7240. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7241. * See the License for the specific language governing permissions and
  7242. * limitations under the License.
  7243. */
  7244. /**
  7245. * <p>Decodes Code 39 barcodes. Supports "Full ASCII Code 39" if USE_CODE_39_EXTENDED_MODE is set.</p>
  7246. *
  7247. * @author Sean Owen
  7248. * @see Code93Reader
  7249. */
  7250. class Code39Reader extends OneDReader {
  7251. /**
  7252. * Creates a reader that assumes all encoded data is data, and does not treat the final
  7253. * character as a check digit. It will not decoded "extended Code 39" sequences.
  7254. */
  7255. // public Code39Reader() {
  7256. // this(false);
  7257. // }
  7258. /**
  7259. * Creates a reader that can be configured to check the last character as a check digit.
  7260. * It will not decoded "extended Code 39" sequences.
  7261. *
  7262. * @param usingCheckDigit if true, treat the last data character as a check digit, not
  7263. * data, and verify that the checksum passes.
  7264. */
  7265. // public Code39Reader(boolean usingCheckDigit) {
  7266. // this(usingCheckDigit, false);
  7267. // }
  7268. /**
  7269. * Creates a reader that can be configured to check the last character as a check digit,
  7270. * or optionally attempt to decode "extended Code 39" sequences that are used to encode
  7271. * the full ASCII character set.
  7272. *
  7273. * @param usingCheckDigit if true, treat the last data character as a check digit, not
  7274. * data, and verify that the checksum passes.
  7275. * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
  7276. * text.
  7277. */
  7278. constructor(usingCheckDigit = false, extendedMode = false) {
  7279. super();
  7280. this.usingCheckDigit = usingCheckDigit;
  7281. this.extendedMode = extendedMode;
  7282. this.decodeRowResult = '';
  7283. this.counters = new Int32Array(9);
  7284. }
  7285. decodeRow(rowNumber, row, hints) {
  7286. let theCounters = this.counters;
  7287. theCounters.fill(0);
  7288. this.decodeRowResult = '';
  7289. let start = Code39Reader.findAsteriskPattern(row, theCounters);
  7290. // Read off white space
  7291. let nextStart = row.getNextSet(start[1]);
  7292. let end = row.getSize();
  7293. let decodedChar;
  7294. let lastStart;
  7295. do {
  7296. Code39Reader.recordPattern(row, nextStart, theCounters);
  7297. let pattern = Code39Reader.toNarrowWidePattern(theCounters);
  7298. if (pattern < 0) {
  7299. throw new NotFoundException();
  7300. }
  7301. decodedChar = Code39Reader.patternToChar(pattern);
  7302. this.decodeRowResult += decodedChar;
  7303. lastStart = nextStart;
  7304. for (let counter of theCounters) {
  7305. nextStart += counter;
  7306. }
  7307. // Read off white space
  7308. nextStart = row.getNextSet(nextStart);
  7309. } while (decodedChar !== '*');
  7310. this.decodeRowResult = this.decodeRowResult.substring(0, this.decodeRowResult.length - 1); // remove asterisk
  7311. // Look for whitespace after pattern:
  7312. let lastPatternSize = 0;
  7313. for (let counter of theCounters) {
  7314. lastPatternSize += counter;
  7315. }
  7316. let whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
  7317. // If 50% of last pattern size, following last pattern, is not whitespace, fail
  7318. // (but if it's whitespace to the very end of the image, that's OK)
  7319. if (nextStart !== end && (whiteSpaceAfterEnd * 2) < lastPatternSize) {
  7320. throw new NotFoundException();
  7321. }
  7322. if (this.usingCheckDigit) {
  7323. let max = this.decodeRowResult.length - 1;
  7324. let total = 0;
  7325. for (let i = 0; i < max; i++) {
  7326. total += Code39Reader.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(i));
  7327. }
  7328. if (this.decodeRowResult.charAt(max) !== Code39Reader.ALPHABET_STRING.charAt(total % 43)) {
  7329. throw new ChecksumException();
  7330. }
  7331. this.decodeRowResult = this.decodeRowResult.substring(0, max);
  7332. }
  7333. if (this.decodeRowResult.length === 0) {
  7334. // false positive
  7335. throw new NotFoundException();
  7336. }
  7337. let resultString;
  7338. if (this.extendedMode) {
  7339. resultString = Code39Reader.decodeExtended(this.decodeRowResult);
  7340. }
  7341. else {
  7342. resultString = this.decodeRowResult;
  7343. }
  7344. let left = (start[1] + start[0]) / 2.0;
  7345. let right = lastStart + lastPatternSize / 2.0;
  7346. return new Result(resultString, null, 0, [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)], BarcodeFormat$1.CODE_39, new Date().getTime());
  7347. }
  7348. static findAsteriskPattern(row, counters) {
  7349. let width = row.getSize();
  7350. let rowOffset = row.getNextSet(0);
  7351. let counterPosition = 0;
  7352. let patternStart = rowOffset;
  7353. let isWhite = false;
  7354. let patternLength = counters.length;
  7355. for (let i = rowOffset; i < width; i++) {
  7356. if (row.get(i) !== isWhite) {
  7357. counters[counterPosition]++;
  7358. }
  7359. else {
  7360. if (counterPosition === patternLength - 1) {
  7361. // Look for whitespace before start pattern, >= 50% of width of start pattern
  7362. if (this.toNarrowWidePattern(counters) === Code39Reader.ASTERISK_ENCODING &&
  7363. row.isRange(Math.max(0, patternStart - Math.floor((i - patternStart) / 2)), patternStart, false)) {
  7364. return [patternStart, i];
  7365. }
  7366. patternStart += counters[0] + counters[1];
  7367. counters.copyWithin(0, 2, 2 + counterPosition - 1);
  7368. counters[counterPosition - 1] = 0;
  7369. counters[counterPosition] = 0;
  7370. counterPosition--;
  7371. }
  7372. else {
  7373. counterPosition++;
  7374. }
  7375. counters[counterPosition] = 1;
  7376. isWhite = !isWhite;
  7377. }
  7378. }
  7379. throw new NotFoundException();
  7380. }
  7381. // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
  7382. // per image when using some of our blackbox images.
  7383. static toNarrowWidePattern(counters) {
  7384. let numCounters = counters.length;
  7385. let maxNarrowCounter = 0;
  7386. let wideCounters;
  7387. do {
  7388. let minCounter = 0x7fffffff;
  7389. for (let counter of counters) {
  7390. if (counter < minCounter && counter > maxNarrowCounter) {
  7391. minCounter = counter;
  7392. }
  7393. }
  7394. maxNarrowCounter = minCounter;
  7395. wideCounters = 0;
  7396. let totalWideCountersWidth = 0;
  7397. let pattern = 0;
  7398. for (let i = 0; i < numCounters; i++) {
  7399. let counter = counters[i];
  7400. if (counter > maxNarrowCounter) {
  7401. pattern |= 1 << (numCounters - 1 - i);
  7402. wideCounters++;
  7403. totalWideCountersWidth += counter;
  7404. }
  7405. }
  7406. if (wideCounters === 3) {
  7407. // Found 3 wide counters, but are they close enough in width?
  7408. // We can perform a cheap, conservative check to see if any individual
  7409. // counter is more than 1.5 times the average:
  7410. for (let i = 0; i < numCounters && wideCounters > 0; i++) {
  7411. let counter = counters[i];
  7412. if (counter > maxNarrowCounter) {
  7413. wideCounters--;
  7414. // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
  7415. if ((counter * 2) >= totalWideCountersWidth) {
  7416. return -1;
  7417. }
  7418. }
  7419. }
  7420. return pattern;
  7421. }
  7422. } while (wideCounters > 3);
  7423. return -1;
  7424. }
  7425. static patternToChar(pattern) {
  7426. for (let i = 0; i < Code39Reader.CHARACTER_ENCODINGS.length; i++) {
  7427. if (Code39Reader.CHARACTER_ENCODINGS[i] === pattern) {
  7428. return Code39Reader.ALPHABET_STRING.charAt(i);
  7429. }
  7430. }
  7431. if (pattern === Code39Reader.ASTERISK_ENCODING) {
  7432. return '*';
  7433. }
  7434. throw new NotFoundException();
  7435. }
  7436. static decodeExtended(encoded) {
  7437. let length = encoded.length;
  7438. let decoded = '';
  7439. for (let i = 0; i < length; i++) {
  7440. let c = encoded.charAt(i);
  7441. if (c === '+' || c === '$' || c === '%' || c === '/') {
  7442. let next = encoded.charAt(i + 1);
  7443. let decodedChar = '\0';
  7444. switch (c) {
  7445. case '+':
  7446. // +A to +Z map to a to z
  7447. if (next >= 'A' && next <= 'Z') {
  7448. decodedChar = String.fromCharCode(next.charCodeAt(0) + 32);
  7449. }
  7450. else {
  7451. throw new FormatException();
  7452. }
  7453. break;
  7454. case '$':
  7455. // $A to $Z map to control codes SH to SB
  7456. if (next >= 'A' && next <= 'Z') {
  7457. decodedChar = String.fromCharCode(next.charCodeAt(0) - 64);
  7458. }
  7459. else {
  7460. throw new FormatException();
  7461. }
  7462. break;
  7463. case '%':
  7464. // %A to %E map to control codes ESC to US
  7465. if (next >= 'A' && next <= 'E') {
  7466. decodedChar = String.fromCharCode(next.charCodeAt(0) - 38);
  7467. }
  7468. else if (next >= 'F' && next <= 'J') {
  7469. decodedChar = String.fromCharCode(next.charCodeAt(0) - 11);
  7470. }
  7471. else if (next >= 'K' && next <= 'O') {
  7472. decodedChar = String.fromCharCode(next.charCodeAt(0) + 16);
  7473. }
  7474. else if (next >= 'P' && next <= 'T') {
  7475. decodedChar = String.fromCharCode(next.charCodeAt(0) + 43);
  7476. }
  7477. else if (next === 'U') {
  7478. decodedChar = '\0';
  7479. }
  7480. else if (next === 'V') {
  7481. decodedChar = '@';
  7482. }
  7483. else if (next === 'W') {
  7484. decodedChar = '`';
  7485. }
  7486. else if (next === 'X' || next === 'Y' || next === 'Z') {
  7487. decodedChar = '\x7f';
  7488. }
  7489. else {
  7490. throw new FormatException();
  7491. }
  7492. break;
  7493. case '/':
  7494. // /A to /O map to ! to , and /Z maps to :
  7495. if (next >= 'A' && next <= 'O') {
  7496. decodedChar = String.fromCharCode(next.charCodeAt(0) - 32);
  7497. }
  7498. else if (next === 'Z') {
  7499. decodedChar = ':';
  7500. }
  7501. else {
  7502. throw new FormatException();
  7503. }
  7504. break;
  7505. }
  7506. decoded += decodedChar;
  7507. // bump up i again since we read two characters
  7508. i++;
  7509. }
  7510. else {
  7511. decoded += c;
  7512. }
  7513. }
  7514. return decoded;
  7515. }
  7516. }
  7517. Code39Reader.ALPHABET_STRING = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%';
  7518. /**
  7519. * These represent the encodings of characters, as patterns of wide and narrow bars.
  7520. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
  7521. * with 1s representing "wide" and 0s representing narrow.
  7522. */
  7523. Code39Reader.CHARACTER_ENCODINGS = [
  7524. 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064,
  7525. 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C,
  7526. 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016,
  7527. 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x0A8,
  7528. 0x0A2, 0x08A, 0x02A // /-%
  7529. ];
  7530. Code39Reader.ASTERISK_ENCODING = 0x094;
  7531. /*
  7532. * Copyright 2010 ZXing authors
  7533. *
  7534. * Licensed under the Apache License, Version 2.0 (the "License");
  7535. * you may not use this file except in compliance with the License.
  7536. * You may obtain a copy of the License at
  7537. *
  7538. * http://www.apache.org/licenses/LICENSE-2.0
  7539. *
  7540. * Unless required by applicable law or agreed to in writing, software
  7541. * distributed under the License is distributed on an "AS IS" BASIS,
  7542. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7543. * See the License for the specific language governing permissions and
  7544. * limitations under the License.
  7545. */
  7546. /**
  7547. * <p>Decodes Code 93 barcodes.</p>
  7548. *
  7549. * @author Sean Owen
  7550. * @see Code39Reader
  7551. */
  7552. class Code93Reader extends OneDReader {
  7553. //public Code93Reader() {
  7554. // decodeRowResult = new StringBuilder(20);
  7555. // counters = new int[6];
  7556. //}
  7557. constructor() {
  7558. super();
  7559. this.decodeRowResult = '';
  7560. this.counters = new Int32Array(6);
  7561. }
  7562. decodeRow(rowNumber, row, hints) {
  7563. let start = this.findAsteriskPattern(row);
  7564. // Read off white space
  7565. let nextStart = row.getNextSet(start[1]);
  7566. let end = row.getSize();
  7567. let theCounters = this.counters;
  7568. theCounters.fill(0);
  7569. this.decodeRowResult = '';
  7570. let decodedChar;
  7571. let lastStart;
  7572. do {
  7573. Code93Reader.recordPattern(row, nextStart, theCounters);
  7574. let pattern = this.toPattern(theCounters);
  7575. if (pattern < 0) {
  7576. throw new NotFoundException();
  7577. }
  7578. decodedChar = this.patternToChar(pattern);
  7579. this.decodeRowResult += decodedChar;
  7580. lastStart = nextStart;
  7581. for (let counter of theCounters) {
  7582. nextStart += counter;
  7583. }
  7584. // Read off white space
  7585. nextStart = row.getNextSet(nextStart);
  7586. } while (decodedChar !== '*');
  7587. this.decodeRowResult = this.decodeRowResult.substring(0, this.decodeRowResult.length - 1); // remove asterisk
  7588. let lastPatternSize = 0;
  7589. for (let counter of theCounters) {
  7590. lastPatternSize += counter;
  7591. }
  7592. // Should be at least one more black module
  7593. if (nextStart === end || !row.get(nextStart)) {
  7594. throw new NotFoundException();
  7595. }
  7596. if (this.decodeRowResult.length < 2) {
  7597. // false positive -- need at least 2 checksum digits
  7598. throw new NotFoundException();
  7599. }
  7600. this.checkChecksums(this.decodeRowResult);
  7601. // Remove checksum digits
  7602. this.decodeRowResult = this.decodeRowResult.substring(0, this.decodeRowResult.length - 2);
  7603. let resultString = this.decodeExtended(this.decodeRowResult);
  7604. let left = (start[1] + start[0]) / 2.0;
  7605. let right = lastStart + lastPatternSize / 2.0;
  7606. return new Result(resultString, null, 0, [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)], BarcodeFormat$1.CODE_93, new Date().getTime());
  7607. }
  7608. findAsteriskPattern(row) {
  7609. let width = row.getSize();
  7610. let rowOffset = row.getNextSet(0);
  7611. this.counters.fill(0);
  7612. let theCounters = this.counters;
  7613. let patternStart = rowOffset;
  7614. let isWhite = false;
  7615. let patternLength = theCounters.length;
  7616. let counterPosition = 0;
  7617. for (let i = rowOffset; i < width; i++) {
  7618. if (row.get(i) !== isWhite) {
  7619. theCounters[counterPosition]++;
  7620. }
  7621. else {
  7622. if (counterPosition === patternLength - 1) {
  7623. if (this.toPattern(theCounters) === Code93Reader.ASTERISK_ENCODING) {
  7624. return new Int32Array([patternStart, i]);
  7625. }
  7626. patternStart += theCounters[0] + theCounters[1];
  7627. theCounters.copyWithin(0, 2, 2 + counterPosition - 1);
  7628. theCounters[counterPosition - 1] = 0;
  7629. theCounters[counterPosition] = 0;
  7630. counterPosition--;
  7631. }
  7632. else {
  7633. counterPosition++;
  7634. }
  7635. theCounters[counterPosition] = 1;
  7636. isWhite = !isWhite;
  7637. }
  7638. }
  7639. throw new NotFoundException;
  7640. }
  7641. toPattern(counters) {
  7642. let sum = 0;
  7643. for (const counter of counters) {
  7644. sum += counter;
  7645. }
  7646. let pattern = 0;
  7647. let max = counters.length;
  7648. for (let i = 0; i < max; i++) {
  7649. let scaled = Math.round(counters[i] * 9.0 / sum);
  7650. if (scaled < 1 || scaled > 4) {
  7651. return -1;
  7652. }
  7653. if ((i & 0x01) === 0) {
  7654. for (let j = 0; j < scaled; j++) {
  7655. pattern = (pattern << 1) | 0x01;
  7656. }
  7657. }
  7658. else {
  7659. pattern <<= scaled;
  7660. }
  7661. }
  7662. return pattern;
  7663. }
  7664. patternToChar(pattern) {
  7665. for (let i = 0; i < Code93Reader.CHARACTER_ENCODINGS.length; i++) {
  7666. if (Code93Reader.CHARACTER_ENCODINGS[i] === pattern) {
  7667. return Code93Reader.ALPHABET_STRING.charAt(i);
  7668. }
  7669. }
  7670. throw new NotFoundException();
  7671. }
  7672. decodeExtended(encoded) {
  7673. let length = encoded.length;
  7674. let decoded = '';
  7675. for (let i = 0; i < length; i++) {
  7676. let c = encoded.charAt(i);
  7677. if (c >= 'a' && c <= 'd') {
  7678. if (i >= length - 1) {
  7679. throw new FormatException();
  7680. }
  7681. let next = encoded.charAt(i + 1);
  7682. let decodedChar = '\0';
  7683. switch (c) {
  7684. case 'd':
  7685. // +A to +Z map to a to z
  7686. if (next >= 'A' && next <= 'Z') {
  7687. decodedChar = String.fromCharCode(next.charCodeAt(0) + 32);
  7688. }
  7689. else {
  7690. throw new FormatException();
  7691. }
  7692. break;
  7693. case 'a':
  7694. // $A to $Z map to control codes SH to SB
  7695. if (next >= 'A' && next <= 'Z') {
  7696. decodedChar = String.fromCharCode(next.charCodeAt(0) - 64);
  7697. }
  7698. else {
  7699. throw new FormatException();
  7700. }
  7701. break;
  7702. case 'b':
  7703. if (next >= 'A' && next <= 'E') {
  7704. // %A to %E map to control codes ESC to USep
  7705. decodedChar = String.fromCharCode(next.charCodeAt(0) - 38);
  7706. }
  7707. else if (next >= 'F' && next <= 'J') {
  7708. // %F to %J map to ; < = > ?
  7709. decodedChar = String.fromCharCode(next.charCodeAt(0) - 11);
  7710. }
  7711. else if (next >= 'K' && next <= 'O') {
  7712. // %K to %O map to [ \ ] ^ _
  7713. decodedChar = String.fromCharCode(next.charCodeAt(0) + 16);
  7714. }
  7715. else if (next >= 'P' && next <= 'T') {
  7716. // %P to %T map to { | } ~ DEL
  7717. decodedChar = String.fromCharCode(next.charCodeAt(0) + 43);
  7718. }
  7719. else if (next === 'U') {
  7720. // %U map to NUL
  7721. decodedChar = '\0';
  7722. }
  7723. else if (next === 'V') {
  7724. // %V map to @
  7725. decodedChar = '@';
  7726. }
  7727. else if (next === 'W') {
  7728. // %W map to `
  7729. decodedChar = '`';
  7730. }
  7731. else if (next >= 'X' && next <= 'Z') {
  7732. // %X to %Z all map to DEL (127)
  7733. decodedChar = String.fromCharCode(127);
  7734. }
  7735. else {
  7736. throw new FormatException();
  7737. }
  7738. break;
  7739. case 'c':
  7740. // /A to /O map to ! to , and /Z maps to :
  7741. if (next >= 'A' && next <= 'O') {
  7742. decodedChar = String.fromCharCode(next.charCodeAt(0) - 32);
  7743. }
  7744. else if (next === 'Z') {
  7745. decodedChar = ':';
  7746. }
  7747. else {
  7748. throw new FormatException();
  7749. }
  7750. break;
  7751. }
  7752. decoded += decodedChar;
  7753. // bump up i again since we read two characters
  7754. i++;
  7755. }
  7756. else {
  7757. decoded += c;
  7758. }
  7759. }
  7760. return decoded;
  7761. }
  7762. checkChecksums(result) {
  7763. let length = result.length;
  7764. this.checkOneChecksum(result, length - 2, 20);
  7765. this.checkOneChecksum(result, length - 1, 15);
  7766. }
  7767. checkOneChecksum(result, checkPosition, weightMax) {
  7768. let weight = 1;
  7769. let total = 0;
  7770. for (let i = checkPosition - 1; i >= 0; i--) {
  7771. total += weight * Code93Reader.ALPHABET_STRING.indexOf(result.charAt(i));
  7772. if (++weight > weightMax) {
  7773. weight = 1;
  7774. }
  7775. }
  7776. if (result.charAt(checkPosition) !== Code93Reader.ALPHABET_STRING[total % 47]) {
  7777. throw new ChecksumException;
  7778. }
  7779. }
  7780. }
  7781. // Note that 'abcd' are dummy characters in place of control characters.
  7782. Code93Reader.ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
  7783. /**
  7784. * These represent the encodings of characters, as patterns of wide and narrow bars.
  7785. * The 9 least-significant bits of each int correspond to the pattern of wide and narrow.
  7786. */
  7787. Code93Reader.CHARACTER_ENCODINGS = [
  7788. 0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A,
  7789. 0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134,
  7790. 0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6,
  7791. 0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A,
  7792. 0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE,
  7793. 0x126, 0x1DA, 0x1D6, 0x132, 0x15E,
  7794. ];
  7795. Code93Reader.ASTERISK_ENCODING = Code93Reader.CHARACTER_ENCODINGS[47];
  7796. /*
  7797. * Copyright 2008 ZXing authors
  7798. *
  7799. * Licensed under the Apache License, Version 2.0 (the "License");
  7800. * you may not use this file except in compliance with the License.
  7801. * You may obtain a copy of the License at
  7802. *
  7803. * http://www.apache.org/licenses/LICENSE-2.0
  7804. *
  7805. * Unless required by applicable law or agreed to in writing, software
  7806. * distributed under the License is distributed on an "AS IS" BASIS,
  7807. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7808. * See the License for the specific language governing permissions and
  7809. * limitations under the License.
  7810. */
  7811. /**
  7812. * <p>Decodes ITF barcodes.</p>
  7813. *
  7814. * @author Tjieco
  7815. */
  7816. class ITFReader extends OneDReader {
  7817. constructor() {
  7818. // private static W = 3; // Pixel width of a 3x wide line
  7819. // private static w = 2; // Pixel width of a 2x wide line
  7820. // private static N = 1; // Pixed width of a narrow line
  7821. super(...arguments);
  7822. // Stores the actual narrow line width of the image being decoded.
  7823. this.narrowLineWidth = -1;
  7824. }
  7825. // See ITFWriter.PATTERNS
  7826. /*
  7827. /!**
  7828. * Patterns of Wide / Narrow lines to indicate each digit
  7829. *!/
  7830. */
  7831. decodeRow(rowNumber, row, hints) {
  7832. // Find out where the Middle section (payload) starts & ends
  7833. let startRange = this.decodeStart(row);
  7834. let endRange = this.decodeEnd(row);
  7835. let result = new StringBuilder();
  7836. ITFReader.decodeMiddle(row, startRange[1], endRange[0], result);
  7837. let resultString = result.toString();
  7838. let allowedLengths = null;
  7839. if (hints != null) {
  7840. allowedLengths = hints.get(DecodeHintType$1.ALLOWED_LENGTHS);
  7841. }
  7842. if (allowedLengths == null) {
  7843. allowedLengths = ITFReader.DEFAULT_ALLOWED_LENGTHS;
  7844. }
  7845. // To avoid false positives with 2D barcodes (and other patterns), make
  7846. // an assumption that the decoded string must be a 'standard' length if it's short
  7847. let length = resultString.length;
  7848. let lengthOK = false;
  7849. let maxAllowedLength = 0;
  7850. for (let value of allowedLengths) {
  7851. if (length === value) {
  7852. lengthOK = true;
  7853. break;
  7854. }
  7855. if (value > maxAllowedLength) {
  7856. maxAllowedLength = value;
  7857. }
  7858. }
  7859. if (!lengthOK && length > maxAllowedLength) {
  7860. lengthOK = true;
  7861. }
  7862. if (!lengthOK) {
  7863. throw new FormatException();
  7864. }
  7865. const points = [new ResultPoint(startRange[1], rowNumber), new ResultPoint(endRange[0], rowNumber)];
  7866. let resultReturn = new Result(resultString, null, // no natural byte representation for these barcodes
  7867. 0, points, BarcodeFormat$1.ITF, new Date().getTime());
  7868. return resultReturn;
  7869. }
  7870. /*
  7871. /!**
  7872. * @param row row of black/white values to search
  7873. * @param payloadStart offset of start pattern
  7874. * @param resultString {@link StringBuilder} to append decoded chars to
  7875. * @throws NotFoundException if decoding could not complete successfully
  7876. *!/*/
  7877. static decodeMiddle(row, payloadStart, payloadEnd, resultString) {
  7878. // Digits are interleaved in pairs - 5 black lines for one digit, and the
  7879. // 5
  7880. // interleaved white lines for the second digit.
  7881. // Therefore, need to scan 10 lines and then
  7882. // split these into two arrays
  7883. let counterDigitPair = new Int32Array(10); // 10
  7884. let counterBlack = new Int32Array(5); // 5
  7885. let counterWhite = new Int32Array(5); // 5
  7886. counterDigitPair.fill(0);
  7887. counterBlack.fill(0);
  7888. counterWhite.fill(0);
  7889. while (payloadStart < payloadEnd) {
  7890. // Get 10 runs of black/white.
  7891. OneDReader.recordPattern(row, payloadStart, counterDigitPair);
  7892. // Split them into each array
  7893. for (let k = 0; k < 5; k++) {
  7894. let twoK = 2 * k;
  7895. counterBlack[k] = counterDigitPair[twoK];
  7896. counterWhite[k] = counterDigitPair[twoK + 1];
  7897. }
  7898. let bestMatch = ITFReader.decodeDigit(counterBlack);
  7899. resultString.append(bestMatch.toString());
  7900. bestMatch = this.decodeDigit(counterWhite);
  7901. resultString.append(bestMatch.toString());
  7902. counterDigitPair.forEach(function (counterDigit) {
  7903. payloadStart += counterDigit;
  7904. });
  7905. }
  7906. }
  7907. /*/!**
  7908. * Identify where the start of the middle / payload section starts.
  7909. *
  7910. * @param row row of black/white values to search
  7911. * @return Array, containing index of start of 'start block' and end of
  7912. * 'start block'
  7913. *!/*/
  7914. decodeStart(row) {
  7915. let endStart = ITFReader.skipWhiteSpace(row);
  7916. let startPattern = ITFReader.findGuardPattern(row, endStart, ITFReader.START_PATTERN);
  7917. // Determine the width of a narrow line in pixels. We can do this by
  7918. // getting the width of the start pattern and dividing by 4 because its
  7919. // made up of 4 narrow lines.
  7920. this.narrowLineWidth = (startPattern[1] - startPattern[0]) / 4;
  7921. this.validateQuietZone(row, startPattern[0]);
  7922. return startPattern;
  7923. }
  7924. /*/!**
  7925. * The start & end patterns must be pre/post fixed by a quiet zone. This
  7926. * zone must be at least 10 times the width of a narrow line. Scan back until
  7927. * we either get to the start of the barcode or match the necessary number of
  7928. * quiet zone pixels.
  7929. *
  7930. * Note: Its assumed the row is reversed when using this method to find
  7931. * quiet zone after the end pattern.
  7932. *
  7933. * ref: http://www.barcode-1.net/i25code.html
  7934. *
  7935. * @param row bit array representing the scanned barcode.
  7936. * @param startPattern index into row of the start or end pattern.
  7937. * @throws NotFoundException if the quiet zone cannot be found
  7938. *!/*/
  7939. validateQuietZone(row, startPattern) {
  7940. let quietCount = this.narrowLineWidth * 10; // expect to find this many pixels of quiet zone
  7941. // if there are not so many pixel at all let's try as many as possible
  7942. quietCount = quietCount < startPattern ? quietCount : startPattern;
  7943. for (let i = startPattern - 1; quietCount > 0 && i >= 0; i--) {
  7944. if (row.get(i)) {
  7945. break;
  7946. }
  7947. quietCount--;
  7948. }
  7949. if (quietCount !== 0) {
  7950. // Unable to find the necessary number of quiet zone pixels.
  7951. throw new NotFoundException();
  7952. }
  7953. }
  7954. /*
  7955. /!**
  7956. * Skip all whitespace until we get to the first black line.
  7957. *
  7958. * @param row row of black/white values to search
  7959. * @return index of the first black line.
  7960. * @throws NotFoundException Throws exception if no black lines are found in the row
  7961. *!/*/
  7962. static skipWhiteSpace(row) {
  7963. const width = row.getSize();
  7964. const endStart = row.getNextSet(0);
  7965. if (endStart === width) {
  7966. throw new NotFoundException();
  7967. }
  7968. return endStart;
  7969. }
  7970. /*/!**
  7971. * Identify where the end of the middle / payload section ends.
  7972. *
  7973. * @param row row of black/white values to search
  7974. * @return Array, containing index of start of 'end block' and end of 'end
  7975. * block'
  7976. *!/*/
  7977. decodeEnd(row) {
  7978. // For convenience, reverse the row and then
  7979. // search from 'the start' for the end block
  7980. row.reverse();
  7981. try {
  7982. let endStart = ITFReader.skipWhiteSpace(row);
  7983. let endPattern;
  7984. try {
  7985. endPattern = ITFReader.findGuardPattern(row, endStart, ITFReader.END_PATTERN_REVERSED[0]);
  7986. }
  7987. catch (error) {
  7988. if (error instanceof NotFoundException) {
  7989. endPattern = ITFReader.findGuardPattern(row, endStart, ITFReader.END_PATTERN_REVERSED[1]);
  7990. }
  7991. }
  7992. // The start & end patterns must be pre/post fixed by a quiet zone. This
  7993. // zone must be at least 10 times the width of a narrow line.
  7994. // ref: http://www.barcode-1.net/i25code.html
  7995. this.validateQuietZone(row, endPattern[0]);
  7996. // Now recalculate the indices of where the 'endblock' starts & stops to
  7997. // accommodate
  7998. // the reversed nature of the search
  7999. let temp = endPattern[0];
  8000. endPattern[0] = row.getSize() - endPattern[1];
  8001. endPattern[1] = row.getSize() - temp;
  8002. return endPattern;
  8003. }
  8004. finally {
  8005. // Put the row back the right way.
  8006. row.reverse();
  8007. }
  8008. }
  8009. /*
  8010. /!**
  8011. * @param row row of black/white values to search
  8012. * @param rowOffset position to start search
  8013. * @param pattern pattern of counts of number of black and white pixels that are
  8014. * being searched for as a pattern
  8015. * @return start/end horizontal offset of guard pattern, as an array of two
  8016. * ints
  8017. * @throws NotFoundException if pattern is not found
  8018. *!/*/
  8019. static findGuardPattern(row, rowOffset, pattern) {
  8020. let patternLength = pattern.length;
  8021. let counters = new Int32Array(patternLength);
  8022. let width = row.getSize();
  8023. let isWhite = false;
  8024. let counterPosition = 0;
  8025. let patternStart = rowOffset;
  8026. counters.fill(0);
  8027. for (let x = rowOffset; x < width; x++) {
  8028. if (row.get(x) !== isWhite) {
  8029. counters[counterPosition]++;
  8030. }
  8031. else {
  8032. if (counterPosition === patternLength - 1) {
  8033. if (OneDReader.patternMatchVariance(counters, pattern, ITFReader.MAX_INDIVIDUAL_VARIANCE) < ITFReader.MAX_AVG_VARIANCE) {
  8034. return [patternStart, x];
  8035. }
  8036. patternStart += counters[0] + counters[1];
  8037. System.arraycopy(counters, 2, counters, 0, counterPosition - 1);
  8038. counters[counterPosition - 1] = 0;
  8039. counters[counterPosition] = 0;
  8040. counterPosition--;
  8041. }
  8042. else {
  8043. counterPosition++;
  8044. }
  8045. counters[counterPosition] = 1;
  8046. isWhite = !isWhite;
  8047. }
  8048. }
  8049. throw new NotFoundException();
  8050. }
  8051. /*/!**
  8052. * Attempts to decode a sequence of ITF black/white lines into single
  8053. * digit.
  8054. *
  8055. * @param counters the counts of runs of observed black/white/black/... values
  8056. * @return The decoded digit
  8057. * @throws NotFoundException if digit cannot be decoded
  8058. *!/*/
  8059. static decodeDigit(counters) {
  8060. let bestVariance = ITFReader.MAX_AVG_VARIANCE; // worst variance we'll accept
  8061. let bestMatch = -1;
  8062. let max = ITFReader.PATTERNS.length;
  8063. for (let i = 0; i < max; i++) {
  8064. let pattern = ITFReader.PATTERNS[i];
  8065. let variance = OneDReader.patternMatchVariance(counters, pattern, ITFReader.MAX_INDIVIDUAL_VARIANCE);
  8066. if (variance < bestVariance) {
  8067. bestVariance = variance;
  8068. bestMatch = i;
  8069. }
  8070. else if (variance === bestVariance) {
  8071. // if we find a second 'best match' with the same variance, we can not reliably report to have a suitable match
  8072. bestMatch = -1;
  8073. }
  8074. }
  8075. if (bestMatch >= 0) {
  8076. return bestMatch % 10;
  8077. }
  8078. else {
  8079. throw new NotFoundException();
  8080. }
  8081. }
  8082. }
  8083. ITFReader.PATTERNS = [
  8084. Int32Array.from([1, 1, 2, 2, 1]),
  8085. Int32Array.from([2, 1, 1, 1, 2]),
  8086. Int32Array.from([1, 2, 1, 1, 2]),
  8087. Int32Array.from([2, 2, 1, 1, 1]),
  8088. Int32Array.from([1, 1, 2, 1, 2]),
  8089. Int32Array.from([2, 1, 2, 1, 1]),
  8090. Int32Array.from([1, 2, 2, 1, 1]),
  8091. Int32Array.from([1, 1, 1, 2, 2]),
  8092. Int32Array.from([2, 1, 1, 2, 1]),
  8093. Int32Array.from([1, 2, 1, 2, 1]),
  8094. Int32Array.from([1, 1, 3, 3, 1]),
  8095. Int32Array.from([3, 1, 1, 1, 3]),
  8096. Int32Array.from([1, 3, 1, 1, 3]),
  8097. Int32Array.from([3, 3, 1, 1, 1]),
  8098. Int32Array.from([1, 1, 3, 1, 3]),
  8099. Int32Array.from([3, 1, 3, 1, 1]),
  8100. Int32Array.from([1, 3, 3, 1, 1]),
  8101. Int32Array.from([1, 1, 1, 3, 3]),
  8102. Int32Array.from([3, 1, 1, 3, 1]),
  8103. Int32Array.from([1, 3, 1, 3, 1]) // 9
  8104. ];
  8105. ITFReader.MAX_AVG_VARIANCE = 0.38;
  8106. ITFReader.MAX_INDIVIDUAL_VARIANCE = 0.5;
  8107. /* /!** Valid ITF lengths. Anything longer than the largest value is also allowed. *!/*/
  8108. ITFReader.DEFAULT_ALLOWED_LENGTHS = [6, 8, 10, 12, 14];
  8109. /*/!**
  8110. * Start/end guard pattern.
  8111. *
  8112. * Note: The end pattern is reversed because the row is reversed before
  8113. * searching for the END_PATTERN
  8114. *!/*/
  8115. ITFReader.START_PATTERN = Int32Array.from([1, 1, 1, 1]);
  8116. ITFReader.END_PATTERN_REVERSED = [
  8117. Int32Array.from([1, 1, 2]),
  8118. Int32Array.from([1, 1, 3]) // 3x
  8119. ];
  8120. /*
  8121. * Copyright 2008 ZXing authors
  8122. *
  8123. * Licensed under the Apache License, Version 2.0 (the "License");
  8124. * you may not use this file except in compliance with the License.
  8125. * You may obtain a copy of the License at
  8126. *
  8127. * http://www.apache.org/licenses/LICENSE-2.0
  8128. *
  8129. * Unless required by applicable law or agreed to in writing, software
  8130. * distributed under the License is distributed on an "AS IS" BASIS,
  8131. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8132. * See the License for the specific language governing permissions and
  8133. * limitations under the License.
  8134. */
  8135. /**
  8136. * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
  8137. * of one-dimensional barcodes.</p>
  8138. *
  8139. * @author dswitkin@google.com (Daniel Switkin)
  8140. * @author Sean Owen
  8141. * @author alasdair@google.com (Alasdair Mackintosh)
  8142. */
  8143. class AbstractUPCEANReader extends OneDReader {
  8144. constructor() {
  8145. super(...arguments);
  8146. this.decodeRowStringBuffer = '';
  8147. }
  8148. // private final UPCEANExtensionSupport extensionReader;
  8149. // private final EANManufacturerOrgSupport eanManSupport;
  8150. /*
  8151. protected UPCEANReader() {
  8152. decodeRowStringBuffer = new StringBuilder(20);
  8153. extensionReader = new UPCEANExtensionSupport();
  8154. eanManSupport = new EANManufacturerOrgSupport();
  8155. }
  8156. */
  8157. static findStartGuardPattern(row) {
  8158. let foundStart = false;
  8159. let startRange;
  8160. let nextStart = 0;
  8161. let counters = Int32Array.from([0, 0, 0]);
  8162. while (!foundStart) {
  8163. counters = Int32Array.from([0, 0, 0]);
  8164. startRange = AbstractUPCEANReader.findGuardPattern(row, nextStart, false, this.START_END_PATTERN, counters);
  8165. let start = startRange[0];
  8166. nextStart = startRange[1];
  8167. let quietStart = start - (nextStart - start);
  8168. if (quietStart >= 0) {
  8169. foundStart = row.isRange(quietStart, start, false);
  8170. }
  8171. }
  8172. return startRange;
  8173. }
  8174. static checkChecksum(s) {
  8175. return AbstractUPCEANReader.checkStandardUPCEANChecksum(s);
  8176. }
  8177. static checkStandardUPCEANChecksum(s) {
  8178. let length = s.length;
  8179. if (length === 0)
  8180. return false;
  8181. let check = parseInt(s.charAt(length - 1), 10);
  8182. return AbstractUPCEANReader.getStandardUPCEANChecksum(s.substring(0, length - 1)) === check;
  8183. }
  8184. static getStandardUPCEANChecksum(s) {
  8185. let length = s.length;
  8186. let sum = 0;
  8187. for (let i = length - 1; i >= 0; i -= 2) {
  8188. let digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);
  8189. if (digit < 0 || digit > 9) {
  8190. throw new FormatException();
  8191. }
  8192. sum += digit;
  8193. }
  8194. sum *= 3;
  8195. for (let i = length - 2; i >= 0; i -= 2) {
  8196. let digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);
  8197. if (digit < 0 || digit > 9) {
  8198. throw new FormatException();
  8199. }
  8200. sum += digit;
  8201. }
  8202. return (1000 - sum) % 10;
  8203. }
  8204. static decodeEnd(row, endStart) {
  8205. return AbstractUPCEANReader.findGuardPattern(row, endStart, false, AbstractUPCEANReader.START_END_PATTERN, new Int32Array(AbstractUPCEANReader.START_END_PATTERN.length).fill(0));
  8206. }
  8207. /**
  8208. * @throws NotFoundException
  8209. */
  8210. static findGuardPatternWithoutCounters(row, rowOffset, whiteFirst, pattern) {
  8211. return this.findGuardPattern(row, rowOffset, whiteFirst, pattern, new Int32Array(pattern.length));
  8212. }
  8213. /**
  8214. * @param row row of black/white values to search
  8215. * @param rowOffset position to start search
  8216. * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
  8217. * pixel counts, otherwise, it is interpreted as black/white/black/...
  8218. * @param pattern pattern of counts of number of black and white pixels that are being
  8219. * searched for as a pattern
  8220. * @param counters array of counters, as long as pattern, to re-use
  8221. * @return start/end horizontal offset of guard pattern, as an array of two ints
  8222. * @throws NotFoundException if pattern is not found
  8223. */
  8224. static findGuardPattern(row, rowOffset, whiteFirst, pattern, counters) {
  8225. let width = row.getSize();
  8226. rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset);
  8227. let counterPosition = 0;
  8228. let patternStart = rowOffset;
  8229. let patternLength = pattern.length;
  8230. let isWhite = whiteFirst;
  8231. for (let x = rowOffset; x < width; x++) {
  8232. if (row.get(x) !== isWhite) {
  8233. counters[counterPosition]++;
  8234. }
  8235. else {
  8236. if (counterPosition === patternLength - 1) {
  8237. if (OneDReader.patternMatchVariance(counters, pattern, AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE) < AbstractUPCEANReader.MAX_AVG_VARIANCE) {
  8238. return Int32Array.from([patternStart, x]);
  8239. }
  8240. patternStart += counters[0] + counters[1];
  8241. let slice = counters.slice(2, counters.length);
  8242. for (let i = 0; i < counterPosition - 1; i++) {
  8243. counters[i] = slice[i];
  8244. }
  8245. counters[counterPosition - 1] = 0;
  8246. counters[counterPosition] = 0;
  8247. counterPosition--;
  8248. }
  8249. else {
  8250. counterPosition++;
  8251. }
  8252. counters[counterPosition] = 1;
  8253. isWhite = !isWhite;
  8254. }
  8255. }
  8256. throw new NotFoundException();
  8257. }
  8258. static decodeDigit(row, counters, rowOffset, patterns) {
  8259. this.recordPattern(row, rowOffset, counters);
  8260. let bestVariance = this.MAX_AVG_VARIANCE;
  8261. let bestMatch = -1;
  8262. let max = patterns.length;
  8263. for (let i = 0; i < max; i++) {
  8264. let pattern = patterns[i];
  8265. let variance = OneDReader.patternMatchVariance(counters, pattern, AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE);
  8266. if (variance < bestVariance) {
  8267. bestVariance = variance;
  8268. bestMatch = i;
  8269. }
  8270. }
  8271. if (bestMatch >= 0) {
  8272. return bestMatch;
  8273. }
  8274. else {
  8275. throw new NotFoundException();
  8276. }
  8277. }
  8278. }
  8279. // These two values are critical for determining how permissive the decoding will be.
  8280. // We've arrived at these values through a lot of trial and error. Setting them any higher
  8281. // lets false positives creep in quickly.
  8282. AbstractUPCEANReader.MAX_AVG_VARIANCE = 0.48;
  8283. AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE = 0.7;
  8284. /**
  8285. * Start/end guard pattern.
  8286. */
  8287. AbstractUPCEANReader.START_END_PATTERN = Int32Array.from([1, 1, 1]);
  8288. /**
  8289. * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.
  8290. */
  8291. AbstractUPCEANReader.MIDDLE_PATTERN = Int32Array.from([1, 1, 1, 1, 1]);
  8292. /**
  8293. * end guard pattern.
  8294. */
  8295. AbstractUPCEANReader.END_PATTERN = Int32Array.from([1, 1, 1, 1, 1, 1]);
  8296. /**
  8297. * "Odd", or "L" patterns used to encode UPC/EAN digits.
  8298. */
  8299. AbstractUPCEANReader.L_PATTERNS = [
  8300. Int32Array.from([3, 2, 1, 1]),
  8301. Int32Array.from([2, 2, 2, 1]),
  8302. Int32Array.from([2, 1, 2, 2]),
  8303. Int32Array.from([1, 4, 1, 1]),
  8304. Int32Array.from([1, 1, 3, 2]),
  8305. Int32Array.from([1, 2, 3, 1]),
  8306. Int32Array.from([1, 1, 1, 4]),
  8307. Int32Array.from([1, 3, 1, 2]),
  8308. Int32Array.from([1, 2, 1, 3]),
  8309. Int32Array.from([3, 1, 1, 2]),
  8310. ];
  8311. /*
  8312. * Copyright (C) 2010 ZXing authors
  8313. *
  8314. * Licensed under the Apache License, Version 2.0 (the "License");
  8315. * you may not use this file except in compliance with the License.
  8316. * You may obtain a copy of the License at
  8317. *
  8318. * http://www.apache.org/licenses/LICENSE-2.0
  8319. *
  8320. * Unless required by applicable law or agreed to in writing, software
  8321. * distributed under the License is distributed on an "AS IS" BASIS,
  8322. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8323. * See the License for the specific language governing permissions and
  8324. * limitations under the License.
  8325. */
  8326. /**
  8327. * @see UPCEANExtension2Support
  8328. */
  8329. class UPCEANExtension5Support {
  8330. constructor() {
  8331. this.CHECK_DIGIT_ENCODINGS = [0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05];
  8332. this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);
  8333. this.decodeRowStringBuffer = '';
  8334. }
  8335. decodeRow(rowNumber, row, extensionStartRange) {
  8336. let result = this.decodeRowStringBuffer;
  8337. let end = this.decodeMiddle(row, extensionStartRange, result);
  8338. let resultString = result.toString();
  8339. let extensionData = UPCEANExtension5Support.parseExtensionString(resultString);
  8340. let resultPoints = [
  8341. new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0, rowNumber),
  8342. new ResultPoint(end, rowNumber)
  8343. ];
  8344. let extensionResult = new Result(resultString, null, 0, resultPoints, BarcodeFormat$1.UPC_EAN_EXTENSION, new Date().getTime());
  8345. if (extensionData != null) {
  8346. extensionResult.putAllMetadata(extensionData);
  8347. }
  8348. return extensionResult;
  8349. }
  8350. decodeMiddle(row, startRange, resultString) {
  8351. let counters = this.decodeMiddleCounters;
  8352. counters[0] = 0;
  8353. counters[1] = 0;
  8354. counters[2] = 0;
  8355. counters[3] = 0;
  8356. let end = row.getSize();
  8357. let rowOffset = startRange[1];
  8358. let lgPatternFound = 0;
  8359. for (let x = 0; x < 5 && rowOffset < end; x++) {
  8360. let bestMatch = AbstractUPCEANReader.decodeDigit(row, counters, rowOffset, AbstractUPCEANReader.L_AND_G_PATTERNS);
  8361. resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));
  8362. for (let counter of counters) {
  8363. rowOffset += counter;
  8364. }
  8365. if (bestMatch >= 10) {
  8366. lgPatternFound |= 1 << (4 - x);
  8367. }
  8368. if (x !== 4) {
  8369. // Read off separator if not last
  8370. rowOffset = row.getNextSet(rowOffset);
  8371. rowOffset = row.getNextUnset(rowOffset);
  8372. }
  8373. }
  8374. if (resultString.length !== 5) {
  8375. throw new NotFoundException();
  8376. }
  8377. let checkDigit = this.determineCheckDigit(lgPatternFound);
  8378. if (UPCEANExtension5Support.extensionChecksum(resultString.toString()) !== checkDigit) {
  8379. throw new NotFoundException();
  8380. }
  8381. return rowOffset;
  8382. }
  8383. static extensionChecksum(s) {
  8384. let length = s.length;
  8385. let sum = 0;
  8386. for (let i = length - 2; i >= 0; i -= 2) {
  8387. sum += s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);
  8388. }
  8389. sum *= 3;
  8390. for (let i = length - 1; i >= 0; i -= 2) {
  8391. sum += s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);
  8392. }
  8393. sum *= 3;
  8394. return sum % 10;
  8395. }
  8396. determineCheckDigit(lgPatternFound) {
  8397. for (let d = 0; d < 10; d++) {
  8398. if (lgPatternFound === this.CHECK_DIGIT_ENCODINGS[d]) {
  8399. return d;
  8400. }
  8401. }
  8402. throw new NotFoundException();
  8403. }
  8404. static parseExtensionString(raw) {
  8405. if (raw.length !== 5) {
  8406. return null;
  8407. }
  8408. let value = UPCEANExtension5Support.parseExtension5String(raw);
  8409. if (value == null) {
  8410. return null;
  8411. }
  8412. return new Map([[ResultMetadataType$1.SUGGESTED_PRICE, value]]);
  8413. }
  8414. static parseExtension5String(raw) {
  8415. let currency;
  8416. switch (raw.charAt(0)) {
  8417. case '0':
  8418. currency = '£';
  8419. break;
  8420. case '5':
  8421. currency = '$';
  8422. break;
  8423. case '9':
  8424. // Reference: http://www.jollytech.com
  8425. switch (raw) {
  8426. case '90000':
  8427. // No suggested retail price
  8428. return null;
  8429. case '99991':
  8430. // Complementary
  8431. return '0.00';
  8432. case '99990':
  8433. return 'Used';
  8434. }
  8435. // Otherwise... unknown currency?
  8436. currency = '';
  8437. break;
  8438. default:
  8439. currency = '';
  8440. break;
  8441. }
  8442. let rawAmount = parseInt(raw.substring(1));
  8443. let unitsString = (rawAmount / 100).toString();
  8444. let hundredths = rawAmount % 100;
  8445. let hundredthsString = hundredths < 10 ? '0' + hundredths : hundredths.toString(); // fixme
  8446. return currency + unitsString + '.' + hundredthsString;
  8447. }
  8448. }
  8449. /*
  8450. * Copyright (C) 2012 ZXing authors
  8451. *
  8452. * Licensed under the Apache License, Version 2.0 (the "License");
  8453. * you may not use this file except in compliance with the License.
  8454. * You may obtain a copy of the License at
  8455. *
  8456. * http://www.apache.org/licenses/LICENSE-2.0
  8457. *
  8458. * Unless required by applicable law or agreed to in writing, software
  8459. * distributed under the License is distributed on an "AS IS" BASIS,
  8460. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8461. * See the License for the specific language governing permissions and
  8462. * limitations under the License.
  8463. */
  8464. /**
  8465. * @see UPCEANExtension5Support
  8466. */
  8467. class UPCEANExtension2Support {
  8468. constructor() {
  8469. this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);
  8470. this.decodeRowStringBuffer = '';
  8471. }
  8472. decodeRow(rowNumber, row, extensionStartRange) {
  8473. let result = this.decodeRowStringBuffer;
  8474. let end = this.decodeMiddle(row, extensionStartRange, result);
  8475. let resultString = result.toString();
  8476. let extensionData = UPCEANExtension2Support.parseExtensionString(resultString);
  8477. let resultPoints = [
  8478. new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0, rowNumber),
  8479. new ResultPoint(end, rowNumber)
  8480. ];
  8481. let extensionResult = new Result(resultString, null, 0, resultPoints, BarcodeFormat$1.UPC_EAN_EXTENSION, new Date().getTime());
  8482. if (extensionData != null) {
  8483. extensionResult.putAllMetadata(extensionData);
  8484. }
  8485. return extensionResult;
  8486. }
  8487. decodeMiddle(row, startRange, resultString) {
  8488. let counters = this.decodeMiddleCounters;
  8489. counters[0] = 0;
  8490. counters[1] = 0;
  8491. counters[2] = 0;
  8492. counters[3] = 0;
  8493. let end = row.getSize();
  8494. let rowOffset = startRange[1];
  8495. let checkParity = 0;
  8496. for (let x = 0; x < 2 && rowOffset < end; x++) {
  8497. let bestMatch = AbstractUPCEANReader.decodeDigit(row, counters, rowOffset, AbstractUPCEANReader.L_AND_G_PATTERNS);
  8498. resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));
  8499. for (let counter of counters) {
  8500. rowOffset += counter;
  8501. }
  8502. if (bestMatch >= 10) {
  8503. checkParity |= 1 << (1 - x);
  8504. }
  8505. if (x !== 1) {
  8506. // Read off separator if not last
  8507. rowOffset = row.getNextSet(rowOffset);
  8508. rowOffset = row.getNextUnset(rowOffset);
  8509. }
  8510. }
  8511. if (resultString.length !== 2) {
  8512. throw new NotFoundException();
  8513. }
  8514. if (parseInt(resultString.toString()) % 4 !== checkParity) {
  8515. throw new NotFoundException();
  8516. }
  8517. return rowOffset;
  8518. }
  8519. static parseExtensionString(raw) {
  8520. if (raw.length !== 2) {
  8521. return null;
  8522. }
  8523. return new Map([[ResultMetadataType$1.ISSUE_NUMBER, parseInt(raw)]]);
  8524. }
  8525. }
  8526. /*
  8527. * Copyright (C) 2010 ZXing authors
  8528. *
  8529. * Licensed under the Apache License, Version 2.0 (the "License");
  8530. * you may not use this file except in compliance with the License.
  8531. * You may obtain a copy of the License at
  8532. *
  8533. * http://www.apache.org/licenses/LICENSE-2.0
  8534. *
  8535. * Unless required by applicable law or agreed to in writing, software
  8536. * distributed under the License is distributed on an "AS IS" BASIS,
  8537. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8538. * See the License for the specific language governing permissions and
  8539. * limitations under the License.
  8540. */
  8541. class UPCEANExtensionSupport {
  8542. static decodeRow(rowNumber, row, rowOffset) {
  8543. let extensionStartRange = AbstractUPCEANReader.findGuardPattern(row, rowOffset, false, this.EXTENSION_START_PATTERN, new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));
  8544. try {
  8545. // return null;
  8546. let fiveSupport = new UPCEANExtension5Support();
  8547. return fiveSupport.decodeRow(rowNumber, row, extensionStartRange);
  8548. }
  8549. catch (err) {
  8550. // return null;
  8551. let twoSupport = new UPCEANExtension2Support();
  8552. return twoSupport.decodeRow(rowNumber, row, extensionStartRange);
  8553. }
  8554. }
  8555. }
  8556. UPCEANExtensionSupport.EXTENSION_START_PATTERN = Int32Array.from([1, 1, 2]);
  8557. /*
  8558. * Copyright 2008 ZXing authors
  8559. *
  8560. * Licensed under the Apache License, Version 2.0 (the "License");
  8561. * you may not use this file except in compliance with the License.
  8562. * You may obtain a copy of the License at
  8563. *
  8564. * http://www.apache.org/licenses/LICENSE-2.0
  8565. *
  8566. * Unless required by applicable law or agreed to in writing, software
  8567. * distributed under the License is distributed on an "AS IS" BASIS,
  8568. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8569. * See the License for the specific language governing permissions and
  8570. * limitations under the License.
  8571. */
  8572. /**
  8573. * <p>Encapsulates functionality and implementation that is common to UPC and EAN families
  8574. * of one-dimensional barcodes.</p>
  8575. *
  8576. * @author dswitkin@google.com (Daniel Switkin)
  8577. * @author Sean Owen
  8578. * @author alasdair@google.com (Alasdair Mackintosh)
  8579. */
  8580. class UPCEANReader extends AbstractUPCEANReader {
  8581. constructor() {
  8582. super();
  8583. this.decodeRowStringBuffer = '';
  8584. UPCEANReader.L_AND_G_PATTERNS = UPCEANReader.L_PATTERNS.map(arr => Int32Array.from(arr));
  8585. for (let i = 10; i < 20; i++) {
  8586. let widths = UPCEANReader.L_PATTERNS[i - 10];
  8587. let reversedWidths = new Int32Array(widths.length);
  8588. for (let j = 0; j < widths.length; j++) {
  8589. reversedWidths[j] = widths[widths.length - j - 1];
  8590. }
  8591. UPCEANReader.L_AND_G_PATTERNS[i] = reversedWidths;
  8592. }
  8593. }
  8594. decodeRow(rowNumber, row, hints) {
  8595. let startGuardRange = UPCEANReader.findStartGuardPattern(row);
  8596. let resultPointCallback = hints == null ? null : hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);
  8597. if (resultPointCallback != null) {
  8598. const resultPoint = new ResultPoint((startGuardRange[0] + startGuardRange[1]) / 2.0, rowNumber);
  8599. resultPointCallback.foundPossibleResultPoint(resultPoint);
  8600. }
  8601. let budello = this.decodeMiddle(row, startGuardRange, this.decodeRowStringBuffer);
  8602. let endStart = budello.rowOffset;
  8603. let result = budello.resultString;
  8604. if (resultPointCallback != null) {
  8605. const resultPoint = new ResultPoint(endStart, rowNumber);
  8606. resultPointCallback.foundPossibleResultPoint(resultPoint);
  8607. }
  8608. let endRange = UPCEANReader.decodeEnd(row, endStart);
  8609. if (resultPointCallback != null) {
  8610. const resultPoint = new ResultPoint((endRange[0] + endRange[1]) / 2.0, rowNumber);
  8611. resultPointCallback.foundPossibleResultPoint(resultPoint);
  8612. }
  8613. // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The
  8614. // spec might want more whitespace, but in practice this is the maximum we can count on.
  8615. let end = endRange[1];
  8616. let quietEnd = end + (end - endRange[0]);
  8617. if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {
  8618. throw new NotFoundException();
  8619. }
  8620. let resultString = result.toString();
  8621. // UPC/EAN should never be less than 8 chars anyway
  8622. if (resultString.length < 8) {
  8623. throw new FormatException();
  8624. }
  8625. if (!UPCEANReader.checkChecksum(resultString)) {
  8626. throw new ChecksumException();
  8627. }
  8628. let left = (startGuardRange[1] + startGuardRange[0]) / 2.0;
  8629. let right = (endRange[1] + endRange[0]) / 2.0;
  8630. let format = this.getBarcodeFormat();
  8631. let resultPoint = [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)];
  8632. let decodeResult = new Result(resultString, null, 0, resultPoint, format, new Date().getTime());
  8633. let extensionLength = 0;
  8634. try {
  8635. let extensionResult = UPCEANExtensionSupport.decodeRow(rowNumber, row, endRange[1]);
  8636. decodeResult.putMetadata(ResultMetadataType$1.UPC_EAN_EXTENSION, extensionResult.getText());
  8637. decodeResult.putAllMetadata(extensionResult.getResultMetadata());
  8638. decodeResult.addResultPoints(extensionResult.getResultPoints());
  8639. extensionLength = extensionResult.getText().length;
  8640. }
  8641. catch (err) {
  8642. }
  8643. let allowedExtensions = hints == null ? null : hints.get(DecodeHintType$1.ALLOWED_EAN_EXTENSIONS);
  8644. if (allowedExtensions != null) {
  8645. let valid = false;
  8646. for (let length in allowedExtensions) {
  8647. if (extensionLength.toString() === length) { // check me
  8648. valid = true;
  8649. break;
  8650. }
  8651. }
  8652. if (!valid) {
  8653. throw new NotFoundException();
  8654. }
  8655. }
  8656. if (format === BarcodeFormat$1.EAN_13 || format === BarcodeFormat$1.UPC_A) ;
  8657. return decodeResult;
  8658. }
  8659. static checkChecksum(s) {
  8660. return UPCEANReader.checkStandardUPCEANChecksum(s);
  8661. }
  8662. static checkStandardUPCEANChecksum(s) {
  8663. let length = s.length;
  8664. if (length === 0)
  8665. return false;
  8666. let check = parseInt(s.charAt(length - 1), 10);
  8667. return UPCEANReader.getStandardUPCEANChecksum(s.substring(0, length - 1)) === check;
  8668. }
  8669. static getStandardUPCEANChecksum(s) {
  8670. let length = s.length;
  8671. let sum = 0;
  8672. for (let i = length - 1; i >= 0; i -= 2) {
  8673. let digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);
  8674. if (digit < 0 || digit > 9) {
  8675. throw new FormatException();
  8676. }
  8677. sum += digit;
  8678. }
  8679. sum *= 3;
  8680. for (let i = length - 2; i >= 0; i -= 2) {
  8681. let digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);
  8682. if (digit < 0 || digit > 9) {
  8683. throw new FormatException();
  8684. }
  8685. sum += digit;
  8686. }
  8687. return (1000 - sum) % 10;
  8688. }
  8689. static decodeEnd(row, endStart) {
  8690. return UPCEANReader.findGuardPattern(row, endStart, false, UPCEANReader.START_END_PATTERN, new Int32Array(UPCEANReader.START_END_PATTERN.length).fill(0));
  8691. }
  8692. }
  8693. /*
  8694. * Copyright 2008 ZXing authors
  8695. *
  8696. * Licensed under the Apache License, Version 2.0 (the "License");
  8697. * you may not use this file except in compliance with the License.
  8698. * You may obtain a copy of the License at
  8699. *
  8700. * http://www.apache.org/licenses/LICENSE-2.0
  8701. *
  8702. * Unless required by applicable law or agreed to in writing, software
  8703. * distributed under the License is distributed on an "AS IS" BASIS,
  8704. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8705. * See the License for the specific language governing permissions and
  8706. * limitations under the License.
  8707. */
  8708. /**
  8709. * <p>Implements decoding of the EAN-13 format.</p>
  8710. *
  8711. * @author dswitkin@google.com (Daniel Switkin)
  8712. * @author Sean Owen
  8713. * @author alasdair@google.com (Alasdair Mackintosh)
  8714. */
  8715. class EAN13Reader extends UPCEANReader {
  8716. constructor() {
  8717. super();
  8718. this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);
  8719. }
  8720. decodeMiddle(row, startRange, resultString) {
  8721. let counters = this.decodeMiddleCounters;
  8722. counters[0] = 0;
  8723. counters[1] = 0;
  8724. counters[2] = 0;
  8725. counters[3] = 0;
  8726. let end = row.getSize();
  8727. let rowOffset = startRange[1];
  8728. let lgPatternFound = 0;
  8729. for (let x = 0; x < 6 && rowOffset < end; x++) {
  8730. let bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS);
  8731. resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));
  8732. for (let counter of counters) {
  8733. rowOffset += counter;
  8734. }
  8735. if (bestMatch >= 10) {
  8736. lgPatternFound |= 1 << (5 - x);
  8737. }
  8738. }
  8739. resultString = EAN13Reader.determineFirstDigit(resultString, lgPatternFound);
  8740. let middleRange = UPCEANReader.findGuardPattern(row, rowOffset, true, UPCEANReader.MIDDLE_PATTERN, new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));
  8741. rowOffset = middleRange[1];
  8742. for (let x = 0; x < 6 && rowOffset < end; x++) {
  8743. let bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_PATTERNS);
  8744. resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch));
  8745. for (let counter of counters) {
  8746. rowOffset += counter;
  8747. }
  8748. }
  8749. return { rowOffset, resultString };
  8750. }
  8751. getBarcodeFormat() {
  8752. return BarcodeFormat$1.EAN_13;
  8753. }
  8754. static determineFirstDigit(resultString, lgPatternFound) {
  8755. for (let d = 0; d < 10; d++) {
  8756. if (lgPatternFound === this.FIRST_DIGIT_ENCODINGS[d]) {
  8757. resultString = String.fromCharCode(('0'.charCodeAt(0) + d)) + resultString;
  8758. return resultString;
  8759. }
  8760. }
  8761. throw new NotFoundException();
  8762. }
  8763. }
  8764. EAN13Reader.FIRST_DIGIT_ENCODINGS = [0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A];
  8765. /*
  8766. * Copyright 2008 ZXing authors
  8767. *
  8768. * Licensed under the Apache License, Version 2.0 (the "License");
  8769. * you may not use this file except in compliance with the License.
  8770. * You may obtain a copy of the License at
  8771. *
  8772. * http://www.apache.org/licenses/LICENSE-2.0
  8773. *
  8774. * Unless required by applicable law or agreed to in writing, software
  8775. * distributed under the License is distributed on an "AS IS" BASIS,
  8776. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8777. * See the License for the specific language governing permissions and
  8778. * limitations under the License.
  8779. */
  8780. /**
  8781. * <p>Implements decoding of the EAN-8 format.</p>
  8782. *
  8783. * @author Sean Owen
  8784. */
  8785. class EAN8Reader extends UPCEANReader {
  8786. constructor() {
  8787. super();
  8788. this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);
  8789. }
  8790. decodeMiddle(row, startRange, resultString) {
  8791. const counters = this.decodeMiddleCounters;
  8792. counters[0] = 0;
  8793. counters[1] = 0;
  8794. counters[2] = 0;
  8795. counters[3] = 0;
  8796. let end = row.getSize();
  8797. let rowOffset = startRange[1];
  8798. for (let x = 0; x < 4 && rowOffset < end; x++) {
  8799. let bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_PATTERNS);
  8800. resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch));
  8801. for (let counter of counters) {
  8802. rowOffset += counter;
  8803. }
  8804. }
  8805. let middleRange = UPCEANReader.findGuardPattern(row, rowOffset, true, UPCEANReader.MIDDLE_PATTERN, new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));
  8806. rowOffset = middleRange[1];
  8807. for (let x = 0; x < 4 && rowOffset < end; x++) {
  8808. let bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_PATTERNS);
  8809. resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch));
  8810. for (let counter of counters) {
  8811. rowOffset += counter;
  8812. }
  8813. }
  8814. return { rowOffset, resultString };
  8815. }
  8816. getBarcodeFormat() {
  8817. return BarcodeFormat$1.EAN_8;
  8818. }
  8819. }
  8820. /*
  8821. * Copyright 2008 ZXing authors
  8822. *
  8823. * Licensed under the Apache License, Version 2.0 (the "License");
  8824. * you may not use this file except in compliance with the License.
  8825. * You may obtain a copy of the License at
  8826. *
  8827. * http://www.apache.org/licenses/LICENSE-2.0
  8828. *
  8829. * Unless required by applicable law or agreed to in writing, software
  8830. * distributed under the License is distributed on an "AS IS" BASIS,
  8831. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8832. * See the License for the specific language governing permissions and
  8833. * limitations under the License.
  8834. */
  8835. /**
  8836. * Encapsulates functionality and implementation that is common to all families
  8837. * of one-dimensional barcodes.
  8838. *
  8839. * @author dswitkin@google.com (Daniel Switkin)
  8840. * @author Sean Owen
  8841. * @author sam2332 (Sam Rudloff)
  8842. *
  8843. * @source https://github.com/zxing/zxing/blob/3c96923276dd5785d58eb970b6ba3f80d36a9505/core/src/main/java/com/google/zxing/oned/UPCAReader.java
  8844. *
  8845. * @experimental
  8846. */
  8847. class UPCAReader extends UPCEANReader {
  8848. constructor() {
  8849. super(...arguments);
  8850. this.ean13Reader = new EAN13Reader();
  8851. }
  8852. // @Override
  8853. getBarcodeFormat() {
  8854. return BarcodeFormat$1.UPC_A;
  8855. }
  8856. // Note that we don't try rotation without the try harder flag, even if rotation was supported.
  8857. // @Override
  8858. decode(image, hints) {
  8859. return this.maybeReturnResult(this.ean13Reader.decode(image));
  8860. }
  8861. // @Override
  8862. decodeRow(rowNumber, row, hints) {
  8863. return this.maybeReturnResult(this.ean13Reader.decodeRow(rowNumber, row, hints));
  8864. }
  8865. // @Override
  8866. decodeMiddle(row, startRange, resultString) {
  8867. return this.ean13Reader.decodeMiddle(row, startRange, resultString);
  8868. }
  8869. maybeReturnResult(result) {
  8870. let text = result.getText();
  8871. if (text.charAt(0) === '0') {
  8872. let upcaResult = new Result(text.substring(1), null, null, result.getResultPoints(), BarcodeFormat$1.UPC_A);
  8873. if (result.getResultMetadata() != null) {
  8874. upcaResult.putAllMetadata(result.getResultMetadata());
  8875. }
  8876. return upcaResult;
  8877. }
  8878. else {
  8879. throw new NotFoundException();
  8880. }
  8881. }
  8882. reset() {
  8883. this.ean13Reader.reset();
  8884. }
  8885. }
  8886. /*
  8887. * Copyright 2008 ZXing authors
  8888. *
  8889. * Licensed under the Apache License, Version 2.0 (the "License");
  8890. * you may not use this file except in compliance with the License.
  8891. * You may obtain a copy of the License at
  8892. *
  8893. * http://www.apache.org/licenses/LICENSE-2.0
  8894. *
  8895. * Unless required by applicable law or agreed to in writing, software
  8896. * distributed under the License is distributed on an "AS IS" BASIS,
  8897. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8898. * See the License for the specific language governing permissions and
  8899. * limitations under the License.
  8900. */
  8901. // package com.google.zxing.oned;
  8902. // import com.google.zxing.BarcodeFormat;
  8903. // import com.google.zxing.FormatException;
  8904. // import com.google.zxing.NotFoundException;
  8905. // import com.google.zxing.common.BitArray;
  8906. /**
  8907. * <p>Implements decoding of the UPC-E format.</p>
  8908. * <p><a href="http://www.barcodeisland.com/upce.phtml">This</a> is a great reference for
  8909. * UPC-E information.</p>
  8910. *
  8911. * @author Sean Owen
  8912. *
  8913. * @source https://github.com/zxing/zxing/blob/3c96923276dd5785d58eb970b6ba3f80d36a9505/core/src/main/java/com/google/zxing/oned/UPCEReader.java
  8914. *
  8915. * @experimental
  8916. */
  8917. /* final */ class UPCEReader extends UPCEANReader {
  8918. constructor() {
  8919. super();
  8920. this.decodeMiddleCounters = new Int32Array(4);
  8921. }
  8922. /**
  8923. * @throws NotFoundException
  8924. */
  8925. // @Override
  8926. decodeMiddle(row, startRange, result) {
  8927. const counters = this.decodeMiddleCounters.map(x => x);
  8928. counters[0] = 0;
  8929. counters[1] = 0;
  8930. counters[2] = 0;
  8931. counters[3] = 0;
  8932. const end = row.getSize();
  8933. let rowOffset = startRange[1];
  8934. let lgPatternFound = 0;
  8935. for (let x = 0; x < 6 && rowOffset < end; x++) {
  8936. const bestMatch = UPCEReader.decodeDigit(row, counters, rowOffset, UPCEReader.L_AND_G_PATTERNS);
  8937. result += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));
  8938. for (let counter of counters) {
  8939. rowOffset += counter;
  8940. }
  8941. if (bestMatch >= 10) {
  8942. lgPatternFound |= 1 << (5 - x);
  8943. }
  8944. }
  8945. UPCEReader.determineNumSysAndCheckDigit(new StringBuilder(result), lgPatternFound);
  8946. return rowOffset;
  8947. }
  8948. /**
  8949. * @throws NotFoundException
  8950. */
  8951. // @Override
  8952. decodeEnd(row, endStart) {
  8953. return UPCEReader.findGuardPatternWithoutCounters(row, endStart, true, UPCEReader.MIDDLE_END_PATTERN);
  8954. }
  8955. /**
  8956. * @throws FormatException
  8957. */
  8958. // @Override
  8959. checkChecksum(s) {
  8960. return UPCEANReader.checkChecksum(UPCEReader.convertUPCEtoUPCA(s));
  8961. }
  8962. /**
  8963. * @throws NotFoundException
  8964. */
  8965. static determineNumSysAndCheckDigit(resultString, lgPatternFound) {
  8966. for (let numSys = 0; numSys <= 1; numSys++) {
  8967. for (let d = 0; d < 10; d++) {
  8968. if (lgPatternFound === this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) {
  8969. resultString.insert(0, /*(char)*/ ('0' + numSys));
  8970. resultString.append(/*(char)*/ ('0' + d));
  8971. return;
  8972. }
  8973. }
  8974. }
  8975. throw NotFoundException.getNotFoundInstance();
  8976. }
  8977. // @Override
  8978. getBarcodeFormat() {
  8979. return BarcodeFormat$1.UPC_E;
  8980. }
  8981. /**
  8982. * Expands a UPC-E value back into its full, equivalent UPC-A code value.
  8983. *
  8984. * @param upce UPC-E code as string of digits
  8985. * @return equivalent UPC-A code as string of digits
  8986. */
  8987. static convertUPCEtoUPCA(upce) {
  8988. // the following line is equivalent to upce.getChars(1, 7, upceChars, 0);
  8989. const upceChars = upce.slice(1, 7).split('').map(x => x.charCodeAt(0));
  8990. const result = new StringBuilder( /*12*/);
  8991. result.append(upce.charAt(0));
  8992. let lastChar = upceChars[5];
  8993. switch (lastChar) {
  8994. case 0:
  8995. case 1:
  8996. case 2:
  8997. result.appendChars(upceChars, 0, 2);
  8998. result.append(lastChar);
  8999. result.append('0000');
  9000. result.appendChars(upceChars, 2, 3);
  9001. break;
  9002. case 3:
  9003. result.appendChars(upceChars, 0, 3);
  9004. result.append('00000');
  9005. result.appendChars(upceChars, 3, 2);
  9006. break;
  9007. case 4:
  9008. result.appendChars(upceChars, 0, 4);
  9009. result.append('00000');
  9010. result.append(upceChars[4]);
  9011. break;
  9012. default:
  9013. result.appendChars(upceChars, 0, 5);
  9014. result.append('0000');
  9015. result.append(lastChar);
  9016. break;
  9017. }
  9018. // Only append check digit in conversion if supplied
  9019. if (upce.length >= 8) {
  9020. result.append(upce.charAt(7));
  9021. }
  9022. return result.toString();
  9023. }
  9024. }
  9025. /**
  9026. * The pattern that marks the middle, and end, of a UPC-E pattern.
  9027. * There is no "second half" to a UPC-E barcode.
  9028. */
  9029. UPCEReader.MIDDLE_END_PATTERN = Int32Array.from([1, 1, 1, 1, 1, 1]);
  9030. // For an UPC-E barcode, the final digit is represented by the parities used
  9031. // to encode the middle six digits, according to the table below.
  9032. //
  9033. // Parity of next 6 digits
  9034. // Digit 0 1 2 3 4 5
  9035. // 0 Even Even Even Odd Odd Odd
  9036. // 1 Even Even Odd Even Odd Odd
  9037. // 2 Even Even Odd Odd Even Odd
  9038. // 3 Even Even Odd Odd Odd Even
  9039. // 4 Even Odd Even Even Odd Odd
  9040. // 5 Even Odd Odd Even Even Odd
  9041. // 6 Even Odd Odd Odd Even Even
  9042. // 7 Even Odd Even Odd Even Odd
  9043. // 8 Even Odd Even Odd Odd Even
  9044. // 9 Even Odd Odd Even Odd Even
  9045. //
  9046. // The encoding is represented by the following array, which is a bit pattern
  9047. // using Odd = 0 and Even = 1. For example, 5 is represented by:
  9048. //
  9049. // Odd Even Even Odd Odd Even
  9050. // in binary:
  9051. // 0 1 1 0 0 1 == 0x19
  9052. //
  9053. /**
  9054. * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of
  9055. * even-odd parity encodings of digits that imply both the number system (0 or 1)
  9056. * used, and the check digit.
  9057. */
  9058. UPCEReader.NUMSYS_AND_CHECK_DIGIT_PATTERNS = [
  9059. Int32Array.from([0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25]),
  9060. Int32Array.from([0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1]),
  9061. ];
  9062. /*
  9063. * Copyright 2008 ZXing authors
  9064. *
  9065. * Licensed under the Apache License, Version 2.0 (the "License");
  9066. * you may not use this file except in compliance with the License.
  9067. * You may obtain a copy of the License at
  9068. *
  9069. * http://www.apache.org/licenses/LICENSE-2.0
  9070. *
  9071. * Unless required by applicable law or agreed to in writing, software
  9072. * distributed under the License is distributed on an "AS IS" BASIS,
  9073. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9074. * See the License for the specific language governing permissions and
  9075. * limitations under the License.
  9076. */
  9077. /**
  9078. * <p>A reader that can read all available UPC/EAN formats. If a caller wants to try to
  9079. * read all such formats, it is most efficient to use this implementation rather than invoke
  9080. * individual readers.</p>
  9081. *
  9082. * @author Sean Owen
  9083. */
  9084. class MultiFormatUPCEANReader extends OneDReader {
  9085. constructor(hints) {
  9086. super();
  9087. let possibleFormats = hints == null ? null : hints.get(DecodeHintType$1.POSSIBLE_FORMATS);
  9088. let readers = [];
  9089. if (possibleFormats != null) {
  9090. if (possibleFormats.indexOf(BarcodeFormat$1.EAN_13) > -1) {
  9091. readers.push(new EAN13Reader());
  9092. }
  9093. if (possibleFormats.indexOf(BarcodeFormat$1.UPC_A) > -1) {
  9094. readers.push(new UPCAReader());
  9095. }
  9096. if (possibleFormats.indexOf(BarcodeFormat$1.EAN_8) > -1) {
  9097. readers.push(new EAN8Reader());
  9098. }
  9099. if (possibleFormats.indexOf(BarcodeFormat$1.UPC_E) > -1) {
  9100. readers.push(new UPCEReader());
  9101. }
  9102. }
  9103. if (readers.length === 0) {
  9104. readers.push(new EAN13Reader());
  9105. readers.push(new UPCAReader());
  9106. readers.push(new EAN8Reader());
  9107. readers.push(new UPCEReader());
  9108. }
  9109. this.readers = readers;
  9110. }
  9111. decodeRow(rowNumber, row, hints) {
  9112. for (let reader of this.readers) {
  9113. try {
  9114. // const result: Result = reader.decodeRow(rowNumber, row, startGuardPattern, hints);
  9115. const result = reader.decodeRow(rowNumber, row, hints);
  9116. // Special case: a 12-digit code encoded in UPC-A is identical to a "0"
  9117. // followed by those 12 digits encoded as EAN-13. Each will recognize such a code,
  9118. // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0".
  9119. // Individually these are correct and their readers will both read such a code
  9120. // and correctly call it EAN-13, or UPC-A, respectively.
  9121. //
  9122. // In this case, if we've been looking for both types, we'd like to call it
  9123. // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read
  9124. // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
  9125. // result if appropriate.
  9126. //
  9127. // But, don't return UPC-A if UPC-A was not a requested format!
  9128. const ean13MayBeUPCA = result.getBarcodeFormat() === BarcodeFormat$1.EAN_13 &&
  9129. result.getText().charAt(0) === '0';
  9130. // @SuppressWarnings("unchecked")
  9131. const possibleFormats = hints == null ? null : hints.get(DecodeHintType$1.POSSIBLE_FORMATS);
  9132. const canReturnUPCA = possibleFormats == null || possibleFormats.includes(BarcodeFormat$1.UPC_A);
  9133. if (ean13MayBeUPCA && canReturnUPCA) {
  9134. const rawBytes = result.getRawBytes();
  9135. // Transfer the metadata across
  9136. const resultUPCA = new Result(result.getText().substring(1), rawBytes, (rawBytes ? rawBytes.length : null), result.getResultPoints(), BarcodeFormat$1.UPC_A);
  9137. resultUPCA.putAllMetadata(result.getResultMetadata());
  9138. return resultUPCA;
  9139. }
  9140. return result;
  9141. }
  9142. catch (err) {
  9143. // continue;
  9144. }
  9145. }
  9146. throw new NotFoundException();
  9147. }
  9148. reset() {
  9149. for (let reader of this.readers) {
  9150. reader.reset();
  9151. }
  9152. }
  9153. }
  9154. /*
  9155. * Copyright 2008 ZXing authors
  9156. *
  9157. * Licensed under the Apache License, Version 2.0 (the "License");
  9158. * you may not use this file except in compliance with the License.
  9159. * You may obtain a copy of the License at
  9160. *
  9161. * http://www.apache.org/licenses/LICENSE-2.0
  9162. *
  9163. * Unless required by applicable law or agreed to in writing, software
  9164. * distributed under the License is distributed on an "AS IS" BASIS,
  9165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9166. * See the License for the specific language governing permissions and
  9167. * limitations under the License.
  9168. */
  9169. /**
  9170. * <p>Decodes CodaBar barcodes. </p>
  9171. *
  9172. * @author Evan @dodobelieve
  9173. * @see CodaBarReader
  9174. */
  9175. class CodaBarReader extends OneDReader {
  9176. constructor() {
  9177. super(...arguments);
  9178. this.CODA_BAR_CHAR_SET = {
  9179. nnnnnww: '0',
  9180. nnnnwwn: '1',
  9181. nnnwnnw: '2',
  9182. wwnnnnn: '3',
  9183. nnwnnwn: '4',
  9184. wnnnnwn: '5',
  9185. nwnnnnw: '6',
  9186. nwnnwnn: '7',
  9187. nwwnnnn: '8',
  9188. wnnwnnn: '9',
  9189. nnnwwnn: '-',
  9190. nnwwnnn: '$',
  9191. wnnnwnw: ':',
  9192. wnwnnnw: '/',
  9193. wnwnwnn: '.',
  9194. nnwwwww: '+',
  9195. nnwwnwn: 'A',
  9196. nwnwnnw: 'B',
  9197. nnnwnww: 'C',
  9198. nnnwwwn: 'D'
  9199. };
  9200. }
  9201. decodeRow(rowNumber, row, hints) {
  9202. let validRowData = this.getValidRowData(row);
  9203. if (!validRowData)
  9204. throw new NotFoundException();
  9205. let retStr = this.codaBarDecodeRow(validRowData.row);
  9206. if (!retStr)
  9207. throw new NotFoundException();
  9208. return new Result(retStr, null, 0, [new ResultPoint(validRowData.left, rowNumber), new ResultPoint(validRowData.right, rowNumber)], BarcodeFormat$1.CODABAR, new Date().getTime());
  9209. }
  9210. /**
  9211. * converts bit array to valid data array(lengths of black bits and white bits)
  9212. * @param row bit array to convert
  9213. */
  9214. getValidRowData(row) {
  9215. let booleanArr = row.toArray();
  9216. let startIndex = booleanArr.indexOf(true);
  9217. if (startIndex === -1)
  9218. return null;
  9219. let lastIndex = booleanArr.lastIndexOf(true);
  9220. if (lastIndex <= startIndex)
  9221. return null;
  9222. booleanArr = booleanArr.slice(startIndex, lastIndex + 1);
  9223. let result = [];
  9224. let lastBit = booleanArr[0];
  9225. let bitLength = 1;
  9226. for (let i = 1; i < booleanArr.length; i++) {
  9227. if (booleanArr[i] === lastBit) {
  9228. bitLength++;
  9229. }
  9230. else {
  9231. lastBit = booleanArr[i];
  9232. result.push(bitLength);
  9233. bitLength = 1;
  9234. }
  9235. }
  9236. result.push(bitLength);
  9237. // CodaBar code data valid
  9238. if (result.length < 23 && (result.length + 1) % 8 !== 0)
  9239. return null;
  9240. return { row: result, left: startIndex, right: lastIndex };
  9241. }
  9242. /**
  9243. * decode codabar code
  9244. * @param row row to cecode
  9245. */
  9246. codaBarDecodeRow(row) {
  9247. const code = [];
  9248. const barThreshold = Math.ceil(row.reduce((pre, item) => (pre + item) / 2, 0));
  9249. // Read one encoded character at a time.
  9250. while (row.length > 0) {
  9251. const seg = row.splice(0, 8).splice(0, 7);
  9252. const key = seg.map(len => (len < barThreshold ? 'n' : 'w')).join('');
  9253. if (this.CODA_BAR_CHAR_SET[key] === undefined)
  9254. return null;
  9255. code.push(this.CODA_BAR_CHAR_SET[key]);
  9256. }
  9257. let strCode = code.join('');
  9258. if (this.validCodaBarString(strCode))
  9259. return strCode;
  9260. return null;
  9261. }
  9262. /**
  9263. * check if the string is a CodaBar string
  9264. * @param src string to determine
  9265. */
  9266. validCodaBarString(src) {
  9267. let reg = /^[A-D].{1,}[A-D]$/;
  9268. return reg.test(src);
  9269. }
  9270. }
  9271. // import Integer from '../../util/Integer';
  9272. // import Float from '../../util/Float';
  9273. class AbstractRSSReader extends OneDReader {
  9274. constructor() {
  9275. super();
  9276. this.decodeFinderCounters = new Int32Array(4);
  9277. this.dataCharacterCounters = new Int32Array(8);
  9278. this.oddRoundingErrors = new Array(4);
  9279. this.evenRoundingErrors = new Array(4);
  9280. this.oddCounts = new Array(this.dataCharacterCounters.length / 2);
  9281. this.evenCounts = new Array(this.dataCharacterCounters.length / 2);
  9282. }
  9283. getDecodeFinderCounters() {
  9284. return this.decodeFinderCounters;
  9285. }
  9286. getDataCharacterCounters() {
  9287. return this.dataCharacterCounters;
  9288. }
  9289. getOddRoundingErrors() {
  9290. return this.oddRoundingErrors;
  9291. }
  9292. getEvenRoundingErrors() {
  9293. return this.evenRoundingErrors;
  9294. }
  9295. getOddCounts() {
  9296. return this.oddCounts;
  9297. }
  9298. getEvenCounts() {
  9299. return this.evenCounts;
  9300. }
  9301. parseFinderValue(counters, finderPatterns) {
  9302. for (let value = 0; value < finderPatterns.length; value++) {
  9303. if (OneDReader.patternMatchVariance(counters, finderPatterns[value], AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE) < AbstractRSSReader.MAX_AVG_VARIANCE) {
  9304. return value;
  9305. }
  9306. }
  9307. throw new NotFoundException();
  9308. }
  9309. /**
  9310. * @param array values to sum
  9311. * @return sum of values
  9312. * @deprecated call {@link MathUtils#sum(int[])}
  9313. */
  9314. static count(array) {
  9315. return MathUtils.sum(new Int32Array(array));
  9316. }
  9317. static increment(array, errors) {
  9318. let index = 0;
  9319. let biggestError = errors[0];
  9320. for (let i = 1; i < array.length; i++) {
  9321. if (errors[i] > biggestError) {
  9322. biggestError = errors[i];
  9323. index = i;
  9324. }
  9325. }
  9326. array[index]++;
  9327. }
  9328. static decrement(array, errors) {
  9329. let index = 0;
  9330. let biggestError = errors[0];
  9331. for (let i = 1; i < array.length; i++) {
  9332. if (errors[i] < biggestError) {
  9333. biggestError = errors[i];
  9334. index = i;
  9335. }
  9336. }
  9337. array[index]--;
  9338. }
  9339. static isFinderPattern(counters) {
  9340. let firstTwoSum = counters[0] + counters[1];
  9341. let sum = firstTwoSum + counters[2] + counters[3];
  9342. let ratio = firstTwoSum / sum;
  9343. if (ratio >= AbstractRSSReader.MIN_FINDER_PATTERN_RATIO && ratio <= AbstractRSSReader.MAX_FINDER_PATTERN_RATIO) {
  9344. // passes ratio test in spec, but see if the counts are unreasonable
  9345. let minCounter = Number.MAX_SAFE_INTEGER;
  9346. let maxCounter = Number.MIN_SAFE_INTEGER;
  9347. for (let counter of counters) {
  9348. if (counter > maxCounter) {
  9349. maxCounter = counter;
  9350. }
  9351. if (counter < minCounter) {
  9352. minCounter = counter;
  9353. }
  9354. }
  9355. return maxCounter < 10 * minCounter;
  9356. }
  9357. return false;
  9358. }
  9359. }
  9360. AbstractRSSReader.MAX_AVG_VARIANCE = 0.2;
  9361. AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE = 0.45;
  9362. AbstractRSSReader.MIN_FINDER_PATTERN_RATIO = 9.5 / 12.0;
  9363. AbstractRSSReader.MAX_FINDER_PATTERN_RATIO = 12.5 / 14.0;
  9364. class DataCharacter {
  9365. constructor(value, checksumPortion) {
  9366. this.value = value;
  9367. this.checksumPortion = checksumPortion;
  9368. }
  9369. getValue() {
  9370. return this.value;
  9371. }
  9372. getChecksumPortion() {
  9373. return this.checksumPortion;
  9374. }
  9375. toString() {
  9376. return this.value + '(' + this.checksumPortion + ')';
  9377. }
  9378. equals(o) {
  9379. if (!(o instanceof DataCharacter)) {
  9380. return false;
  9381. }
  9382. const that = o;
  9383. return this.value === that.value && this.checksumPortion === that.checksumPortion;
  9384. }
  9385. hashCode() {
  9386. return this.value ^ this.checksumPortion;
  9387. }
  9388. }
  9389. class FinderPattern {
  9390. constructor(value, startEnd, start, end, rowNumber) {
  9391. this.value = value;
  9392. this.startEnd = startEnd;
  9393. this.value = value;
  9394. this.startEnd = startEnd;
  9395. this.resultPoints = new Array();
  9396. this.resultPoints.push(new ResultPoint(start, rowNumber));
  9397. this.resultPoints.push(new ResultPoint(end, rowNumber));
  9398. }
  9399. getValue() {
  9400. return this.value;
  9401. }
  9402. getStartEnd() {
  9403. return this.startEnd;
  9404. }
  9405. getResultPoints() {
  9406. return this.resultPoints;
  9407. }
  9408. equals(o) {
  9409. if (!(o instanceof FinderPattern)) {
  9410. return false;
  9411. }
  9412. const that = o;
  9413. return this.value === that.value;
  9414. }
  9415. hashCode() {
  9416. return this.value;
  9417. }
  9418. }
  9419. /**
  9420. * RSS util functions.
  9421. */
  9422. class RSSUtils {
  9423. constructor() { }
  9424. static getRSSvalue(widths, maxWidth, noNarrow) {
  9425. let n = 0;
  9426. for (let width of widths) {
  9427. n += width;
  9428. }
  9429. let val = 0;
  9430. let narrowMask = 0;
  9431. let elements = widths.length;
  9432. for (let bar = 0; bar < elements - 1; bar++) {
  9433. let elmWidth;
  9434. for (elmWidth = 1, narrowMask |= 1 << bar; elmWidth < widths[bar]; elmWidth++, narrowMask &= ~(1 << bar)) {
  9435. let subVal = RSSUtils.combins(n - elmWidth - 1, elements - bar - 2);
  9436. if (noNarrow && (narrowMask === 0) && (n - elmWidth - (elements - bar - 1) >= elements - bar - 1)) {
  9437. subVal -= RSSUtils.combins(n - elmWidth - (elements - bar), elements - bar - 2);
  9438. }
  9439. if (elements - bar - 1 > 1) {
  9440. let lessVal = 0;
  9441. for (let mxwElement = n - elmWidth - (elements - bar - 2); mxwElement > maxWidth; mxwElement--) {
  9442. lessVal += RSSUtils.combins(n - elmWidth - mxwElement - 1, elements - bar - 3);
  9443. }
  9444. subVal -= lessVal * (elements - 1 - bar);
  9445. }
  9446. else if (n - elmWidth > maxWidth) {
  9447. subVal--;
  9448. }
  9449. val += subVal;
  9450. }
  9451. n -= elmWidth;
  9452. }
  9453. return val;
  9454. }
  9455. static combins(n, r) {
  9456. let maxDenom;
  9457. let minDenom;
  9458. if (n - r > r) {
  9459. minDenom = r;
  9460. maxDenom = n - r;
  9461. }
  9462. else {
  9463. minDenom = n - r;
  9464. maxDenom = r;
  9465. }
  9466. let val = 1;
  9467. let j = 1;
  9468. for (let i = n; i > maxDenom; i--) {
  9469. val *= i;
  9470. if (j <= minDenom) {
  9471. val /= j;
  9472. j++;
  9473. }
  9474. }
  9475. while ((j <= minDenom)) {
  9476. val /= j;
  9477. j++;
  9478. }
  9479. return val;
  9480. }
  9481. }
  9482. class BitArrayBuilder {
  9483. static buildBitArray(pairs) {
  9484. let charNumber = pairs.length * 2 - 1;
  9485. if (pairs[pairs.length - 1].getRightChar() == null) {
  9486. charNumber -= 1;
  9487. }
  9488. let size = 12 * charNumber;
  9489. let binary = new BitArray(size);
  9490. let accPos = 0;
  9491. let firstPair = pairs[0];
  9492. let firstValue = firstPair.getRightChar().getValue();
  9493. for (let i = 11; i >= 0; --i) {
  9494. if ((firstValue & (1 << i)) !== 0) {
  9495. binary.set(accPos);
  9496. }
  9497. accPos++;
  9498. }
  9499. for (let i = 1; i < pairs.length; ++i) {
  9500. let currentPair = pairs[i];
  9501. let leftValue = currentPair.getLeftChar().getValue();
  9502. for (let j = 11; j >= 0; --j) {
  9503. if ((leftValue & (1 << j)) !== 0) {
  9504. binary.set(accPos);
  9505. }
  9506. accPos++;
  9507. }
  9508. if (currentPair.getRightChar() !== null) {
  9509. let rightValue = currentPair.getRightChar().getValue();
  9510. for (let j = 11; j >= 0; --j) {
  9511. if ((rightValue & (1 << j)) !== 0) {
  9512. binary.set(accPos);
  9513. }
  9514. accPos++;
  9515. }
  9516. }
  9517. }
  9518. return binary;
  9519. }
  9520. }
  9521. class BlockParsedResult {
  9522. constructor(finished, decodedInformation) {
  9523. if (decodedInformation) {
  9524. this.decodedInformation = null;
  9525. }
  9526. else {
  9527. this.finished = finished;
  9528. this.decodedInformation = decodedInformation;
  9529. }
  9530. }
  9531. getDecodedInformation() {
  9532. return this.decodedInformation;
  9533. }
  9534. isFinished() {
  9535. return this.finished;
  9536. }
  9537. }
  9538. class DecodedObject {
  9539. constructor(newPosition) {
  9540. this.newPosition = newPosition;
  9541. }
  9542. getNewPosition() {
  9543. return this.newPosition;
  9544. }
  9545. }
  9546. class DecodedChar extends DecodedObject {
  9547. constructor(newPosition, value) {
  9548. super(newPosition);
  9549. this.value = value;
  9550. }
  9551. getValue() {
  9552. return this.value;
  9553. }
  9554. isFNC1() {
  9555. return this.value === DecodedChar.FNC1;
  9556. }
  9557. }
  9558. DecodedChar.FNC1 = '$';
  9559. class DecodedInformation extends DecodedObject {
  9560. constructor(newPosition, newString, remainingValue) {
  9561. super(newPosition);
  9562. if (remainingValue) {
  9563. this.remaining = true;
  9564. this.remainingValue = this.remainingValue;
  9565. }
  9566. else {
  9567. this.remaining = false;
  9568. this.remainingValue = 0;
  9569. }
  9570. this.newString = newString;
  9571. }
  9572. getNewString() {
  9573. return this.newString;
  9574. }
  9575. isRemaining() {
  9576. return this.remaining;
  9577. }
  9578. getRemainingValue() {
  9579. return this.remainingValue;
  9580. }
  9581. }
  9582. class DecodedNumeric extends DecodedObject {
  9583. constructor(newPosition, firstDigit, secondDigit) {
  9584. super(newPosition);
  9585. if (firstDigit < 0 || firstDigit > 10 || secondDigit < 0 || secondDigit > 10) {
  9586. throw new FormatException();
  9587. }
  9588. this.firstDigit = firstDigit;
  9589. this.secondDigit = secondDigit;
  9590. }
  9591. getFirstDigit() {
  9592. return this.firstDigit;
  9593. }
  9594. getSecondDigit() {
  9595. return this.secondDigit;
  9596. }
  9597. getValue() {
  9598. return this.firstDigit * 10 + this.secondDigit;
  9599. }
  9600. isFirstDigitFNC1() {
  9601. return this.firstDigit === DecodedNumeric.FNC1;
  9602. }
  9603. isSecondDigitFNC1() {
  9604. return this.secondDigit === DecodedNumeric.FNC1;
  9605. }
  9606. isAnyFNC1() {
  9607. return this.firstDigit === DecodedNumeric.FNC1 || this.secondDigit === DecodedNumeric.FNC1;
  9608. }
  9609. }
  9610. DecodedNumeric.FNC1 = 10;
  9611. class FieldParser {
  9612. constructor() {
  9613. }
  9614. static parseFieldsInGeneralPurpose(rawInformation) {
  9615. if (!rawInformation) {
  9616. return null;
  9617. }
  9618. // Processing 2-digit AIs
  9619. if (rawInformation.length < 2) {
  9620. throw new NotFoundException();
  9621. }
  9622. let firstTwoDigits = rawInformation.substring(0, 2);
  9623. for (let dataLength of FieldParser.TWO_DIGIT_DATA_LENGTH) {
  9624. if (dataLength[0] === firstTwoDigits) {
  9625. if (dataLength[1] === FieldParser.VARIABLE_LENGTH) {
  9626. return FieldParser.processVariableAI(2, dataLength[2], rawInformation);
  9627. }
  9628. return FieldParser.processFixedAI(2, dataLength[1], rawInformation);
  9629. }
  9630. }
  9631. if (rawInformation.length < 3) {
  9632. throw new NotFoundException();
  9633. }
  9634. let firstThreeDigits = rawInformation.substring(0, 3);
  9635. for (let dataLength of FieldParser.THREE_DIGIT_DATA_LENGTH) {
  9636. if (dataLength[0] === firstThreeDigits) {
  9637. if (dataLength[1] === FieldParser.VARIABLE_LENGTH) {
  9638. return FieldParser.processVariableAI(3, dataLength[2], rawInformation);
  9639. }
  9640. return FieldParser.processFixedAI(3, dataLength[1], rawInformation);
  9641. }
  9642. }
  9643. for (let dataLength of FieldParser.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH) {
  9644. if (dataLength[0] === firstThreeDigits) {
  9645. if (dataLength[1] === FieldParser.VARIABLE_LENGTH) {
  9646. return FieldParser.processVariableAI(4, dataLength[2], rawInformation);
  9647. }
  9648. return FieldParser.processFixedAI(4, dataLength[1], rawInformation);
  9649. }
  9650. }
  9651. if (rawInformation.length < 4) {
  9652. throw new NotFoundException();
  9653. }
  9654. let firstFourDigits = rawInformation.substring(0, 4);
  9655. for (let dataLength of FieldParser.FOUR_DIGIT_DATA_LENGTH) {
  9656. if (dataLength[0] === firstFourDigits) {
  9657. if (dataLength[1] === FieldParser.VARIABLE_LENGTH) {
  9658. return FieldParser.processVariableAI(4, dataLength[2], rawInformation);
  9659. }
  9660. return FieldParser.processFixedAI(4, dataLength[1], rawInformation);
  9661. }
  9662. }
  9663. throw new NotFoundException();
  9664. }
  9665. static processFixedAI(aiSize, fieldSize, rawInformation) {
  9666. if (rawInformation.length < aiSize) {
  9667. throw new NotFoundException();
  9668. }
  9669. let ai = rawInformation.substring(0, aiSize);
  9670. if (rawInformation.length < aiSize + fieldSize) {
  9671. throw new NotFoundException();
  9672. }
  9673. let field = rawInformation.substring(aiSize, aiSize + fieldSize);
  9674. let remaining = rawInformation.substring(aiSize + fieldSize);
  9675. let result = '(' + ai + ')' + field;
  9676. let parsedAI = FieldParser.parseFieldsInGeneralPurpose(remaining);
  9677. return parsedAI == null ? result : result + parsedAI;
  9678. }
  9679. static processVariableAI(aiSize, variableFieldSize, rawInformation) {
  9680. let ai = rawInformation.substring(0, aiSize);
  9681. let maxSize;
  9682. if (rawInformation.length < aiSize + variableFieldSize) {
  9683. maxSize = rawInformation.length;
  9684. }
  9685. else {
  9686. maxSize = aiSize + variableFieldSize;
  9687. }
  9688. let field = rawInformation.substring(aiSize, maxSize);
  9689. let remaining = rawInformation.substring(maxSize);
  9690. let result = '(' + ai + ')' + field;
  9691. let parsedAI = FieldParser.parseFieldsInGeneralPurpose(remaining);
  9692. return parsedAI == null ? result : result + parsedAI;
  9693. }
  9694. }
  9695. FieldParser.VARIABLE_LENGTH = [];
  9696. FieldParser.TWO_DIGIT_DATA_LENGTH = [
  9697. ['00', 18],
  9698. ['01', 14],
  9699. ['02', 14],
  9700. ['10', FieldParser.VARIABLE_LENGTH, 20],
  9701. ['11', 6],
  9702. ['12', 6],
  9703. ['13', 6],
  9704. ['15', 6],
  9705. ['17', 6],
  9706. ['20', 2],
  9707. ['21', FieldParser.VARIABLE_LENGTH, 20],
  9708. ['22', FieldParser.VARIABLE_LENGTH, 29],
  9709. ['30', FieldParser.VARIABLE_LENGTH, 8],
  9710. ['37', FieldParser.VARIABLE_LENGTH, 8],
  9711. // internal company codes
  9712. ['90', FieldParser.VARIABLE_LENGTH, 30],
  9713. ['91', FieldParser.VARIABLE_LENGTH, 30],
  9714. ['92', FieldParser.VARIABLE_LENGTH, 30],
  9715. ['93', FieldParser.VARIABLE_LENGTH, 30],
  9716. ['94', FieldParser.VARIABLE_LENGTH, 30],
  9717. ['95', FieldParser.VARIABLE_LENGTH, 30],
  9718. ['96', FieldParser.VARIABLE_LENGTH, 30],
  9719. ['97', FieldParser.VARIABLE_LENGTH, 3],
  9720. ['98', FieldParser.VARIABLE_LENGTH, 30],
  9721. ['99', FieldParser.VARIABLE_LENGTH, 30],
  9722. ];
  9723. FieldParser.THREE_DIGIT_DATA_LENGTH = [
  9724. // Same format as above
  9725. ['240', FieldParser.VARIABLE_LENGTH, 30],
  9726. ['241', FieldParser.VARIABLE_LENGTH, 30],
  9727. ['242', FieldParser.VARIABLE_LENGTH, 6],
  9728. ['250', FieldParser.VARIABLE_LENGTH, 30],
  9729. ['251', FieldParser.VARIABLE_LENGTH, 30],
  9730. ['253', FieldParser.VARIABLE_LENGTH, 17],
  9731. ['254', FieldParser.VARIABLE_LENGTH, 20],
  9732. ['400', FieldParser.VARIABLE_LENGTH, 30],
  9733. ['401', FieldParser.VARIABLE_LENGTH, 30],
  9734. ['402', 17],
  9735. ['403', FieldParser.VARIABLE_LENGTH, 30],
  9736. ['410', 13],
  9737. ['411', 13],
  9738. ['412', 13],
  9739. ['413', 13],
  9740. ['414', 13],
  9741. ['420', FieldParser.VARIABLE_LENGTH, 20],
  9742. ['421', FieldParser.VARIABLE_LENGTH, 15],
  9743. ['422', 3],
  9744. ['423', FieldParser.VARIABLE_LENGTH, 15],
  9745. ['424', 3],
  9746. ['425', 3],
  9747. ['426', 3],
  9748. ];
  9749. FieldParser.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH = [
  9750. // Same format as above
  9751. ['310', 6],
  9752. ['311', 6],
  9753. ['312', 6],
  9754. ['313', 6],
  9755. ['314', 6],
  9756. ['315', 6],
  9757. ['316', 6],
  9758. ['320', 6],
  9759. ['321', 6],
  9760. ['322', 6],
  9761. ['323', 6],
  9762. ['324', 6],
  9763. ['325', 6],
  9764. ['326', 6],
  9765. ['327', 6],
  9766. ['328', 6],
  9767. ['329', 6],
  9768. ['330', 6],
  9769. ['331', 6],
  9770. ['332', 6],
  9771. ['333', 6],
  9772. ['334', 6],
  9773. ['335', 6],
  9774. ['336', 6],
  9775. ['340', 6],
  9776. ['341', 6],
  9777. ['342', 6],
  9778. ['343', 6],
  9779. ['344', 6],
  9780. ['345', 6],
  9781. ['346', 6],
  9782. ['347', 6],
  9783. ['348', 6],
  9784. ['349', 6],
  9785. ['350', 6],
  9786. ['351', 6],
  9787. ['352', 6],
  9788. ['353', 6],
  9789. ['354', 6],
  9790. ['355', 6],
  9791. ['356', 6],
  9792. ['357', 6],
  9793. ['360', 6],
  9794. ['361', 6],
  9795. ['362', 6],
  9796. ['363', 6],
  9797. ['364', 6],
  9798. ['365', 6],
  9799. ['366', 6],
  9800. ['367', 6],
  9801. ['368', 6],
  9802. ['369', 6],
  9803. ['390', FieldParser.VARIABLE_LENGTH, 15],
  9804. ['391', FieldParser.VARIABLE_LENGTH, 18],
  9805. ['392', FieldParser.VARIABLE_LENGTH, 15],
  9806. ['393', FieldParser.VARIABLE_LENGTH, 18],
  9807. ['703', FieldParser.VARIABLE_LENGTH, 30],
  9808. ];
  9809. FieldParser.FOUR_DIGIT_DATA_LENGTH = [
  9810. // Same format as above
  9811. ['7001', 13],
  9812. ['7002', FieldParser.VARIABLE_LENGTH, 30],
  9813. ['7003', 10],
  9814. ['8001', 14],
  9815. ['8002', FieldParser.VARIABLE_LENGTH, 20],
  9816. ['8003', FieldParser.VARIABLE_LENGTH, 30],
  9817. ['8004', FieldParser.VARIABLE_LENGTH, 30],
  9818. ['8005', 6],
  9819. ['8006', 18],
  9820. ['8007', FieldParser.VARIABLE_LENGTH, 30],
  9821. ['8008', FieldParser.VARIABLE_LENGTH, 12],
  9822. ['8018', 18],
  9823. ['8020', FieldParser.VARIABLE_LENGTH, 25],
  9824. ['8100', 6],
  9825. ['8101', 10],
  9826. ['8102', 2],
  9827. ['8110', FieldParser.VARIABLE_LENGTH, 70],
  9828. ['8200', FieldParser.VARIABLE_LENGTH, 70],
  9829. ];
  9830. class GeneralAppIdDecoder {
  9831. constructor(information) {
  9832. this.buffer = new StringBuilder();
  9833. this.information = information;
  9834. }
  9835. decodeAllCodes(buff, initialPosition) {
  9836. let currentPosition = initialPosition;
  9837. let remaining = null;
  9838. do {
  9839. let info = this.decodeGeneralPurposeField(currentPosition, remaining);
  9840. let parsedFields = FieldParser.parseFieldsInGeneralPurpose(info.getNewString());
  9841. if (parsedFields != null) {
  9842. buff.append(parsedFields);
  9843. }
  9844. if (info.isRemaining()) {
  9845. remaining = '' + info.getRemainingValue();
  9846. }
  9847. else {
  9848. remaining = null;
  9849. }
  9850. if (currentPosition === info.getNewPosition()) { // No step forward!
  9851. break;
  9852. }
  9853. currentPosition = info.getNewPosition();
  9854. } while (true);
  9855. return buff.toString();
  9856. }
  9857. isStillNumeric(pos) {
  9858. // It's numeric if it still has 7 positions
  9859. // and one of the first 4 bits is "1".
  9860. if (pos + 7 > this.information.getSize()) {
  9861. return pos + 4 <= this.information.getSize();
  9862. }
  9863. for (let i = pos; i < pos + 3; ++i) {
  9864. if (this.information.get(i)) {
  9865. return true;
  9866. }
  9867. }
  9868. return this.information.get(pos + 3);
  9869. }
  9870. decodeNumeric(pos) {
  9871. if (pos + 7 > this.information.getSize()) {
  9872. let numeric = this.extractNumericValueFromBitArray(pos, 4);
  9873. if (numeric === 0) {
  9874. return new DecodedNumeric(this.information.getSize(), DecodedNumeric.FNC1, DecodedNumeric.FNC1);
  9875. }
  9876. return new DecodedNumeric(this.information.getSize(), numeric - 1, DecodedNumeric.FNC1);
  9877. }
  9878. let numeric = this.extractNumericValueFromBitArray(pos, 7);
  9879. let digit1 = (numeric - 8) / 11;
  9880. let digit2 = (numeric - 8) % 11;
  9881. return new DecodedNumeric(pos + 7, digit1, digit2);
  9882. }
  9883. extractNumericValueFromBitArray(pos, bits) {
  9884. return GeneralAppIdDecoder.extractNumericValueFromBitArray(this.information, pos, bits);
  9885. }
  9886. static extractNumericValueFromBitArray(information, pos, bits) {
  9887. let value = 0;
  9888. for (let i = 0; i < bits; ++i) {
  9889. if (information.get(pos + i)) {
  9890. value |= 1 << (bits - i - 1);
  9891. }
  9892. }
  9893. return value;
  9894. }
  9895. decodeGeneralPurposeField(pos, remaining) {
  9896. // this.buffer.setLength(0);
  9897. this.buffer.setLengthToZero();
  9898. if (remaining != null) {
  9899. this.buffer.append(remaining);
  9900. }
  9901. this.current.setPosition(pos);
  9902. let lastDecoded = this.parseBlocks();
  9903. if (lastDecoded != null && lastDecoded.isRemaining()) {
  9904. return new DecodedInformation(this.current.getPosition(), this.buffer.toString(), lastDecoded.getRemainingValue());
  9905. }
  9906. return new DecodedInformation(this.current.getPosition(), this.buffer.toString());
  9907. }
  9908. parseBlocks() {
  9909. let isFinished;
  9910. let result;
  9911. do {
  9912. let initialPosition = this.current.getPosition();
  9913. if (this.current.isAlpha()) {
  9914. result = this.parseAlphaBlock();
  9915. isFinished = result.isFinished();
  9916. }
  9917. else if (this.current.isIsoIec646()) {
  9918. result = this.parseIsoIec646Block();
  9919. isFinished = result.isFinished();
  9920. }
  9921. else { // it must be numeric
  9922. result = this.parseNumericBlock();
  9923. isFinished = result.isFinished();
  9924. }
  9925. let positionChanged = initialPosition !== this.current.getPosition();
  9926. if (!positionChanged && !isFinished) {
  9927. break;
  9928. }
  9929. } while (!isFinished);
  9930. return result.getDecodedInformation();
  9931. }
  9932. parseNumericBlock() {
  9933. while (this.isStillNumeric(this.current.getPosition())) {
  9934. let numeric = this.decodeNumeric(this.current.getPosition());
  9935. this.current.setPosition(numeric.getNewPosition());
  9936. if (numeric.isFirstDigitFNC1()) {
  9937. let information;
  9938. if (numeric.isSecondDigitFNC1()) {
  9939. information = new DecodedInformation(this.current.getPosition(), this.buffer.toString());
  9940. }
  9941. else {
  9942. information = new DecodedInformation(this.current.getPosition(), this.buffer.toString(), numeric.getSecondDigit());
  9943. }
  9944. return new BlockParsedResult(true, information);
  9945. }
  9946. this.buffer.append(numeric.getFirstDigit());
  9947. if (numeric.isSecondDigitFNC1()) {
  9948. let information = new DecodedInformation(this.current.getPosition(), this.buffer.toString());
  9949. return new BlockParsedResult(true, information);
  9950. }
  9951. this.buffer.append(numeric.getSecondDigit());
  9952. }
  9953. if (this.isNumericToAlphaNumericLatch(this.current.getPosition())) {
  9954. this.current.setAlpha();
  9955. this.current.incrementPosition(4);
  9956. }
  9957. return new BlockParsedResult(false);
  9958. }
  9959. parseIsoIec646Block() {
  9960. while (this.isStillIsoIec646(this.current.getPosition())) {
  9961. let iso = this.decodeIsoIec646(this.current.getPosition());
  9962. this.current.setPosition(iso.getNewPosition());
  9963. if (iso.isFNC1()) {
  9964. let information = new DecodedInformation(this.current.getPosition(), this.buffer.toString());
  9965. return new BlockParsedResult(true, information);
  9966. }
  9967. this.buffer.append(iso.getValue());
  9968. }
  9969. if (this.isAlphaOr646ToNumericLatch(this.current.getPosition())) {
  9970. this.current.incrementPosition(3);
  9971. this.current.setNumeric();
  9972. }
  9973. else if (this.isAlphaTo646ToAlphaLatch(this.current.getPosition())) {
  9974. if (this.current.getPosition() + 5 < this.information.getSize()) {
  9975. this.current.incrementPosition(5);
  9976. }
  9977. else {
  9978. this.current.setPosition(this.information.getSize());
  9979. }
  9980. this.current.setAlpha();
  9981. }
  9982. return new BlockParsedResult(false);
  9983. }
  9984. parseAlphaBlock() {
  9985. while (this.isStillAlpha(this.current.getPosition())) {
  9986. let alpha = this.decodeAlphanumeric(this.current.getPosition());
  9987. this.current.setPosition(alpha.getNewPosition());
  9988. if (alpha.isFNC1()) {
  9989. let information = new DecodedInformation(this.current.getPosition(), this.buffer.toString());
  9990. return new BlockParsedResult(true, information); // end of the char block
  9991. }
  9992. this.buffer.append(alpha.getValue());
  9993. }
  9994. if (this.isAlphaOr646ToNumericLatch(this.current.getPosition())) {
  9995. this.current.incrementPosition(3);
  9996. this.current.setNumeric();
  9997. }
  9998. else if (this.isAlphaTo646ToAlphaLatch(this.current.getPosition())) {
  9999. if (this.current.getPosition() + 5 < this.information.getSize()) {
  10000. this.current.incrementPosition(5);
  10001. }
  10002. else {
  10003. this.current.setPosition(this.information.getSize());
  10004. }
  10005. this.current.setIsoIec646();
  10006. }
  10007. return new BlockParsedResult(false);
  10008. }
  10009. isStillIsoIec646(pos) {
  10010. if (pos + 5 > this.information.getSize()) {
  10011. return false;
  10012. }
  10013. let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5);
  10014. if (fiveBitValue >= 5 && fiveBitValue < 16) {
  10015. return true;
  10016. }
  10017. if (pos + 7 > this.information.getSize()) {
  10018. return false;
  10019. }
  10020. let sevenBitValue = this.extractNumericValueFromBitArray(pos, 7);
  10021. if (sevenBitValue >= 64 && sevenBitValue < 116) {
  10022. return true;
  10023. }
  10024. if (pos + 8 > this.information.getSize()) {
  10025. return false;
  10026. }
  10027. let eightBitValue = this.extractNumericValueFromBitArray(pos, 8);
  10028. return eightBitValue >= 232 && eightBitValue < 253;
  10029. }
  10030. decodeIsoIec646(pos) {
  10031. let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5);
  10032. if (fiveBitValue === 15) {
  10033. return new DecodedChar(pos + 5, DecodedChar.FNC1);
  10034. }
  10035. if (fiveBitValue >= 5 && fiveBitValue < 15) {
  10036. return new DecodedChar(pos + 5, ('0' + (fiveBitValue - 5)));
  10037. }
  10038. let sevenBitValue = this.extractNumericValueFromBitArray(pos, 7);
  10039. if (sevenBitValue >= 64 && sevenBitValue < 90) {
  10040. return new DecodedChar(pos + 7, ('' + (sevenBitValue + 1)));
  10041. }
  10042. if (sevenBitValue >= 90 && sevenBitValue < 116) {
  10043. return new DecodedChar(pos + 7, ('' + (sevenBitValue + 7)));
  10044. }
  10045. let eightBitValue = this.extractNumericValueFromBitArray(pos, 8);
  10046. let c;
  10047. switch (eightBitValue) {
  10048. case 232:
  10049. c = '!';
  10050. break;
  10051. case 233:
  10052. c = '"';
  10053. break;
  10054. case 234:
  10055. c = '%';
  10056. break;
  10057. case 235:
  10058. c = '&';
  10059. break;
  10060. case 236:
  10061. c = '\'';
  10062. break;
  10063. case 237:
  10064. c = '(';
  10065. break;
  10066. case 238:
  10067. c = ')';
  10068. break;
  10069. case 239:
  10070. c = '*';
  10071. break;
  10072. case 240:
  10073. c = '+';
  10074. break;
  10075. case 241:
  10076. c = ',';
  10077. break;
  10078. case 242:
  10079. c = '-';
  10080. break;
  10081. case 243:
  10082. c = '.';
  10083. break;
  10084. case 244:
  10085. c = '/';
  10086. break;
  10087. case 245:
  10088. c = ':';
  10089. break;
  10090. case 246:
  10091. c = ';';
  10092. break;
  10093. case 247:
  10094. c = '<';
  10095. break;
  10096. case 248:
  10097. c = '=';
  10098. break;
  10099. case 249:
  10100. c = '>';
  10101. break;
  10102. case 250:
  10103. c = '?';
  10104. break;
  10105. case 251:
  10106. c = '_';
  10107. break;
  10108. case 252:
  10109. c = ' ';
  10110. break;
  10111. default:
  10112. throw new FormatException();
  10113. }
  10114. return new DecodedChar(pos + 8, c);
  10115. }
  10116. isStillAlpha(pos) {
  10117. if (pos + 5 > this.information.getSize()) {
  10118. return false;
  10119. }
  10120. // We now check if it's a valid 5-bit value (0..9 and FNC1)
  10121. let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5);
  10122. if (fiveBitValue >= 5 && fiveBitValue < 16) {
  10123. return true;
  10124. }
  10125. if (pos + 6 > this.information.getSize()) {
  10126. return false;
  10127. }
  10128. let sixBitValue = this.extractNumericValueFromBitArray(pos, 6);
  10129. return sixBitValue >= 16 && sixBitValue < 63; // 63 not included
  10130. }
  10131. decodeAlphanumeric(pos) {
  10132. let fiveBitValue = this.extractNumericValueFromBitArray(pos, 5);
  10133. if (fiveBitValue === 15) {
  10134. return new DecodedChar(pos + 5, DecodedChar.FNC1);
  10135. }
  10136. if (fiveBitValue >= 5 && fiveBitValue < 15) {
  10137. return new DecodedChar(pos + 5, ('0' + (fiveBitValue - 5)));
  10138. }
  10139. let sixBitValue = this.extractNumericValueFromBitArray(pos, 6);
  10140. if (sixBitValue >= 32 && sixBitValue < 58) {
  10141. return new DecodedChar(pos + 6, ('' + (sixBitValue + 33)));
  10142. }
  10143. let c;
  10144. switch (sixBitValue) {
  10145. case 58:
  10146. c = '*';
  10147. break;
  10148. case 59:
  10149. c = ',';
  10150. break;
  10151. case 60:
  10152. c = '-';
  10153. break;
  10154. case 61:
  10155. c = '.';
  10156. break;
  10157. case 62:
  10158. c = '/';
  10159. break;
  10160. default:
  10161. throw new IllegalStateException('Decoding invalid alphanumeric value: ' + sixBitValue);
  10162. }
  10163. return new DecodedChar(pos + 6, c);
  10164. }
  10165. isAlphaTo646ToAlphaLatch(pos) {
  10166. if (pos + 1 > this.information.getSize()) {
  10167. return false;
  10168. }
  10169. for (let i = 0; i < 5 && i + pos < this.information.getSize(); ++i) {
  10170. if (i === 2) {
  10171. if (!this.information.get(pos + 2)) {
  10172. return false;
  10173. }
  10174. }
  10175. else if (this.information.get(pos + i)) {
  10176. return false;
  10177. }
  10178. }
  10179. return true;
  10180. }
  10181. isAlphaOr646ToNumericLatch(pos) {
  10182. // Next is alphanumeric if there are 3 positions and they are all zeros
  10183. if (pos + 3 > this.information.getSize()) {
  10184. return false;
  10185. }
  10186. for (let i = pos; i < pos + 3; ++i) {
  10187. if (this.information.get(i)) {
  10188. return false;
  10189. }
  10190. }
  10191. return true;
  10192. }
  10193. isNumericToAlphaNumericLatch(pos) {
  10194. // Next is alphanumeric if there are 4 positions and they are all zeros, or
  10195. // if there is a subset of this just before the end of the symbol
  10196. if (pos + 1 > this.information.getSize()) {
  10197. return false;
  10198. }
  10199. for (let i = 0; i < 4 && i + pos < this.information.getSize(); ++i) {
  10200. if (this.information.get(pos + i)) {
  10201. return false;
  10202. }
  10203. }
  10204. return true;
  10205. }
  10206. }
  10207. class AbstractExpandedDecoder {
  10208. constructor(information) {
  10209. this.information = information;
  10210. this.generalDecoder = new GeneralAppIdDecoder(information);
  10211. }
  10212. getInformation() {
  10213. return this.information;
  10214. }
  10215. getGeneralDecoder() {
  10216. return this.generalDecoder;
  10217. }
  10218. }
  10219. class AI01decoder extends AbstractExpandedDecoder {
  10220. constructor(information) {
  10221. super(information);
  10222. }
  10223. encodeCompressedGtin(buf, currentPos) {
  10224. buf.append('(01)');
  10225. let initialPosition = buf.length();
  10226. buf.append('9');
  10227. this.encodeCompressedGtinWithoutAI(buf, currentPos, initialPosition);
  10228. }
  10229. encodeCompressedGtinWithoutAI(buf, currentPos, initialBufferPosition) {
  10230. for (let i = 0; i < 4; ++i) {
  10231. let currentBlock = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos + 10 * i, 10);
  10232. if (currentBlock / 100 === 0) {
  10233. buf.append('0');
  10234. }
  10235. if (currentBlock / 10 === 0) {
  10236. buf.append('0');
  10237. }
  10238. buf.append(currentBlock);
  10239. }
  10240. AI01decoder.appendCheckDigit(buf, initialBufferPosition);
  10241. }
  10242. static appendCheckDigit(buf, currentPos) {
  10243. let checkDigit = 0;
  10244. for (let i = 0; i < 13; i++) {
  10245. // let digit = buf.charAt(i + currentPos) - '0';
  10246. // To be checked
  10247. let digit = buf.charAt(i + currentPos).charCodeAt(0) - '0'.charCodeAt(0);
  10248. checkDigit += (i & 0x01) === 0 ? 3 * digit : digit;
  10249. }
  10250. checkDigit = 10 - (checkDigit % 10);
  10251. if (checkDigit === 10) {
  10252. checkDigit = 0;
  10253. }
  10254. buf.append(checkDigit);
  10255. }
  10256. }
  10257. AI01decoder.GTIN_SIZE = 40;
  10258. class AI01AndOtherAIs extends AI01decoder {
  10259. // the second one is the encodation method, and the other two are for the variable length
  10260. constructor(information) {
  10261. super(information);
  10262. }
  10263. parseInformation() {
  10264. let buff = new StringBuilder();
  10265. buff.append('(01)');
  10266. let initialGtinPosition = buff.length();
  10267. let firstGtinDigit = this.getGeneralDecoder().extractNumericValueFromBitArray(AI01AndOtherAIs.HEADER_SIZE, 4);
  10268. buff.append(firstGtinDigit);
  10269. this.encodeCompressedGtinWithoutAI(buff, AI01AndOtherAIs.HEADER_SIZE + 4, initialGtinPosition);
  10270. return this.getGeneralDecoder().decodeAllCodes(buff, AI01AndOtherAIs.HEADER_SIZE + 44);
  10271. }
  10272. }
  10273. AI01AndOtherAIs.HEADER_SIZE = 1 + 1 + 2; // first bit encodes the linkage flag,
  10274. class AnyAIDecoder extends AbstractExpandedDecoder {
  10275. constructor(information) {
  10276. super(information);
  10277. }
  10278. parseInformation() {
  10279. let buf = new StringBuilder();
  10280. return this.getGeneralDecoder().decodeAllCodes(buf, AnyAIDecoder.HEADER_SIZE);
  10281. }
  10282. }
  10283. AnyAIDecoder.HEADER_SIZE = 2 + 1 + 2;
  10284. class AI01weightDecoder extends AI01decoder {
  10285. constructor(information) {
  10286. super(information);
  10287. }
  10288. encodeCompressedWeight(buf, currentPos, weightSize) {
  10289. let originalWeightNumeric = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos, weightSize);
  10290. this.addWeightCode(buf, originalWeightNumeric);
  10291. let weightNumeric = this.checkWeight(originalWeightNumeric);
  10292. let currentDivisor = 100000;
  10293. for (let i = 0; i < 5; ++i) {
  10294. if (weightNumeric / currentDivisor === 0) {
  10295. buf.append('0');
  10296. }
  10297. currentDivisor /= 10;
  10298. }
  10299. buf.append(weightNumeric);
  10300. }
  10301. }
  10302. class AI013x0xDecoder extends AI01weightDecoder {
  10303. constructor(information) {
  10304. super(information);
  10305. }
  10306. parseInformation() {
  10307. if (this.getInformation().getSize() !==
  10308. AI013x0xDecoder.HEADER_SIZE +
  10309. AI01weightDecoder.GTIN_SIZE +
  10310. AI013x0xDecoder.WEIGHT_SIZE) {
  10311. throw new NotFoundException();
  10312. }
  10313. let buf = new StringBuilder();
  10314. this.encodeCompressedGtin(buf, AI013x0xDecoder.HEADER_SIZE);
  10315. this.encodeCompressedWeight(buf, AI013x0xDecoder.HEADER_SIZE + AI01weightDecoder.GTIN_SIZE, AI013x0xDecoder.WEIGHT_SIZE);
  10316. return buf.toString();
  10317. }
  10318. }
  10319. AI013x0xDecoder.HEADER_SIZE = 4 + 1;
  10320. AI013x0xDecoder.WEIGHT_SIZE = 15;
  10321. class AI013103decoder extends AI013x0xDecoder {
  10322. constructor(information) {
  10323. super(information);
  10324. }
  10325. addWeightCode(buf, weight) {
  10326. buf.append('(3103)');
  10327. }
  10328. checkWeight(weight) {
  10329. return weight;
  10330. }
  10331. }
  10332. class AI01320xDecoder extends AI013x0xDecoder {
  10333. constructor(information) {
  10334. super(information);
  10335. }
  10336. addWeightCode(buf, weight) {
  10337. if (weight < 10000) {
  10338. buf.append('(3202)');
  10339. }
  10340. else {
  10341. buf.append('(3203)');
  10342. }
  10343. }
  10344. checkWeight(weight) {
  10345. if (weight < 10000) {
  10346. return weight;
  10347. }
  10348. return weight - 10000;
  10349. }
  10350. }
  10351. class AI01392xDecoder extends AI01decoder {
  10352. constructor(information) {
  10353. super(information);
  10354. }
  10355. parseInformation() {
  10356. if (this.getInformation().getSize() < AI01392xDecoder.HEADER_SIZE + AI01decoder.GTIN_SIZE) {
  10357. throw new NotFoundException();
  10358. }
  10359. let buf = new StringBuilder();
  10360. this.encodeCompressedGtin(buf, AI01392xDecoder.HEADER_SIZE);
  10361. let lastAIdigit = this.getGeneralDecoder().extractNumericValueFromBitArray(AI01392xDecoder.HEADER_SIZE + AI01decoder.GTIN_SIZE, AI01392xDecoder.LAST_DIGIT_SIZE);
  10362. buf.append('(392');
  10363. buf.append(lastAIdigit);
  10364. buf.append(')');
  10365. let decodedInformation = this.getGeneralDecoder().decodeGeneralPurposeField(AI01392xDecoder.HEADER_SIZE + AI01decoder.GTIN_SIZE + AI01392xDecoder.LAST_DIGIT_SIZE, null);
  10366. buf.append(decodedInformation.getNewString());
  10367. return buf.toString();
  10368. }
  10369. }
  10370. AI01392xDecoder.HEADER_SIZE = 5 + 1 + 2;
  10371. AI01392xDecoder.LAST_DIGIT_SIZE = 2;
  10372. class AI01393xDecoder extends AI01decoder {
  10373. constructor(information) {
  10374. super(information);
  10375. }
  10376. parseInformation() {
  10377. if (this.getInformation().getSize() <
  10378. AI01393xDecoder.HEADER_SIZE + AI01decoder.GTIN_SIZE) {
  10379. throw new NotFoundException();
  10380. }
  10381. let buf = new StringBuilder();
  10382. this.encodeCompressedGtin(buf, AI01393xDecoder.HEADER_SIZE);
  10383. let lastAIdigit = this.getGeneralDecoder().extractNumericValueFromBitArray(AI01393xDecoder.HEADER_SIZE + AI01decoder.GTIN_SIZE, AI01393xDecoder.LAST_DIGIT_SIZE);
  10384. buf.append('(393');
  10385. buf.append(lastAIdigit);
  10386. buf.append(')');
  10387. let firstThreeDigits = this.getGeneralDecoder().extractNumericValueFromBitArray(AI01393xDecoder.HEADER_SIZE +
  10388. AI01decoder.GTIN_SIZE +
  10389. AI01393xDecoder.LAST_DIGIT_SIZE, AI01393xDecoder.FIRST_THREE_DIGITS_SIZE);
  10390. if (firstThreeDigits / 100 === 0) {
  10391. buf.append('0');
  10392. }
  10393. if (firstThreeDigits / 10 === 0) {
  10394. buf.append('0');
  10395. }
  10396. buf.append(firstThreeDigits);
  10397. let generalInformation = this.getGeneralDecoder().decodeGeneralPurposeField(AI01393xDecoder.HEADER_SIZE +
  10398. AI01decoder.GTIN_SIZE +
  10399. AI01393xDecoder.LAST_DIGIT_SIZE +
  10400. AI01393xDecoder.FIRST_THREE_DIGITS_SIZE, null);
  10401. buf.append(generalInformation.getNewString());
  10402. return buf.toString();
  10403. }
  10404. }
  10405. AI01393xDecoder.HEADER_SIZE = 5 + 1 + 2;
  10406. AI01393xDecoder.LAST_DIGIT_SIZE = 2;
  10407. AI01393xDecoder.FIRST_THREE_DIGITS_SIZE = 10;
  10408. class AI013x0x1xDecoder extends AI01weightDecoder {
  10409. constructor(information, firstAIdigits, dateCode) {
  10410. super(information);
  10411. this.dateCode = dateCode;
  10412. this.firstAIdigits = firstAIdigits;
  10413. }
  10414. parseInformation() {
  10415. if (this.getInformation().getSize() !==
  10416. AI013x0x1xDecoder.HEADER_SIZE +
  10417. AI013x0x1xDecoder.GTIN_SIZE +
  10418. AI013x0x1xDecoder.WEIGHT_SIZE +
  10419. AI013x0x1xDecoder.DATE_SIZE) {
  10420. throw new NotFoundException();
  10421. }
  10422. let buf = new StringBuilder();
  10423. this.encodeCompressedGtin(buf, AI013x0x1xDecoder.HEADER_SIZE);
  10424. this.encodeCompressedWeight(buf, AI013x0x1xDecoder.HEADER_SIZE + AI013x0x1xDecoder.GTIN_SIZE, AI013x0x1xDecoder.WEIGHT_SIZE);
  10425. this.encodeCompressedDate(buf, AI013x0x1xDecoder.HEADER_SIZE +
  10426. AI013x0x1xDecoder.GTIN_SIZE +
  10427. AI013x0x1xDecoder.WEIGHT_SIZE);
  10428. return buf.toString();
  10429. }
  10430. encodeCompressedDate(buf, currentPos) {
  10431. let numericDate = this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos, AI013x0x1xDecoder.DATE_SIZE);
  10432. if (numericDate === 38400) {
  10433. return;
  10434. }
  10435. buf.append('(');
  10436. buf.append(this.dateCode);
  10437. buf.append(')');
  10438. let day = numericDate % 32;
  10439. numericDate /= 32;
  10440. let month = (numericDate % 12) + 1;
  10441. numericDate /= 12;
  10442. let year = numericDate;
  10443. if (year / 10 === 0) {
  10444. buf.append('0');
  10445. }
  10446. buf.append(year);
  10447. if (month / 10 === 0) {
  10448. buf.append('0');
  10449. }
  10450. buf.append(month);
  10451. if (day / 10 === 0) {
  10452. buf.append('0');
  10453. }
  10454. buf.append(day);
  10455. }
  10456. addWeightCode(buf, weight) {
  10457. buf.append('(');
  10458. buf.append(this.firstAIdigits);
  10459. buf.append(weight / 100000);
  10460. buf.append(')');
  10461. }
  10462. checkWeight(weight) {
  10463. return weight % 100000;
  10464. }
  10465. }
  10466. AI013x0x1xDecoder.HEADER_SIZE = 7 + 1;
  10467. AI013x0x1xDecoder.WEIGHT_SIZE = 20;
  10468. AI013x0x1xDecoder.DATE_SIZE = 16;
  10469. function createDecoder(information) {
  10470. try {
  10471. if (information.get(1)) {
  10472. return new AI01AndOtherAIs(information);
  10473. }
  10474. if (!information.get(2)) {
  10475. return new AnyAIDecoder(information);
  10476. }
  10477. let fourBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 4);
  10478. switch (fourBitEncodationMethod) {
  10479. case 4: return new AI013103decoder(information);
  10480. case 5: return new AI01320xDecoder(information);
  10481. }
  10482. let fiveBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 5);
  10483. switch (fiveBitEncodationMethod) {
  10484. case 12: return new AI01392xDecoder(information);
  10485. case 13: return new AI01393xDecoder(information);
  10486. }
  10487. let sevenBitEncodationMethod = GeneralAppIdDecoder.extractNumericValueFromBitArray(information, 1, 7);
  10488. switch (sevenBitEncodationMethod) {
  10489. case 56: return new AI013x0x1xDecoder(information, '310', '11');
  10490. case 57: return new AI013x0x1xDecoder(information, '320', '11');
  10491. case 58: return new AI013x0x1xDecoder(information, '310', '13');
  10492. case 59: return new AI013x0x1xDecoder(information, '320', '13');
  10493. case 60: return new AI013x0x1xDecoder(information, '310', '15');
  10494. case 61: return new AI013x0x1xDecoder(information, '320', '15');
  10495. case 62: return new AI013x0x1xDecoder(information, '310', '17');
  10496. case 63: return new AI013x0x1xDecoder(information, '320', '17');
  10497. }
  10498. }
  10499. catch (e) {
  10500. console.log(e);
  10501. throw new IllegalStateException('unknown decoder: ' + information);
  10502. }
  10503. }
  10504. class ExpandedPair {
  10505. constructor(leftChar, rightChar, finderPatter, mayBeLast) {
  10506. this.leftchar = leftChar;
  10507. this.rightchar = rightChar;
  10508. this.finderpattern = finderPatter;
  10509. this.maybeLast = mayBeLast;
  10510. }
  10511. mayBeLast() {
  10512. return this.maybeLast;
  10513. }
  10514. getLeftChar() {
  10515. return this.leftchar;
  10516. }
  10517. getRightChar() {
  10518. return this.rightchar;
  10519. }
  10520. getFinderPattern() {
  10521. return this.finderpattern;
  10522. }
  10523. mustBeLast() {
  10524. return this.rightchar == null;
  10525. }
  10526. toString() {
  10527. return '[ ' + this.leftchar + ', ' + this.rightchar + ' : ' + (this.finderpattern == null ? 'null' : this.finderpattern.getValue()) + ' ]';
  10528. }
  10529. static equals(o1, o2) {
  10530. if (!(o1 instanceof ExpandedPair)) {
  10531. return false;
  10532. }
  10533. return ExpandedPair.equalsOrNull(o1.leftchar, o2.leftchar) &&
  10534. ExpandedPair.equalsOrNull(o1.rightchar, o2.rightchar) &&
  10535. ExpandedPair.equalsOrNull(o1.finderpattern, o2.finderpattern);
  10536. }
  10537. static equalsOrNull(o1, o2) {
  10538. return o1 === null ? o2 === null : ExpandedPair.equals(o1, o2);
  10539. }
  10540. hashCode() {
  10541. // return ExpandedPair.hashNotNull(leftChar) ^ hashNotNull(rightChar) ^ hashNotNull(finderPattern);
  10542. let value = this.leftchar.getValue() ^ this.rightchar.getValue() ^ this.finderpattern.getValue();
  10543. return value;
  10544. }
  10545. }
  10546. class ExpandedRow {
  10547. constructor(pairs, rowNumber, wasReversed) {
  10548. this.pairs = pairs;
  10549. this.rowNumber = rowNumber;
  10550. this.wasReversed = wasReversed;
  10551. }
  10552. getPairs() {
  10553. return this.pairs;
  10554. }
  10555. getRowNumber() {
  10556. return this.rowNumber;
  10557. }
  10558. isReversed() {
  10559. return this.wasReversed;
  10560. }
  10561. // check implementation
  10562. isEquivalent(otherPairs) {
  10563. return this.checkEqualitity(this, otherPairs);
  10564. }
  10565. // @Override
  10566. toString() {
  10567. return '{ ' + this.pairs + ' }';
  10568. }
  10569. /**
  10570. * Two rows are equal if they contain the same pairs in the same order.
  10571. */
  10572. // @Override
  10573. // check implementation
  10574. equals(o1, o2) {
  10575. if (!(o1 instanceof ExpandedRow)) {
  10576. return false;
  10577. }
  10578. return this.checkEqualitity(o1, o2) && o1.wasReversed === o2.wasReversed;
  10579. }
  10580. checkEqualitity(pair1, pair2) {
  10581. if (!pair1 || !pair2)
  10582. return;
  10583. let result;
  10584. pair1.forEach((e1, i) => {
  10585. pair2.forEach(e2 => {
  10586. if (e1.getLeftChar().getValue() === e2.getLeftChar().getValue() && e1.getRightChar().getValue() === e2.getRightChar().getValue() && e1.getFinderPatter().getValue() === e2.getFinderPatter().getValue()) {
  10587. result = true;
  10588. }
  10589. });
  10590. });
  10591. return result;
  10592. }
  10593. }
  10594. // import java.util.ArrayList;
  10595. // import java.util.Iterator;
  10596. // import java.util.List;
  10597. // import java.util.Map;
  10598. // import java.util.Collections;
  10599. /** @experimental */
  10600. class RSSExpandedReader extends AbstractRSSReader {
  10601. constructor() {
  10602. super(...arguments);
  10603. this.pairs = new Array(RSSExpandedReader.MAX_PAIRS);
  10604. this.rows = new Array();
  10605. this.startEnd = [2];
  10606. }
  10607. decodeRow(rowNumber, row, hints) {
  10608. // Rows can start with even pattern in case in prev rows there where odd number of patters.
  10609. // So lets try twice
  10610. // this.pairs.clear();
  10611. this.pairs.length = 0;
  10612. this.startFromEven = false;
  10613. try {
  10614. return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber, row));
  10615. }
  10616. catch (e) {
  10617. // OK
  10618. // console.log(e);
  10619. }
  10620. this.pairs.length = 0;
  10621. this.startFromEven = true;
  10622. return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber, row));
  10623. }
  10624. reset() {
  10625. this.pairs.length = 0;
  10626. this.rows.length = 0;
  10627. }
  10628. // Not private for testing
  10629. decodeRow2pairs(rowNumber, row) {
  10630. let done = false;
  10631. while (!done) {
  10632. try {
  10633. this.pairs.push(this.retrieveNextPair(row, this.pairs, rowNumber));
  10634. }
  10635. catch (error) {
  10636. if (error instanceof NotFoundException) {
  10637. if (!this.pairs.length) {
  10638. throw new NotFoundException();
  10639. }
  10640. // exit this loop when retrieveNextPair() fails and throws
  10641. done = true;
  10642. }
  10643. }
  10644. }
  10645. // TODO: verify sequence of finder patterns as in checkPairSequence()
  10646. if (this.checkChecksum()) {
  10647. return this.pairs;
  10648. }
  10649. let tryStackedDecode;
  10650. if (this.rows.length) {
  10651. tryStackedDecode = true;
  10652. }
  10653. else {
  10654. tryStackedDecode = false;
  10655. }
  10656. // let tryStackedDecode = !this.rows.isEmpty();
  10657. this.storeRow(rowNumber, false); // TODO: deal with reversed rows
  10658. if (tryStackedDecode) {
  10659. // When the image is 180-rotated, then rows are sorted in wrong direction.
  10660. // Try twice with both the directions.
  10661. let ps = this.checkRowsBoolean(false);
  10662. if (ps != null) {
  10663. return ps;
  10664. }
  10665. ps = this.checkRowsBoolean(true);
  10666. if (ps != null) {
  10667. return ps;
  10668. }
  10669. }
  10670. throw new NotFoundException();
  10671. }
  10672. // Need to Verify
  10673. checkRowsBoolean(reverse) {
  10674. // Limit number of rows we are checking
  10675. // We use recursive algorithm with pure complexity and don't want it to take forever
  10676. // Stacked barcode can have up to 11 rows, so 25 seems reasonable enough
  10677. if (this.rows.length > 25) {
  10678. this.rows.length = 0; // We will never have a chance to get result, so clear it
  10679. return null;
  10680. }
  10681. this.pairs.length = 0;
  10682. if (reverse) {
  10683. this.rows = this.rows.reverse();
  10684. // Collections.reverse(this.rows);
  10685. }
  10686. let ps = null;
  10687. try {
  10688. ps = this.checkRows(new Array(), 0);
  10689. }
  10690. catch (e) {
  10691. // OK
  10692. console.log(e);
  10693. }
  10694. if (reverse) {
  10695. this.rows = this.rows.reverse();
  10696. // Collections.reverse(this.rows);
  10697. }
  10698. return ps;
  10699. }
  10700. // Try to construct a valid rows sequence
  10701. // Recursion is used to implement backtracking
  10702. checkRows(collectedRows, currentRow) {
  10703. for (let i = currentRow; i < this.rows.length; i++) {
  10704. let row = this.rows[i];
  10705. this.pairs.length = 0;
  10706. for (let collectedRow of collectedRows) {
  10707. this.pairs.push(collectedRow.getPairs());
  10708. }
  10709. this.pairs.push(row.getPairs());
  10710. if (!RSSExpandedReader.isValidSequence(this.pairs)) {
  10711. continue;
  10712. }
  10713. if (this.checkChecksum()) {
  10714. return this.pairs;
  10715. }
  10716. let rs = new Array(collectedRows);
  10717. rs.push(row);
  10718. try {
  10719. // Recursion: try to add more rows
  10720. return this.checkRows(rs, i + 1);
  10721. }
  10722. catch (e) {
  10723. // We failed, try the next candidate
  10724. console.log(e);
  10725. }
  10726. }
  10727. throw new NotFoundException();
  10728. }
  10729. // Whether the pairs form a valid find pattern sequence,
  10730. // either complete or a prefix
  10731. static isValidSequence(pairs) {
  10732. for (let sequence of RSSExpandedReader.FINDER_PATTERN_SEQUENCES) {
  10733. if (pairs.length > sequence.length) {
  10734. continue;
  10735. }
  10736. let stop = true;
  10737. for (let j = 0; j < pairs.length; j++) {
  10738. if (pairs[j].getFinderPattern().getValue() !== sequence[j]) {
  10739. stop = false;
  10740. break;
  10741. }
  10742. }
  10743. if (stop) {
  10744. return true;
  10745. }
  10746. }
  10747. return false;
  10748. }
  10749. storeRow(rowNumber, wasReversed) {
  10750. // Discard if duplicate above or below; otherwise insert in order by row number.
  10751. let insertPos = 0;
  10752. let prevIsSame = false;
  10753. let nextIsSame = false;
  10754. while (insertPos < this.rows.length) {
  10755. let erow = this.rows[insertPos];
  10756. if (erow.getRowNumber() > rowNumber) {
  10757. nextIsSame = erow.isEquivalent(this.pairs);
  10758. break;
  10759. }
  10760. prevIsSame = erow.isEquivalent(this.pairs);
  10761. insertPos++;
  10762. }
  10763. if (nextIsSame || prevIsSame) {
  10764. return;
  10765. }
  10766. // When the row was partially decoded (e.g. 2 pairs found instead of 3),
  10767. // it will prevent us from detecting the barcode.
  10768. // Try to merge partial rows
  10769. // Check whether the row is part of an allready detected row
  10770. if (RSSExpandedReader.isPartialRow(this.pairs, this.rows)) {
  10771. return;
  10772. }
  10773. this.rows.push(insertPos, new ExpandedRow(this.pairs, rowNumber, wasReversed));
  10774. this.removePartialRows(this.pairs, this.rows);
  10775. }
  10776. // Remove all the rows that contains only specified pairs
  10777. removePartialRows(pairs, rows) {
  10778. // for (Iterator<ExpandedRow> iterator = rows.iterator(); iterator.hasNext();) {
  10779. // ExpandedRow r = iterator.next();
  10780. // if (r.getPairs().size() == pairs.size()) {
  10781. // continue;
  10782. // }
  10783. // boolean allFound = true;
  10784. // for (ExpandedPair p : r.getPairs()) {
  10785. // boolean found = false;
  10786. // for (ExpandedPair pp : pairs) {
  10787. // if (p.equals(pp)) {
  10788. // found = true;
  10789. // break;
  10790. // }
  10791. // }
  10792. // if (!found) {
  10793. // allFound = false;
  10794. // break;
  10795. // }
  10796. // }
  10797. // if (allFound) {
  10798. // // 'pairs' contains all the pairs from the row 'r'
  10799. // iterator.remove();
  10800. // }
  10801. // }
  10802. for (let row of rows) {
  10803. if (row.getPairs().length === pairs.length) {
  10804. continue;
  10805. }
  10806. for (let p of row.getPairs()) {
  10807. for (let pp of pairs) {
  10808. if (ExpandedPair.equals(p, pp)) {
  10809. break;
  10810. }
  10811. }
  10812. }
  10813. }
  10814. }
  10815. // Returns true when one of the rows already contains all the pairs
  10816. static isPartialRow(pairs, rows) {
  10817. for (let r of rows) {
  10818. let allFound = true;
  10819. for (let p of pairs) {
  10820. let found = false;
  10821. for (let pp of r.getPairs()) {
  10822. if (p.equals(pp)) {
  10823. found = true;
  10824. break;
  10825. }
  10826. }
  10827. if (!found) {
  10828. allFound = false;
  10829. break;
  10830. }
  10831. }
  10832. if (allFound) {
  10833. // the row 'r' contain all the pairs from 'pairs'
  10834. return true;
  10835. }
  10836. }
  10837. return false;
  10838. }
  10839. // Only used for unit testing
  10840. getRows() {
  10841. return this.rows;
  10842. }
  10843. // Not private for unit testing
  10844. static constructResult(pairs) {
  10845. let binary = BitArrayBuilder.buildBitArray(pairs);
  10846. let decoder = createDecoder(binary);
  10847. let resultingString = decoder.parseInformation();
  10848. let firstPoints = pairs[0].getFinderPattern().getResultPoints();
  10849. let lastPoints = pairs[pairs.length - 1]
  10850. .getFinderPattern()
  10851. .getResultPoints();
  10852. let points = [firstPoints[0], firstPoints[1], lastPoints[0], lastPoints[1]];
  10853. return new Result(resultingString, null, null, points, BarcodeFormat$1.RSS_EXPANDED, null);
  10854. }
  10855. checkChecksum() {
  10856. let firstPair = this.pairs.get(0);
  10857. let checkCharacter = firstPair.getLeftChar();
  10858. let firstCharacter = firstPair.getRightChar();
  10859. if (firstCharacter === null) {
  10860. return false;
  10861. }
  10862. let checksum = firstCharacter.getChecksumPortion();
  10863. let s = 2;
  10864. for (let i = 1; i < this.pairs.size(); ++i) {
  10865. let currentPair = this.pairs.get(i);
  10866. checksum += currentPair.getLeftChar().getChecksumPortion();
  10867. s++;
  10868. let currentRightChar = currentPair.getRightChar();
  10869. if (currentRightChar != null) {
  10870. checksum += currentRightChar.getChecksumPortion();
  10871. s++;
  10872. }
  10873. }
  10874. checksum %= 211;
  10875. let checkCharacterValue = 211 * (s - 4) + checksum;
  10876. return checkCharacterValue === checkCharacter.getValue();
  10877. }
  10878. static getNextSecondBar(row, initialPos) {
  10879. let currentPos;
  10880. if (row.get(initialPos)) {
  10881. currentPos = row.getNextUnset(initialPos);
  10882. currentPos = row.getNextSet(currentPos);
  10883. }
  10884. else {
  10885. currentPos = row.getNextSet(initialPos);
  10886. currentPos = row.getNextUnset(currentPos);
  10887. }
  10888. return currentPos;
  10889. }
  10890. // not private for testing
  10891. retrieveNextPair(row, previousPairs, rowNumber) {
  10892. let isOddPattern = previousPairs.length % 2 === 0;
  10893. if (this.startFromEven) {
  10894. isOddPattern = !isOddPattern;
  10895. }
  10896. let pattern;
  10897. let keepFinding = true;
  10898. let forcedOffset = -1;
  10899. do {
  10900. this.findNextPair(row, previousPairs, forcedOffset);
  10901. pattern = this.parseFoundFinderPattern(row, rowNumber, isOddPattern);
  10902. if (pattern === null) {
  10903. forcedOffset = RSSExpandedReader.getNextSecondBar(row, this.startEnd[0]);
  10904. }
  10905. else {
  10906. keepFinding = false;
  10907. }
  10908. } while (keepFinding);
  10909. // When stacked symbol is split over multiple rows, there's no way to guess if this pair can be last or not.
  10910. // boolean mayBeLast = checkPairSequence(previousPairs, pattern);
  10911. let leftChar = this.decodeDataCharacter(row, pattern, isOddPattern, true);
  10912. if (!this.isEmptyPair(previousPairs) &&
  10913. previousPairs[previousPairs.length - 1].mustBeLast()) {
  10914. throw new NotFoundException();
  10915. }
  10916. let rightChar;
  10917. try {
  10918. rightChar = this.decodeDataCharacter(row, pattern, isOddPattern, false);
  10919. }
  10920. catch (e) {
  10921. rightChar = null;
  10922. console.log(e);
  10923. }
  10924. return new ExpandedPair(leftChar, rightChar, pattern, true);
  10925. }
  10926. isEmptyPair(pairs) {
  10927. if (pairs.length === 0) {
  10928. return true;
  10929. }
  10930. return false;
  10931. }
  10932. findNextPair(row, previousPairs, forcedOffset) {
  10933. let counters = this.getDecodeFinderCounters();
  10934. counters[0] = 0;
  10935. counters[1] = 0;
  10936. counters[2] = 0;
  10937. counters[3] = 0;
  10938. let width = row.getSize();
  10939. let rowOffset;
  10940. if (forcedOffset >= 0) {
  10941. rowOffset = forcedOffset;
  10942. }
  10943. else if (this.isEmptyPair(previousPairs)) {
  10944. rowOffset = 0;
  10945. }
  10946. else {
  10947. let lastPair = previousPairs[previousPairs.length - 1];
  10948. rowOffset = lastPair.getFinderPattern().getStartEnd()[1];
  10949. }
  10950. let searchingEvenPair = previousPairs.length % 2 !== 0;
  10951. if (this.startFromEven) {
  10952. searchingEvenPair = !searchingEvenPair;
  10953. }
  10954. let isWhite = false;
  10955. while (rowOffset < width) {
  10956. isWhite = !row.get(rowOffset);
  10957. if (!isWhite) {
  10958. break;
  10959. }
  10960. rowOffset++;
  10961. }
  10962. let counterPosition = 0;
  10963. let patternStart = rowOffset;
  10964. for (let x = rowOffset; x < width; x++) {
  10965. if (row.get(x) !== isWhite) {
  10966. counters[counterPosition]++;
  10967. }
  10968. else {
  10969. if (counterPosition === 3) {
  10970. if (searchingEvenPair) {
  10971. RSSExpandedReader.reverseCounters(counters);
  10972. }
  10973. if (RSSExpandedReader.isFinderPattern(counters)) {
  10974. this.startEnd[0] = patternStart;
  10975. this.startEnd[1] = x;
  10976. return;
  10977. }
  10978. if (searchingEvenPair) {
  10979. RSSExpandedReader.reverseCounters(counters);
  10980. }
  10981. patternStart += counters[0] + counters[1];
  10982. counters[0] = counters[2];
  10983. counters[1] = counters[3];
  10984. counters[2] = 0;
  10985. counters[3] = 0;
  10986. counterPosition--;
  10987. }
  10988. else {
  10989. counterPosition++;
  10990. }
  10991. counters[counterPosition] = 1;
  10992. isWhite = !isWhite;
  10993. }
  10994. }
  10995. throw new NotFoundException();
  10996. }
  10997. static reverseCounters(counters) {
  10998. let length = counters.length;
  10999. for (let i = 0; i < length / 2; ++i) {
  11000. let tmp = counters[i];
  11001. counters[i] = counters[length - i - 1];
  11002. counters[length - i - 1] = tmp;
  11003. }
  11004. }
  11005. parseFoundFinderPattern(row, rowNumber, oddPattern) {
  11006. // Actually we found elements 2-5.
  11007. let firstCounter;
  11008. let start;
  11009. let end;
  11010. if (oddPattern) {
  11011. // If pattern number is odd, we need to locate element 1 *before* the current block.
  11012. let firstElementStart = this.startEnd[0] - 1;
  11013. // Locate element 1
  11014. while (firstElementStart >= 0 && !row.get(firstElementStart)) {
  11015. firstElementStart--;
  11016. }
  11017. firstElementStart++;
  11018. firstCounter = this.startEnd[0] - firstElementStart;
  11019. start = firstElementStart;
  11020. end = this.startEnd[1];
  11021. }
  11022. else {
  11023. // If pattern number is even, the pattern is reversed, so we need to locate element 1 *after* the current block.
  11024. start = this.startEnd[0];
  11025. end = row.getNextUnset(this.startEnd[1] + 1);
  11026. firstCounter = end - this.startEnd[1];
  11027. }
  11028. // Make 'counters' hold 1-4
  11029. let counters = this.getDecodeFinderCounters();
  11030. System.arraycopy(counters, 0, counters, 1, counters.length - 1);
  11031. counters[0] = firstCounter;
  11032. let value;
  11033. try {
  11034. value = this.parseFinderValue(counters, RSSExpandedReader.FINDER_PATTERNS);
  11035. }
  11036. catch (e) {
  11037. return null;
  11038. }
  11039. // return new FinderPattern(value, new int[] { start, end }, start, end, rowNumber});
  11040. return new FinderPattern(value, [start, end], start, end, rowNumber);
  11041. }
  11042. decodeDataCharacter(row, pattern, isOddPattern, leftChar) {
  11043. let counters = this.getDataCharacterCounters();
  11044. for (let x = 0; x < counters.length; x++) {
  11045. counters[x] = 0;
  11046. }
  11047. if (leftChar) {
  11048. RSSExpandedReader.recordPatternInReverse(row, pattern.getStartEnd()[0], counters);
  11049. }
  11050. else {
  11051. RSSExpandedReader.recordPattern(row, pattern.getStartEnd()[1], counters);
  11052. // reverse it
  11053. for (let i = 0, j = counters.length - 1; i < j; i++, j--) {
  11054. let temp = counters[i];
  11055. counters[i] = counters[j];
  11056. counters[j] = temp;
  11057. }
  11058. } // counters[] has the pixels of the module
  11059. let numModules = 17; // left and right data characters have all the same length
  11060. let elementWidth = MathUtils.sum(new Int32Array(counters)) / numModules;
  11061. // Sanity check: element width for pattern and the character should match
  11062. let expectedElementWidth = (pattern.getStartEnd()[1] - pattern.getStartEnd()[0]) / 15.0;
  11063. if (Math.abs(elementWidth - expectedElementWidth) / expectedElementWidth >
  11064. 0.3) {
  11065. throw new NotFoundException();
  11066. }
  11067. let oddCounts = this.getOddCounts();
  11068. let evenCounts = this.getEvenCounts();
  11069. let oddRoundingErrors = this.getOddRoundingErrors();
  11070. let evenRoundingErrors = this.getEvenRoundingErrors();
  11071. for (let i = 0; i < counters.length; i++) {
  11072. let value = (1.0 * counters[i]) / elementWidth;
  11073. let count = value + 0.5; // Round
  11074. if (count < 1) {
  11075. if (value < 0.3) {
  11076. throw new NotFoundException();
  11077. }
  11078. count = 1;
  11079. }
  11080. else if (count > 8) {
  11081. if (value > 8.7) {
  11082. throw new NotFoundException();
  11083. }
  11084. count = 8;
  11085. }
  11086. let offset = i / 2;
  11087. if ((i & 0x01) === 0) {
  11088. oddCounts[offset] = count;
  11089. oddRoundingErrors[offset] = value - count;
  11090. }
  11091. else {
  11092. evenCounts[offset] = count;
  11093. evenRoundingErrors[offset] = value - count;
  11094. }
  11095. }
  11096. this.adjustOddEvenCounts(numModules);
  11097. let weightRowNumber = 4 * pattern.getValue() + (isOddPattern ? 0 : 2) + (leftChar ? 0 : 1) - 1;
  11098. let oddSum = 0;
  11099. let oddChecksumPortion = 0;
  11100. for (let i = oddCounts.length - 1; i >= 0; i--) {
  11101. if (RSSExpandedReader.isNotA1left(pattern, isOddPattern, leftChar)) {
  11102. let weight = RSSExpandedReader.WEIGHTS[weightRowNumber][2 * i];
  11103. oddChecksumPortion += oddCounts[i] * weight;
  11104. }
  11105. oddSum += oddCounts[i];
  11106. }
  11107. let evenChecksumPortion = 0;
  11108. // int evenSum = 0;
  11109. for (let i = evenCounts.length - 1; i >= 0; i--) {
  11110. if (RSSExpandedReader.isNotA1left(pattern, isOddPattern, leftChar)) {
  11111. let weight = RSSExpandedReader.WEIGHTS[weightRowNumber][2 * i + 1];
  11112. evenChecksumPortion += evenCounts[i] * weight;
  11113. }
  11114. // evenSum += evenCounts[i];
  11115. }
  11116. let checksumPortion = oddChecksumPortion + evenChecksumPortion;
  11117. if ((oddSum & 0x01) !== 0 || oddSum > 13 || oddSum < 4) {
  11118. throw new NotFoundException();
  11119. }
  11120. let group = (13 - oddSum) / 2;
  11121. let oddWidest = RSSExpandedReader.SYMBOL_WIDEST[group];
  11122. let evenWidest = 9 - oddWidest;
  11123. let vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, true);
  11124. let vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, false);
  11125. let tEven = RSSExpandedReader.EVEN_TOTAL_SUBSET[group];
  11126. let gSum = RSSExpandedReader.GSUM[group];
  11127. let value = vOdd * tEven + vEven + gSum;
  11128. return new DataCharacter(value, checksumPortion);
  11129. }
  11130. static isNotA1left(pattern, isOddPattern, leftChar) {
  11131. // A1: pattern.getValue is 0 (A), and it's an oddPattern, and it is a left char
  11132. return !(pattern.getValue() === 0 && isOddPattern && leftChar);
  11133. }
  11134. adjustOddEvenCounts(numModules) {
  11135. let oddSum = MathUtils.sum(new Int32Array(this.getOddCounts()));
  11136. let evenSum = MathUtils.sum(new Int32Array(this.getEvenCounts()));
  11137. let incrementOdd = false;
  11138. let decrementOdd = false;
  11139. if (oddSum > 13) {
  11140. decrementOdd = true;
  11141. }
  11142. else if (oddSum < 4) {
  11143. incrementOdd = true;
  11144. }
  11145. let incrementEven = false;
  11146. let decrementEven = false;
  11147. if (evenSum > 13) {
  11148. decrementEven = true;
  11149. }
  11150. else if (evenSum < 4) {
  11151. incrementEven = true;
  11152. }
  11153. let mismatch = oddSum + evenSum - numModules;
  11154. let oddParityBad = (oddSum & 0x01) === 1;
  11155. let evenParityBad = (evenSum & 0x01) === 0;
  11156. if (mismatch === 1) {
  11157. if (oddParityBad) {
  11158. if (evenParityBad) {
  11159. throw new NotFoundException();
  11160. }
  11161. decrementOdd = true;
  11162. }
  11163. else {
  11164. if (!evenParityBad) {
  11165. throw new NotFoundException();
  11166. }
  11167. decrementEven = true;
  11168. }
  11169. }
  11170. else if (mismatch === -1) {
  11171. if (oddParityBad) {
  11172. if (evenParityBad) {
  11173. throw new NotFoundException();
  11174. }
  11175. incrementOdd = true;
  11176. }
  11177. else {
  11178. if (!evenParityBad) {
  11179. throw new NotFoundException();
  11180. }
  11181. incrementEven = true;
  11182. }
  11183. }
  11184. else if (mismatch === 0) {
  11185. if (oddParityBad) {
  11186. if (!evenParityBad) {
  11187. throw new NotFoundException();
  11188. }
  11189. // Both bad
  11190. if (oddSum < evenSum) {
  11191. incrementOdd = true;
  11192. decrementEven = true;
  11193. }
  11194. else {
  11195. decrementOdd = true;
  11196. incrementEven = true;
  11197. }
  11198. }
  11199. else {
  11200. if (evenParityBad) {
  11201. throw new NotFoundException();
  11202. }
  11203. // Nothing to do!
  11204. }
  11205. }
  11206. else {
  11207. throw new NotFoundException();
  11208. }
  11209. if (incrementOdd) {
  11210. if (decrementOdd) {
  11211. throw new NotFoundException();
  11212. }
  11213. RSSExpandedReader.increment(this.getOddCounts(), this.getOddRoundingErrors());
  11214. }
  11215. if (decrementOdd) {
  11216. RSSExpandedReader.decrement(this.getOddCounts(), this.getOddRoundingErrors());
  11217. }
  11218. if (incrementEven) {
  11219. if (decrementEven) {
  11220. throw new NotFoundException();
  11221. }
  11222. RSSExpandedReader.increment(this.getEvenCounts(), this.getOddRoundingErrors());
  11223. }
  11224. if (decrementEven) {
  11225. RSSExpandedReader.decrement(this.getEvenCounts(), this.getEvenRoundingErrors());
  11226. }
  11227. }
  11228. }
  11229. RSSExpandedReader.SYMBOL_WIDEST = [7, 5, 4, 3, 1];
  11230. RSSExpandedReader.EVEN_TOTAL_SUBSET = [4, 20, 52, 104, 204];
  11231. RSSExpandedReader.GSUM = [0, 348, 1388, 2948, 3988];
  11232. RSSExpandedReader.FINDER_PATTERNS = [
  11233. Int32Array.from([1, 8, 4, 1]),
  11234. Int32Array.from([3, 6, 4, 1]),
  11235. Int32Array.from([3, 4, 6, 1]),
  11236. Int32Array.from([3, 2, 8, 1]),
  11237. Int32Array.from([2, 6, 5, 1]),
  11238. Int32Array.from([2, 2, 9, 1]),
  11239. ];
  11240. RSSExpandedReader.WEIGHTS = [
  11241. [1, 3, 9, 27, 81, 32, 96, 77],
  11242. [20, 60, 180, 118, 143, 7, 21, 63],
  11243. [189, 145, 13, 39, 117, 140, 209, 205],
  11244. [193, 157, 49, 147, 19, 57, 171, 91],
  11245. [62, 186, 136, 197, 169, 85, 44, 132],
  11246. [185, 133, 188, 142, 4, 12, 36, 108],
  11247. [113, 128, 173, 97, 80, 29, 87, 50],
  11248. [150, 28, 84, 41, 123, 158, 52, 156],
  11249. [46, 138, 203, 187, 139, 206, 196, 166],
  11250. [76, 17, 51, 153, 37, 111, 122, 155],
  11251. [43, 129, 176, 106, 107, 110, 119, 146],
  11252. [16, 48, 144, 10, 30, 90, 59, 177],
  11253. [109, 116, 137, 200, 178, 112, 125, 164],
  11254. [70, 210, 208, 202, 184, 130, 179, 115],
  11255. [134, 191, 151, 31, 93, 68, 204, 190],
  11256. [148, 22, 66, 198, 172, 94, 71, 2],
  11257. [6, 18, 54, 162, 64, 192, 154, 40],
  11258. [120, 149, 25, 75, 14, 42, 126, 167],
  11259. [79, 26, 78, 23, 69, 207, 199, 175],
  11260. [103, 98, 83, 38, 114, 131, 182, 124],
  11261. [161, 61, 183, 127, 170, 88, 53, 159],
  11262. [55, 165, 73, 8, 24, 72, 5, 15],
  11263. [45, 135, 194, 160, 58, 174, 100, 89],
  11264. ];
  11265. RSSExpandedReader.FINDER_PAT_A = 0;
  11266. RSSExpandedReader.FINDER_PAT_B = 1;
  11267. RSSExpandedReader.FINDER_PAT_C = 2;
  11268. RSSExpandedReader.FINDER_PAT_D = 3;
  11269. RSSExpandedReader.FINDER_PAT_E = 4;
  11270. RSSExpandedReader.FINDER_PAT_F = 5;
  11271. RSSExpandedReader.FINDER_PATTERN_SEQUENCES = [
  11272. [RSSExpandedReader.FINDER_PAT_A, RSSExpandedReader.FINDER_PAT_A],
  11273. [
  11274. RSSExpandedReader.FINDER_PAT_A,
  11275. RSSExpandedReader.FINDER_PAT_B,
  11276. RSSExpandedReader.FINDER_PAT_B,
  11277. ],
  11278. [
  11279. RSSExpandedReader.FINDER_PAT_A,
  11280. RSSExpandedReader.FINDER_PAT_C,
  11281. RSSExpandedReader.FINDER_PAT_B,
  11282. RSSExpandedReader.FINDER_PAT_D,
  11283. ],
  11284. [
  11285. RSSExpandedReader.FINDER_PAT_A,
  11286. RSSExpandedReader.FINDER_PAT_E,
  11287. RSSExpandedReader.FINDER_PAT_B,
  11288. RSSExpandedReader.FINDER_PAT_D,
  11289. RSSExpandedReader.FINDER_PAT_C,
  11290. ],
  11291. [
  11292. RSSExpandedReader.FINDER_PAT_A,
  11293. RSSExpandedReader.FINDER_PAT_E,
  11294. RSSExpandedReader.FINDER_PAT_B,
  11295. RSSExpandedReader.FINDER_PAT_D,
  11296. RSSExpandedReader.FINDER_PAT_D,
  11297. RSSExpandedReader.FINDER_PAT_F,
  11298. ],
  11299. [
  11300. RSSExpandedReader.FINDER_PAT_A,
  11301. RSSExpandedReader.FINDER_PAT_E,
  11302. RSSExpandedReader.FINDER_PAT_B,
  11303. RSSExpandedReader.FINDER_PAT_D,
  11304. RSSExpandedReader.FINDER_PAT_E,
  11305. RSSExpandedReader.FINDER_PAT_F,
  11306. RSSExpandedReader.FINDER_PAT_F,
  11307. ],
  11308. [
  11309. RSSExpandedReader.FINDER_PAT_A,
  11310. RSSExpandedReader.FINDER_PAT_A,
  11311. RSSExpandedReader.FINDER_PAT_B,
  11312. RSSExpandedReader.FINDER_PAT_B,
  11313. RSSExpandedReader.FINDER_PAT_C,
  11314. RSSExpandedReader.FINDER_PAT_C,
  11315. RSSExpandedReader.FINDER_PAT_D,
  11316. RSSExpandedReader.FINDER_PAT_D,
  11317. ],
  11318. [
  11319. RSSExpandedReader.FINDER_PAT_A,
  11320. RSSExpandedReader.FINDER_PAT_A,
  11321. RSSExpandedReader.FINDER_PAT_B,
  11322. RSSExpandedReader.FINDER_PAT_B,
  11323. RSSExpandedReader.FINDER_PAT_C,
  11324. RSSExpandedReader.FINDER_PAT_C,
  11325. RSSExpandedReader.FINDER_PAT_D,
  11326. RSSExpandedReader.FINDER_PAT_E,
  11327. RSSExpandedReader.FINDER_PAT_E,
  11328. ],
  11329. [
  11330. RSSExpandedReader.FINDER_PAT_A,
  11331. RSSExpandedReader.FINDER_PAT_A,
  11332. RSSExpandedReader.FINDER_PAT_B,
  11333. RSSExpandedReader.FINDER_PAT_B,
  11334. RSSExpandedReader.FINDER_PAT_C,
  11335. RSSExpandedReader.FINDER_PAT_C,
  11336. RSSExpandedReader.FINDER_PAT_D,
  11337. RSSExpandedReader.FINDER_PAT_E,
  11338. RSSExpandedReader.FINDER_PAT_F,
  11339. RSSExpandedReader.FINDER_PAT_F,
  11340. ],
  11341. [
  11342. RSSExpandedReader.FINDER_PAT_A,
  11343. RSSExpandedReader.FINDER_PAT_A,
  11344. RSSExpandedReader.FINDER_PAT_B,
  11345. RSSExpandedReader.FINDER_PAT_B,
  11346. RSSExpandedReader.FINDER_PAT_C,
  11347. RSSExpandedReader.FINDER_PAT_D,
  11348. RSSExpandedReader.FINDER_PAT_D,
  11349. RSSExpandedReader.FINDER_PAT_E,
  11350. RSSExpandedReader.FINDER_PAT_E,
  11351. RSSExpandedReader.FINDER_PAT_F,
  11352. RSSExpandedReader.FINDER_PAT_F,
  11353. ],
  11354. ];
  11355. RSSExpandedReader.MAX_PAIRS = 11;
  11356. class Pair extends DataCharacter {
  11357. constructor(value, checksumPortion, finderPattern) {
  11358. super(value, checksumPortion);
  11359. this.count = 0;
  11360. this.finderPattern = finderPattern;
  11361. }
  11362. getFinderPattern() {
  11363. return this.finderPattern;
  11364. }
  11365. getCount() {
  11366. return this.count;
  11367. }
  11368. incrementCount() {
  11369. this.count++;
  11370. }
  11371. }
  11372. class RSS14Reader extends AbstractRSSReader {
  11373. constructor() {
  11374. super(...arguments);
  11375. this.possibleLeftPairs = [];
  11376. this.possibleRightPairs = [];
  11377. }
  11378. decodeRow(rowNumber, row, hints) {
  11379. const leftPair = this.decodePair(row, false, rowNumber, hints);
  11380. RSS14Reader.addOrTally(this.possibleLeftPairs, leftPair);
  11381. row.reverse();
  11382. let rightPair = this.decodePair(row, true, rowNumber, hints);
  11383. RSS14Reader.addOrTally(this.possibleRightPairs, rightPair);
  11384. row.reverse();
  11385. for (let left of this.possibleLeftPairs) {
  11386. if (left.getCount() > 1) {
  11387. for (let right of this.possibleRightPairs) {
  11388. if (right.getCount() > 1 && RSS14Reader.checkChecksum(left, right)) {
  11389. return RSS14Reader.constructResult(left, right);
  11390. }
  11391. }
  11392. }
  11393. }
  11394. throw new NotFoundException();
  11395. }
  11396. static addOrTally(possiblePairs, pair) {
  11397. if (pair == null) {
  11398. return;
  11399. }
  11400. let found = false;
  11401. for (let other of possiblePairs) {
  11402. if (other.getValue() === pair.getValue()) {
  11403. other.incrementCount();
  11404. found = true;
  11405. break;
  11406. }
  11407. }
  11408. if (!found) {
  11409. possiblePairs.push(pair);
  11410. }
  11411. }
  11412. reset() {
  11413. this.possibleLeftPairs.length = 0;
  11414. this.possibleRightPairs.length = 0;
  11415. }
  11416. static constructResult(leftPair, rightPair) {
  11417. let symbolValue = 4537077 * leftPair.getValue() + rightPair.getValue();
  11418. let text = new String(symbolValue).toString();
  11419. let buffer = new StringBuilder();
  11420. for (let i = 13 - text.length; i > 0; i--) {
  11421. buffer.append('0');
  11422. }
  11423. buffer.append(text);
  11424. let checkDigit = 0;
  11425. for (let i = 0; i < 13; i++) {
  11426. let digit = buffer.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);
  11427. checkDigit += ((i & 0x01) === 0) ? 3 * digit : digit;
  11428. }
  11429. checkDigit = 10 - (checkDigit % 10);
  11430. if (checkDigit === 10) {
  11431. checkDigit = 0;
  11432. }
  11433. buffer.append(checkDigit.toString());
  11434. let leftPoints = leftPair.getFinderPattern().getResultPoints();
  11435. let rightPoints = rightPair.getFinderPattern().getResultPoints();
  11436. return new Result(buffer.toString(), null, 0, [leftPoints[0], leftPoints[1], rightPoints[0], rightPoints[1]], BarcodeFormat$1.RSS_14, new Date().getTime());
  11437. }
  11438. static checkChecksum(leftPair, rightPair) {
  11439. let checkValue = (leftPair.getChecksumPortion() + 16 * rightPair.getChecksumPortion()) % 79;
  11440. let targetCheckValue = 9 * leftPair.getFinderPattern().getValue() + rightPair.getFinderPattern().getValue();
  11441. if (targetCheckValue > 72) {
  11442. targetCheckValue--;
  11443. }
  11444. if (targetCheckValue > 8) {
  11445. targetCheckValue--;
  11446. }
  11447. return checkValue === targetCheckValue;
  11448. }
  11449. decodePair(row, right, rowNumber, hints) {
  11450. try {
  11451. let startEnd = this.findFinderPattern(row, right);
  11452. let pattern = this.parseFoundFinderPattern(row, rowNumber, right, startEnd);
  11453. let resultPointCallback = hints == null ? null : hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);
  11454. if (resultPointCallback != null) {
  11455. let center = (startEnd[0] + startEnd[1]) / 2.0;
  11456. if (right) {
  11457. // row is actually reversed
  11458. center = row.getSize() - 1 - center;
  11459. }
  11460. resultPointCallback.foundPossibleResultPoint(new ResultPoint(center, rowNumber));
  11461. }
  11462. let outside = this.decodeDataCharacter(row, pattern, true);
  11463. let inside = this.decodeDataCharacter(row, pattern, false);
  11464. return new Pair(1597 * outside.getValue() + inside.getValue(), outside.getChecksumPortion() + 4 * inside.getChecksumPortion(), pattern);
  11465. }
  11466. catch (err) {
  11467. return null;
  11468. }
  11469. }
  11470. decodeDataCharacter(row, pattern, outsideChar) {
  11471. let counters = this.getDataCharacterCounters();
  11472. for (let x = 0; x < counters.length; x++) {
  11473. counters[x] = 0;
  11474. }
  11475. if (outsideChar) {
  11476. OneDReader.recordPatternInReverse(row, pattern.getStartEnd()[0], counters);
  11477. }
  11478. else {
  11479. OneDReader.recordPattern(row, pattern.getStartEnd()[1] + 1, counters);
  11480. // reverse it
  11481. for (let i = 0, j = counters.length - 1; i < j; i++, j--) {
  11482. let temp = counters[i];
  11483. counters[i] = counters[j];
  11484. counters[j] = temp;
  11485. }
  11486. }
  11487. let numModules = outsideChar ? 16 : 15;
  11488. let elementWidth = MathUtils.sum(new Int32Array(counters)) / numModules;
  11489. let oddCounts = this.getOddCounts();
  11490. let evenCounts = this.getEvenCounts();
  11491. let oddRoundingErrors = this.getOddRoundingErrors();
  11492. let evenRoundingErrors = this.getEvenRoundingErrors();
  11493. for (let i = 0; i < counters.length; i++) {
  11494. let value = counters[i] / elementWidth;
  11495. let count = Math.floor(value + 0.5);
  11496. if (count < 1) {
  11497. count = 1;
  11498. }
  11499. else if (count > 8) {
  11500. count = 8;
  11501. }
  11502. let offset = Math.floor(i / 2);
  11503. if ((i & 0x01) === 0) {
  11504. oddCounts[offset] = count;
  11505. oddRoundingErrors[offset] = value - count;
  11506. }
  11507. else {
  11508. evenCounts[offset] = count;
  11509. evenRoundingErrors[offset] = value - count;
  11510. }
  11511. }
  11512. this.adjustOddEvenCounts(outsideChar, numModules);
  11513. let oddSum = 0;
  11514. let oddChecksumPortion = 0;
  11515. for (let i = oddCounts.length - 1; i >= 0; i--) {
  11516. oddChecksumPortion *= 9;
  11517. oddChecksumPortion += oddCounts[i];
  11518. oddSum += oddCounts[i];
  11519. }
  11520. let evenChecksumPortion = 0;
  11521. let evenSum = 0;
  11522. for (let i = evenCounts.length - 1; i >= 0; i--) {
  11523. evenChecksumPortion *= 9;
  11524. evenChecksumPortion += evenCounts[i];
  11525. evenSum += evenCounts[i];
  11526. }
  11527. let checksumPortion = oddChecksumPortion + 3 * evenChecksumPortion;
  11528. if (outsideChar) {
  11529. if ((oddSum & 0x01) !== 0 || oddSum > 12 || oddSum < 4) {
  11530. throw new NotFoundException();
  11531. }
  11532. let group = (12 - oddSum) / 2;
  11533. let oddWidest = RSS14Reader.OUTSIDE_ODD_WIDEST[group];
  11534. let evenWidest = 9 - oddWidest;
  11535. let vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, false);
  11536. let vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, true);
  11537. let tEven = RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET[group];
  11538. let gSum = RSS14Reader.OUTSIDE_GSUM[group];
  11539. return new DataCharacter(vOdd * tEven + vEven + gSum, checksumPortion);
  11540. }
  11541. else {
  11542. if ((evenSum & 0x01) !== 0 || evenSum > 10 || evenSum < 4) {
  11543. throw new NotFoundException();
  11544. }
  11545. let group = (10 - evenSum) / 2;
  11546. let oddWidest = RSS14Reader.INSIDE_ODD_WIDEST[group];
  11547. let evenWidest = 9 - oddWidest;
  11548. let vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, true);
  11549. let vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, false);
  11550. let tOdd = RSS14Reader.INSIDE_ODD_TOTAL_SUBSET[group];
  11551. let gSum = RSS14Reader.INSIDE_GSUM[group];
  11552. return new DataCharacter(vEven * tOdd + vOdd + gSum, checksumPortion);
  11553. }
  11554. }
  11555. findFinderPattern(row, rightFinderPattern) {
  11556. let counters = this.getDecodeFinderCounters();
  11557. counters[0] = 0;
  11558. counters[1] = 0;
  11559. counters[2] = 0;
  11560. counters[3] = 0;
  11561. let width = row.getSize();
  11562. let isWhite = false;
  11563. let rowOffset = 0;
  11564. while (rowOffset < width) {
  11565. isWhite = !row.get(rowOffset);
  11566. if (rightFinderPattern === isWhite) {
  11567. // Will encounter white first when searching for right finder pattern
  11568. break;
  11569. }
  11570. rowOffset++;
  11571. }
  11572. let counterPosition = 0;
  11573. let patternStart = rowOffset;
  11574. for (let x = rowOffset; x < width; x++) {
  11575. if (row.get(x) !== isWhite) {
  11576. counters[counterPosition]++;
  11577. }
  11578. else {
  11579. if (counterPosition === 3) {
  11580. if (AbstractRSSReader.isFinderPattern(counters)) {
  11581. return [patternStart, x];
  11582. }
  11583. patternStart += counters[0] + counters[1];
  11584. counters[0] = counters[2];
  11585. counters[1] = counters[3];
  11586. counters[2] = 0;
  11587. counters[3] = 0;
  11588. counterPosition--;
  11589. }
  11590. else {
  11591. counterPosition++;
  11592. }
  11593. counters[counterPosition] = 1;
  11594. isWhite = !isWhite;
  11595. }
  11596. }
  11597. throw new NotFoundException();
  11598. }
  11599. parseFoundFinderPattern(row, rowNumber, right, startEnd) {
  11600. // Actually we found elements 2-5
  11601. let firstIsBlack = row.get(startEnd[0]);
  11602. let firstElementStart = startEnd[0] - 1;
  11603. // Locate element 1
  11604. while (firstElementStart >= 0 && firstIsBlack !== row.get(firstElementStart)) {
  11605. firstElementStart--;
  11606. }
  11607. firstElementStart++;
  11608. const firstCounter = startEnd[0] - firstElementStart;
  11609. // Make 'counters' hold 1-4
  11610. const counters = this.getDecodeFinderCounters();
  11611. const copy = new Int32Array(counters.length);
  11612. System.arraycopy(counters, 0, copy, 1, counters.length - 1);
  11613. copy[0] = firstCounter;
  11614. const value = this.parseFinderValue(copy, RSS14Reader.FINDER_PATTERNS);
  11615. let start = firstElementStart;
  11616. let end = startEnd[1];
  11617. if (right) {
  11618. // row is actually reversed
  11619. start = row.getSize() - 1 - start;
  11620. end = row.getSize() - 1 - end;
  11621. }
  11622. return new FinderPattern(value, [firstElementStart, startEnd[1]], start, end, rowNumber);
  11623. }
  11624. adjustOddEvenCounts(outsideChar, numModules) {
  11625. let oddSum = MathUtils.sum(new Int32Array(this.getOddCounts()));
  11626. let evenSum = MathUtils.sum(new Int32Array(this.getEvenCounts()));
  11627. let incrementOdd = false;
  11628. let decrementOdd = false;
  11629. let incrementEven = false;
  11630. let decrementEven = false;
  11631. if (outsideChar) {
  11632. if (oddSum > 12) {
  11633. decrementOdd = true;
  11634. }
  11635. else if (oddSum < 4) {
  11636. incrementOdd = true;
  11637. }
  11638. if (evenSum > 12) {
  11639. decrementEven = true;
  11640. }
  11641. else if (evenSum < 4) {
  11642. incrementEven = true;
  11643. }
  11644. }
  11645. else {
  11646. if (oddSum > 11) {
  11647. decrementOdd = true;
  11648. }
  11649. else if (oddSum < 5) {
  11650. incrementOdd = true;
  11651. }
  11652. if (evenSum > 10) {
  11653. decrementEven = true;
  11654. }
  11655. else if (evenSum < 4) {
  11656. incrementEven = true;
  11657. }
  11658. }
  11659. let mismatch = oddSum + evenSum - numModules;
  11660. let oddParityBad = (oddSum & 0x01) === (outsideChar ? 1 : 0);
  11661. let evenParityBad = (evenSum & 0x01) === 1;
  11662. if (mismatch === 1) {
  11663. if (oddParityBad) {
  11664. if (evenParityBad) {
  11665. throw new NotFoundException();
  11666. }
  11667. decrementOdd = true;
  11668. }
  11669. else {
  11670. if (!evenParityBad) {
  11671. throw new NotFoundException();
  11672. }
  11673. decrementEven = true;
  11674. }
  11675. }
  11676. else if (mismatch === -1) {
  11677. if (oddParityBad) {
  11678. if (evenParityBad) {
  11679. throw new NotFoundException();
  11680. }
  11681. incrementOdd = true;
  11682. }
  11683. else {
  11684. if (!evenParityBad) {
  11685. throw new NotFoundException();
  11686. }
  11687. incrementEven = true;
  11688. }
  11689. }
  11690. else if (mismatch === 0) {
  11691. if (oddParityBad) {
  11692. if (!evenParityBad) {
  11693. throw new NotFoundException();
  11694. }
  11695. // Both bad
  11696. if (oddSum < evenSum) {
  11697. incrementOdd = true;
  11698. decrementEven = true;
  11699. }
  11700. else {
  11701. decrementOdd = true;
  11702. incrementEven = true;
  11703. }
  11704. }
  11705. else {
  11706. if (evenParityBad) {
  11707. throw new NotFoundException();
  11708. }
  11709. // Nothing to do!
  11710. }
  11711. }
  11712. else {
  11713. throw new NotFoundException();
  11714. }
  11715. if (incrementOdd) {
  11716. if (decrementOdd) {
  11717. throw new NotFoundException();
  11718. }
  11719. AbstractRSSReader.increment(this.getOddCounts(), this.getOddRoundingErrors());
  11720. }
  11721. if (decrementOdd) {
  11722. AbstractRSSReader.decrement(this.getOddCounts(), this.getOddRoundingErrors());
  11723. }
  11724. if (incrementEven) {
  11725. if (decrementEven) {
  11726. throw new NotFoundException();
  11727. }
  11728. AbstractRSSReader.increment(this.getEvenCounts(), this.getOddRoundingErrors());
  11729. }
  11730. if (decrementEven) {
  11731. AbstractRSSReader.decrement(this.getEvenCounts(), this.getEvenRoundingErrors());
  11732. }
  11733. }
  11734. }
  11735. RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET = [1, 10, 34, 70, 126];
  11736. RSS14Reader.INSIDE_ODD_TOTAL_SUBSET = [4, 20, 48, 81];
  11737. RSS14Reader.OUTSIDE_GSUM = [0, 161, 961, 2015, 2715];
  11738. RSS14Reader.INSIDE_GSUM = [0, 336, 1036, 1516];
  11739. RSS14Reader.OUTSIDE_ODD_WIDEST = [8, 6, 4, 3, 1];
  11740. RSS14Reader.INSIDE_ODD_WIDEST = [2, 4, 6, 8];
  11741. RSS14Reader.FINDER_PATTERNS = [
  11742. Int32Array.from([3, 8, 2, 1]),
  11743. Int32Array.from([3, 5, 5, 1]),
  11744. Int32Array.from([3, 3, 7, 1]),
  11745. Int32Array.from([3, 1, 9, 1]),
  11746. Int32Array.from([2, 7, 4, 1]),
  11747. Int32Array.from([2, 5, 6, 1]),
  11748. Int32Array.from([2, 3, 8, 1]),
  11749. Int32Array.from([1, 5, 7, 1]),
  11750. Int32Array.from([1, 3, 9, 1]),
  11751. ];
  11752. /*
  11753. * Copyright 2008 ZXing authors
  11754. *
  11755. * Licensed under the Apache License, Version 2.0 (the "License");
  11756. * you may not use this file except in compliance with the License.
  11757. * You may obtain a copy of the License at
  11758. *
  11759. * http://www.apache.org/licenses/LICENSE-2.0
  11760. *
  11761. * Unless required by applicable law or agreed to in writing, software
  11762. * distributed under the License is distributed on an "AS IS" BASIS,
  11763. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11764. * See the License for the specific language governing permissions and
  11765. * limitations under the License.
  11766. */
  11767. /**
  11768. * @author Daniel Switkin <dswitkin@google.com>
  11769. * @author Sean Owen
  11770. */
  11771. class MultiFormatOneDReader extends OneDReader {
  11772. constructor(hints) {
  11773. super();
  11774. this.readers = [];
  11775. const possibleFormats = !hints ? null : hints.get(DecodeHintType$1.POSSIBLE_FORMATS);
  11776. const useCode39CheckDigit = hints && hints.get(DecodeHintType$1.ASSUME_CODE_39_CHECK_DIGIT) !== undefined;
  11777. if (possibleFormats) {
  11778. if (possibleFormats.includes(BarcodeFormat$1.EAN_13) ||
  11779. possibleFormats.includes(BarcodeFormat$1.UPC_A) ||
  11780. possibleFormats.includes(BarcodeFormat$1.EAN_8) ||
  11781. possibleFormats.includes(BarcodeFormat$1.UPC_E)) {
  11782. this.readers.push(new MultiFormatUPCEANReader(hints));
  11783. }
  11784. if (possibleFormats.includes(BarcodeFormat$1.CODE_39)) {
  11785. this.readers.push(new Code39Reader(useCode39CheckDigit));
  11786. }
  11787. if (possibleFormats.includes(BarcodeFormat$1.CODE_93)) {
  11788. this.readers.push(new Code93Reader());
  11789. }
  11790. if (possibleFormats.includes(BarcodeFormat$1.CODE_128)) {
  11791. this.readers.push(new Code128Reader());
  11792. }
  11793. if (possibleFormats.includes(BarcodeFormat$1.ITF)) {
  11794. this.readers.push(new ITFReader());
  11795. }
  11796. if (possibleFormats.includes(BarcodeFormat$1.CODABAR)) {
  11797. this.readers.push(new CodaBarReader());
  11798. }
  11799. if (possibleFormats.includes(BarcodeFormat$1.RSS_14)) {
  11800. this.readers.push(new RSS14Reader());
  11801. }
  11802. if (possibleFormats.includes(BarcodeFormat$1.RSS_EXPANDED)) {
  11803. console.warn('RSS Expanded reader IS NOT ready for production yet! use at your own risk.');
  11804. this.readers.push(new RSSExpandedReader());
  11805. }
  11806. }
  11807. if (this.readers.length === 0) {
  11808. this.readers.push(new MultiFormatUPCEANReader(hints));
  11809. this.readers.push(new Code39Reader());
  11810. // this.readers.push(new CodaBarReader());
  11811. this.readers.push(new Code93Reader());
  11812. this.readers.push(new MultiFormatUPCEANReader(hints));
  11813. this.readers.push(new Code128Reader());
  11814. this.readers.push(new ITFReader());
  11815. this.readers.push(new RSS14Reader());
  11816. // this.readers.push(new RSSExpandedReader());
  11817. }
  11818. }
  11819. // @Override
  11820. decodeRow(rowNumber, row, hints) {
  11821. for (let i = 0; i < this.readers.length; i++) {
  11822. try {
  11823. return this.readers[i].decodeRow(rowNumber, row, hints);
  11824. }
  11825. catch (re) {
  11826. // continue
  11827. }
  11828. }
  11829. throw new NotFoundException();
  11830. }
  11831. // @Override
  11832. reset() {
  11833. this.readers.forEach(reader => reader.reset());
  11834. }
  11835. }
  11836. /**
  11837. * @deprecated Moving to @zxing/browser
  11838. *
  11839. * Barcode reader reader to use from browser.
  11840. */
  11841. class BrowserBarcodeReader extends BrowserCodeReader {
  11842. /**
  11843. * Creates an instance of BrowserBarcodeReader.
  11844. * @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
  11845. * @param {Map<DecodeHintType, any>} hints
  11846. */
  11847. constructor(timeBetweenScansMillis = 500, hints) {
  11848. super(new MultiFormatOneDReader(hints), timeBetweenScansMillis, hints);
  11849. }
  11850. }
  11851. /*
  11852. * Copyright 2007 ZXing authors
  11853. *
  11854. * Licensed under the Apache License, Version 2.0 (the "License");
  11855. * you may not use this file except in compliance with the License.
  11856. * You may obtain a copy of the License at
  11857. *
  11858. * http://www.apache.org/licenses/LICENSE-2.0
  11859. *
  11860. * Unless required by applicable law or agreed to in writing, software
  11861. * distributed under the License is distributed on an "AS IS" BASIS,
  11862. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11863. * See the License for the specific language governing permissions and
  11864. * limitations under the License.
  11865. */
  11866. /**
  11867. * <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
  11868. * use blocks of differing sizes within one version, so, this encapsulates the parameters for
  11869. * each set of blocks. It also holds the number of error-correction codewords per block since it
  11870. * will be the same across all blocks within one version.</p>
  11871. */
  11872. class ECBlocks {
  11873. constructor(ecCodewords, ecBlocks1, ecBlocks2) {
  11874. this.ecCodewords = ecCodewords;
  11875. this.ecBlocks = [ecBlocks1];
  11876. ecBlocks2 && this.ecBlocks.push(ecBlocks2);
  11877. }
  11878. getECCodewords() {
  11879. return this.ecCodewords;
  11880. }
  11881. getECBlocks() {
  11882. return this.ecBlocks;
  11883. }
  11884. }
  11885. /**
  11886. * <p>Encapsulates the parameters for one error-correction block in one symbol version.
  11887. * This includes the number of data codewords, and the number of times a block with these
  11888. * parameters is used consecutively in the Data Matrix code version's format.</p>
  11889. */
  11890. class ECB {
  11891. constructor(count, dataCodewords) {
  11892. this.count = count;
  11893. this.dataCodewords = dataCodewords;
  11894. }
  11895. getCount() {
  11896. return this.count;
  11897. }
  11898. getDataCodewords() {
  11899. return this.dataCodewords;
  11900. }
  11901. }
  11902. /**
  11903. * The Version object encapsulates attributes about a particular
  11904. * size Data Matrix Code.
  11905. *
  11906. * @author bbrown@google.com (Brian Brown)
  11907. */
  11908. class Version {
  11909. constructor(versionNumber, symbolSizeRows, symbolSizeColumns, dataRegionSizeRows, dataRegionSizeColumns, ecBlocks) {
  11910. this.versionNumber = versionNumber;
  11911. this.symbolSizeRows = symbolSizeRows;
  11912. this.symbolSizeColumns = symbolSizeColumns;
  11913. this.dataRegionSizeRows = dataRegionSizeRows;
  11914. this.dataRegionSizeColumns = dataRegionSizeColumns;
  11915. this.ecBlocks = ecBlocks;
  11916. // Calculate the total number of codewords
  11917. let total = 0;
  11918. const ecCodewords = ecBlocks.getECCodewords();
  11919. const ecbArray = ecBlocks.getECBlocks();
  11920. for (let ecBlock of ecbArray) {
  11921. total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords);
  11922. }
  11923. this.totalCodewords = total;
  11924. }
  11925. getVersionNumber() {
  11926. return this.versionNumber;
  11927. }
  11928. getSymbolSizeRows() {
  11929. return this.symbolSizeRows;
  11930. }
  11931. getSymbolSizeColumns() {
  11932. return this.symbolSizeColumns;
  11933. }
  11934. getDataRegionSizeRows() {
  11935. return this.dataRegionSizeRows;
  11936. }
  11937. getDataRegionSizeColumns() {
  11938. return this.dataRegionSizeColumns;
  11939. }
  11940. getTotalCodewords() {
  11941. return this.totalCodewords;
  11942. }
  11943. getECBlocks() {
  11944. return this.ecBlocks;
  11945. }
  11946. /**
  11947. * <p>Deduces version information from Data Matrix dimensions.</p>
  11948. *
  11949. * @param numRows Number of rows in modules
  11950. * @param numColumns Number of columns in modules
  11951. * @return Version for a Data Matrix Code of those dimensions
  11952. * @throws FormatException if dimensions do correspond to a valid Data Matrix size
  11953. */
  11954. static getVersionForDimensions(numRows, numColumns) {
  11955. if ((numRows & 0x01) !== 0 || (numColumns & 0x01) !== 0) {
  11956. throw new FormatException();
  11957. }
  11958. for (let version of Version.VERSIONS) {
  11959. if (version.symbolSizeRows === numRows && version.symbolSizeColumns === numColumns) {
  11960. return version;
  11961. }
  11962. }
  11963. throw new FormatException();
  11964. }
  11965. // @Override
  11966. toString() {
  11967. return '' + this.versionNumber;
  11968. }
  11969. /**
  11970. * See ISO 16022:2006 5.5.1 Table 7
  11971. */
  11972. static buildVersions() {
  11973. return [
  11974. new Version(1, 10, 10, 8, 8, new ECBlocks(5, new ECB(1, 3))),
  11975. new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))),
  11976. new Version(3, 14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))),
  11977. new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))),
  11978. new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))),
  11979. new Version(6, 20, 20, 18, 18, new ECBlocks(18, new ECB(1, 22))),
  11980. new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))),
  11981. new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))),
  11982. new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))),
  11983. new Version(10, 32, 32, 14, 14, new ECBlocks(36, new ECB(1, 62))),
  11984. new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))),
  11985. new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))),
  11986. new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))),
  11987. new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))),
  11988. new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))),
  11989. new Version(16, 64, 64, 14, 14, new ECBlocks(56, new ECB(2, 140))),
  11990. new Version(17, 72, 72, 16, 16, new ECBlocks(36, new ECB(4, 92))),
  11991. new Version(18, 80, 80, 18, 18, new ECBlocks(48, new ECB(4, 114))),
  11992. new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))),
  11993. new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))),
  11994. new Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))),
  11995. new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))),
  11996. new Version(23, 132, 132, 20, 20, new ECBlocks(62, new ECB(8, 163))),
  11997. new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))),
  11998. new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))),
  11999. new Version(26, 8, 32, 6, 14, new ECBlocks(11, new ECB(1, 10))),
  12000. new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))),
  12001. new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))),
  12002. new Version(29, 16, 36, 14, 16, new ECBlocks(24, new ECB(1, 32))),
  12003. new Version(30, 16, 48, 14, 22, new ECBlocks(28, new ECB(1, 49)))
  12004. ];
  12005. }
  12006. }
  12007. Version.VERSIONS = Version.buildVersions();
  12008. /*
  12009. * Copyright 2007 ZXing authors
  12010. *
  12011. * Licensed under the Apache License, Version 2.0 (the "License");
  12012. * you may not use this file except in compliance with the License.
  12013. * You may obtain a copy of the License at
  12014. *
  12015. * http://www.apache.org/licenses/LICENSE-2.0
  12016. *
  12017. * Unless required by applicable law or agreed to in writing, software
  12018. * distributed under the License is distributed on an "AS IS" BASIS,
  12019. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12020. * See the License for the specific language governing permissions and
  12021. * limitations under the License.
  12022. */
  12023. /**
  12024. * @author bbrown@google.com (Brian Brown)
  12025. */
  12026. class BitMatrixParser {
  12027. /**
  12028. * @param bitMatrix {@link BitMatrix} to parse
  12029. * @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2
  12030. */
  12031. constructor(bitMatrix) {
  12032. const dimension = bitMatrix.getHeight();
  12033. if (dimension < 8 || dimension > 144 || (dimension & 0x01) !== 0) {
  12034. throw new FormatException();
  12035. }
  12036. this.version = BitMatrixParser.readVersion(bitMatrix);
  12037. this.mappingBitMatrix = this.extractDataRegion(bitMatrix);
  12038. this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.getWidth(), this.mappingBitMatrix.getHeight());
  12039. }
  12040. getVersion() {
  12041. return this.version;
  12042. }
  12043. /**
  12044. * <p>Creates the version object based on the dimension of the original bit matrix from
  12045. * the datamatrix code.</p>
  12046. *
  12047. * <p>See ISO 16022:2006 Table 7 - ECC 200 symbol attributes</p>
  12048. *
  12049. * @param bitMatrix Original {@link BitMatrix} including alignment patterns
  12050. * @return {@link Version} encapsulating the Data Matrix Code's "version"
  12051. * @throws FormatException if the dimensions of the mapping matrix are not valid
  12052. * Data Matrix dimensions.
  12053. */
  12054. static readVersion(bitMatrix) {
  12055. const numRows = bitMatrix.getHeight();
  12056. const numColumns = bitMatrix.getWidth();
  12057. return Version.getVersionForDimensions(numRows, numColumns);
  12058. }
  12059. /**
  12060. * <p>Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns)
  12061. * in the correct order in order to reconstitute the codewords bytes contained within the
  12062. * Data Matrix Code.</p>
  12063. *
  12064. * @return bytes encoded within the Data Matrix Code
  12065. * @throws FormatException if the exact number of bytes expected is not read
  12066. */
  12067. readCodewords() {
  12068. const result = new Int8Array(this.version.getTotalCodewords());
  12069. let resultOffset = 0;
  12070. let row = 4;
  12071. let column = 0;
  12072. const numRows = this.mappingBitMatrix.getHeight();
  12073. const numColumns = this.mappingBitMatrix.getWidth();
  12074. let corner1Read = false;
  12075. let corner2Read = false;
  12076. let corner3Read = false;
  12077. let corner4Read = false;
  12078. // Read all of the codewords
  12079. do {
  12080. // Check the four corner cases
  12081. if ((row === numRows) && (column === 0) && !corner1Read) {
  12082. result[resultOffset++] = this.readCorner1(numRows, numColumns) & 0xff;
  12083. row -= 2;
  12084. column += 2;
  12085. corner1Read = true;
  12086. }
  12087. else if ((row === numRows - 2) && (column === 0) && ((numColumns & 0x03) !== 0) && !corner2Read) {
  12088. result[resultOffset++] = this.readCorner2(numRows, numColumns) & 0xff;
  12089. row -= 2;
  12090. column += 2;
  12091. corner2Read = true;
  12092. }
  12093. else if ((row === numRows + 4) && (column === 2) && ((numColumns & 0x07) === 0) && !corner3Read) {
  12094. result[resultOffset++] = this.readCorner3(numRows, numColumns) & 0xff;
  12095. row -= 2;
  12096. column += 2;
  12097. corner3Read = true;
  12098. }
  12099. else if ((row === numRows - 2) && (column === 0) && ((numColumns & 0x07) === 4) && !corner4Read) {
  12100. result[resultOffset++] = this.readCorner4(numRows, numColumns) & 0xff;
  12101. row -= 2;
  12102. column += 2;
  12103. corner4Read = true;
  12104. }
  12105. else {
  12106. // Sweep upward diagonally to the right
  12107. do {
  12108. if ((row < numRows) && (column >= 0) && !this.readMappingMatrix.get(column, row)) {
  12109. result[resultOffset++] = this.readUtah(row, column, numRows, numColumns) & 0xff;
  12110. }
  12111. row -= 2;
  12112. column += 2;
  12113. } while ((row >= 0) && (column < numColumns));
  12114. row += 1;
  12115. column += 3;
  12116. // Sweep downward diagonally to the left
  12117. do {
  12118. if ((row >= 0) && (column < numColumns) && !this.readMappingMatrix.get(column, row)) {
  12119. result[resultOffset++] = this.readUtah(row, column, numRows, numColumns) & 0xff;
  12120. }
  12121. row += 2;
  12122. column -= 2;
  12123. } while ((row < numRows) && (column >= 0));
  12124. row += 3;
  12125. column += 1;
  12126. }
  12127. } while ((row < numRows) || (column < numColumns));
  12128. if (resultOffset !== this.version.getTotalCodewords()) {
  12129. throw new FormatException();
  12130. }
  12131. return result;
  12132. }
  12133. /**
  12134. * <p>Reads a bit of the mapping matrix accounting for boundary wrapping.</p>
  12135. *
  12136. * @param row Row to read in the mapping matrix
  12137. * @param column Column to read in the mapping matrix
  12138. * @param numRows Number of rows in the mapping matrix
  12139. * @param numColumns Number of columns in the mapping matrix
  12140. * @return value of the given bit in the mapping matrix
  12141. */
  12142. readModule(row, column, numRows, numColumns) {
  12143. // Adjust the row and column indices based on boundary wrapping
  12144. if (row < 0) {
  12145. row += numRows;
  12146. column += 4 - ((numRows + 4) & 0x07);
  12147. }
  12148. if (column < 0) {
  12149. column += numColumns;
  12150. row += 4 - ((numColumns + 4) & 0x07);
  12151. }
  12152. this.readMappingMatrix.set(column, row);
  12153. return this.mappingBitMatrix.get(column, row);
  12154. }
  12155. /**
  12156. * <p>Reads the 8 bits of the standard Utah-shaped pattern.</p>
  12157. *
  12158. * <p>See ISO 16022:2006, 5.8.1 Figure 6</p>
  12159. *
  12160. * @param row Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern
  12161. * @param column Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern
  12162. * @param numRows Number of rows in the mapping matrix
  12163. * @param numColumns Number of columns in the mapping matrix
  12164. * @return byte from the utah shape
  12165. */
  12166. readUtah(row, column, numRows, numColumns) {
  12167. let currentByte = 0;
  12168. if (this.readModule(row - 2, column - 2, numRows, numColumns)) {
  12169. currentByte |= 1;
  12170. }
  12171. currentByte <<= 1;
  12172. if (this.readModule(row - 2, column - 1, numRows, numColumns)) {
  12173. currentByte |= 1;
  12174. }
  12175. currentByte <<= 1;
  12176. if (this.readModule(row - 1, column - 2, numRows, numColumns)) {
  12177. currentByte |= 1;
  12178. }
  12179. currentByte <<= 1;
  12180. if (this.readModule(row - 1, column - 1, numRows, numColumns)) {
  12181. currentByte |= 1;
  12182. }
  12183. currentByte <<= 1;
  12184. if (this.readModule(row - 1, column, numRows, numColumns)) {
  12185. currentByte |= 1;
  12186. }
  12187. currentByte <<= 1;
  12188. if (this.readModule(row, column - 2, numRows, numColumns)) {
  12189. currentByte |= 1;
  12190. }
  12191. currentByte <<= 1;
  12192. if (this.readModule(row, column - 1, numRows, numColumns)) {
  12193. currentByte |= 1;
  12194. }
  12195. currentByte <<= 1;
  12196. if (this.readModule(row, column, numRows, numColumns)) {
  12197. currentByte |= 1;
  12198. }
  12199. return currentByte;
  12200. }
  12201. /**
  12202. * <p>Reads the 8 bits of the special corner condition 1.</p>
  12203. *
  12204. * <p>See ISO 16022:2006, Figure F.3</p>
  12205. *
  12206. * @param numRows Number of rows in the mapping matrix
  12207. * @param numColumns Number of columns in the mapping matrix
  12208. * @return byte from the Corner condition 1
  12209. */
  12210. readCorner1(numRows, numColumns) {
  12211. let currentByte = 0;
  12212. if (this.readModule(numRows - 1, 0, numRows, numColumns)) {
  12213. currentByte |= 1;
  12214. }
  12215. currentByte <<= 1;
  12216. if (this.readModule(numRows - 1, 1, numRows, numColumns)) {
  12217. currentByte |= 1;
  12218. }
  12219. currentByte <<= 1;
  12220. if (this.readModule(numRows - 1, 2, numRows, numColumns)) {
  12221. currentByte |= 1;
  12222. }
  12223. currentByte <<= 1;
  12224. if (this.readModule(0, numColumns - 2, numRows, numColumns)) {
  12225. currentByte |= 1;
  12226. }
  12227. currentByte <<= 1;
  12228. if (this.readModule(0, numColumns - 1, numRows, numColumns)) {
  12229. currentByte |= 1;
  12230. }
  12231. currentByte <<= 1;
  12232. if (this.readModule(1, numColumns - 1, numRows, numColumns)) {
  12233. currentByte |= 1;
  12234. }
  12235. currentByte <<= 1;
  12236. if (this.readModule(2, numColumns - 1, numRows, numColumns)) {
  12237. currentByte |= 1;
  12238. }
  12239. currentByte <<= 1;
  12240. if (this.readModule(3, numColumns - 1, numRows, numColumns)) {
  12241. currentByte |= 1;
  12242. }
  12243. return currentByte;
  12244. }
  12245. /**
  12246. * <p>Reads the 8 bits of the special corner condition 2.</p>
  12247. *
  12248. * <p>See ISO 16022:2006, Figure F.4</p>
  12249. *
  12250. * @param numRows Number of rows in the mapping matrix
  12251. * @param numColumns Number of columns in the mapping matrix
  12252. * @return byte from the Corner condition 2
  12253. */
  12254. readCorner2(numRows, numColumns) {
  12255. let currentByte = 0;
  12256. if (this.readModule(numRows - 3, 0, numRows, numColumns)) {
  12257. currentByte |= 1;
  12258. }
  12259. currentByte <<= 1;
  12260. if (this.readModule(numRows - 2, 0, numRows, numColumns)) {
  12261. currentByte |= 1;
  12262. }
  12263. currentByte <<= 1;
  12264. if (this.readModule(numRows - 1, 0, numRows, numColumns)) {
  12265. currentByte |= 1;
  12266. }
  12267. currentByte <<= 1;
  12268. if (this.readModule(0, numColumns - 4, numRows, numColumns)) {
  12269. currentByte |= 1;
  12270. }
  12271. currentByte <<= 1;
  12272. if (this.readModule(0, numColumns - 3, numRows, numColumns)) {
  12273. currentByte |= 1;
  12274. }
  12275. currentByte <<= 1;
  12276. if (this.readModule(0, numColumns - 2, numRows, numColumns)) {
  12277. currentByte |= 1;
  12278. }
  12279. currentByte <<= 1;
  12280. if (this.readModule(0, numColumns - 1, numRows, numColumns)) {
  12281. currentByte |= 1;
  12282. }
  12283. currentByte <<= 1;
  12284. if (this.readModule(1, numColumns - 1, numRows, numColumns)) {
  12285. currentByte |= 1;
  12286. }
  12287. return currentByte;
  12288. }
  12289. /**
  12290. * <p>Reads the 8 bits of the special corner condition 3.</p>
  12291. *
  12292. * <p>See ISO 16022:2006, Figure F.5</p>
  12293. *
  12294. * @param numRows Number of rows in the mapping matrix
  12295. * @param numColumns Number of columns in the mapping matrix
  12296. * @return byte from the Corner condition 3
  12297. */
  12298. readCorner3(numRows, numColumns) {
  12299. let currentByte = 0;
  12300. if (this.readModule(numRows - 1, 0, numRows, numColumns)) {
  12301. currentByte |= 1;
  12302. }
  12303. currentByte <<= 1;
  12304. if (this.readModule(numRows - 1, numColumns - 1, numRows, numColumns)) {
  12305. currentByte |= 1;
  12306. }
  12307. currentByte <<= 1;
  12308. if (this.readModule(0, numColumns - 3, numRows, numColumns)) {
  12309. currentByte |= 1;
  12310. }
  12311. currentByte <<= 1;
  12312. if (this.readModule(0, numColumns - 2, numRows, numColumns)) {
  12313. currentByte |= 1;
  12314. }
  12315. currentByte <<= 1;
  12316. if (this.readModule(0, numColumns - 1, numRows, numColumns)) {
  12317. currentByte |= 1;
  12318. }
  12319. currentByte <<= 1;
  12320. if (this.readModule(1, numColumns - 3, numRows, numColumns)) {
  12321. currentByte |= 1;
  12322. }
  12323. currentByte <<= 1;
  12324. if (this.readModule(1, numColumns - 2, numRows, numColumns)) {
  12325. currentByte |= 1;
  12326. }
  12327. currentByte <<= 1;
  12328. if (this.readModule(1, numColumns - 1, numRows, numColumns)) {
  12329. currentByte |= 1;
  12330. }
  12331. return currentByte;
  12332. }
  12333. /**
  12334. * <p>Reads the 8 bits of the special corner condition 4.</p>
  12335. *
  12336. * <p>See ISO 16022:2006, Figure F.6</p>
  12337. *
  12338. * @param numRows Number of rows in the mapping matrix
  12339. * @param numColumns Number of columns in the mapping matrix
  12340. * @return byte from the Corner condition 4
  12341. */
  12342. readCorner4(numRows, numColumns) {
  12343. let currentByte = 0;
  12344. if (this.readModule(numRows - 3, 0, numRows, numColumns)) {
  12345. currentByte |= 1;
  12346. }
  12347. currentByte <<= 1;
  12348. if (this.readModule(numRows - 2, 0, numRows, numColumns)) {
  12349. currentByte |= 1;
  12350. }
  12351. currentByte <<= 1;
  12352. if (this.readModule(numRows - 1, 0, numRows, numColumns)) {
  12353. currentByte |= 1;
  12354. }
  12355. currentByte <<= 1;
  12356. if (this.readModule(0, numColumns - 2, numRows, numColumns)) {
  12357. currentByte |= 1;
  12358. }
  12359. currentByte <<= 1;
  12360. if (this.readModule(0, numColumns - 1, numRows, numColumns)) {
  12361. currentByte |= 1;
  12362. }
  12363. currentByte <<= 1;
  12364. if (this.readModule(1, numColumns - 1, numRows, numColumns)) {
  12365. currentByte |= 1;
  12366. }
  12367. currentByte <<= 1;
  12368. if (this.readModule(2, numColumns - 1, numRows, numColumns)) {
  12369. currentByte |= 1;
  12370. }
  12371. currentByte <<= 1;
  12372. if (this.readModule(3, numColumns - 1, numRows, numColumns)) {
  12373. currentByte |= 1;
  12374. }
  12375. return currentByte;
  12376. }
  12377. /**
  12378. * <p>Extracts the data region from a {@link BitMatrix} that contains
  12379. * alignment patterns.</p>
  12380. *
  12381. * @param bitMatrix Original {@link BitMatrix} with alignment patterns
  12382. * @return BitMatrix that has the alignment patterns removed
  12383. */
  12384. extractDataRegion(bitMatrix) {
  12385. const symbolSizeRows = this.version.getSymbolSizeRows();
  12386. const symbolSizeColumns = this.version.getSymbolSizeColumns();
  12387. if (bitMatrix.getHeight() !== symbolSizeRows) {
  12388. throw new IllegalArgumentException('Dimension of bitMatrix must match the version size');
  12389. }
  12390. const dataRegionSizeRows = this.version.getDataRegionSizeRows();
  12391. const dataRegionSizeColumns = this.version.getDataRegionSizeColumns();
  12392. const numDataRegionsRow = symbolSizeRows / dataRegionSizeRows | 0;
  12393. const numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns | 0;
  12394. const sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
  12395. const sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;
  12396. const bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow);
  12397. for (let dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {
  12398. const dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;
  12399. for (let dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) {
  12400. const dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;
  12401. for (let i = 0; i < dataRegionSizeRows; ++i) {
  12402. const readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;
  12403. const writeRowOffset = dataRegionRowOffset + i;
  12404. for (let j = 0; j < dataRegionSizeColumns; ++j) {
  12405. const readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;
  12406. if (bitMatrix.get(readColumnOffset, readRowOffset)) {
  12407. const writeColumnOffset = dataRegionColumnOffset + j;
  12408. bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset);
  12409. }
  12410. }
  12411. }
  12412. }
  12413. }
  12414. return bitMatrixWithoutAlignment;
  12415. }
  12416. }
  12417. /*
  12418. * Copyright 2008 ZXing authors
  12419. *
  12420. * Licensed under the Apache License, Version 2.0 (the "License");
  12421. * you may not use this file except in compliance with the License.
  12422. * You may obtain a copy of the License at
  12423. *
  12424. * http://www.apache.org/licenses/LICENSE-2.0
  12425. *
  12426. * Unless required by applicable law or agreed to in writing, software
  12427. * distributed under the License is distributed on an "AS IS" BASIS,
  12428. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12429. * See the License for the specific language governing permissions and
  12430. * limitations under the License.
  12431. */
  12432. /**
  12433. * <p>Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into
  12434. * multiple blocks, each of which is a unit of data and error-correction codewords. Each
  12435. * is represented by an instance of this class.</p>
  12436. *
  12437. * @author bbrown@google.com (Brian Brown)
  12438. */
  12439. class DataBlock {
  12440. constructor(numDataCodewords, codewords) {
  12441. this.numDataCodewords = numDataCodewords;
  12442. this.codewords = codewords;
  12443. }
  12444. /**
  12445. * <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them.
  12446. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
  12447. * method will separate the data into original blocks.</p>
  12448. *
  12449. * @param rawCodewords bytes as read directly from the Data Matrix Code
  12450. * @param version version of the Data Matrix Code
  12451. * @return DataBlocks containing original bytes, "de-interleaved" from representation in the
  12452. * Data Matrix Code
  12453. */
  12454. static getDataBlocks(rawCodewords, version) {
  12455. // Figure out the number and size of data blocks used by this version
  12456. const ecBlocks = version.getECBlocks();
  12457. // First count the total number of data blocks
  12458. let totalBlocks = 0;
  12459. const ecBlockArray = ecBlocks.getECBlocks();
  12460. for (let ecBlock of ecBlockArray) {
  12461. totalBlocks += ecBlock.getCount();
  12462. }
  12463. // Now establish DataBlocks of the appropriate size and number of data codewords
  12464. const result = new Array(totalBlocks);
  12465. let numResultBlocks = 0;
  12466. for (let ecBlock of ecBlockArray) {
  12467. for (let i = 0; i < ecBlock.getCount(); i++) {
  12468. const numDataCodewords = ecBlock.getDataCodewords();
  12469. const numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords;
  12470. result[numResultBlocks++] = new DataBlock(numDataCodewords, new Uint8Array(numBlockCodewords));
  12471. }
  12472. }
  12473. // All blocks have the same amount of data, except that the last n
  12474. // (where n may be 0) have 1 less byte. Figure out where these start.
  12475. // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144
  12476. const longerBlocksTotalCodewords = result[0].codewords.length;
  12477. // int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1;
  12478. const longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords();
  12479. const shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1;
  12480. // The last elements of result may be 1 element shorter for 144 matrix
  12481. // first fill out as many elements as all of them have minus 1
  12482. let rawCodewordsOffset = 0;
  12483. for (let i = 0; i < shorterBlocksNumDataCodewords; i++) {
  12484. for (let j = 0; j < numResultBlocks; j++) {
  12485. result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
  12486. }
  12487. }
  12488. // Fill out the last data block in the longer ones
  12489. const specialVersion = version.getVersionNumber() === 24;
  12490. const numLongerBlocks = specialVersion ? 8 : numResultBlocks;
  12491. for (let j = 0; j < numLongerBlocks; j++) {
  12492. result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++];
  12493. }
  12494. // Now add in error correction blocks
  12495. const max = result[0].codewords.length;
  12496. for (let i = longerBlocksNumDataCodewords; i < max; i++) {
  12497. for (let j = 0; j < numResultBlocks; j++) {
  12498. const jOffset = specialVersion ? (j + 8) % numResultBlocks : j;
  12499. const iOffset = specialVersion && jOffset > 7 ? i - 1 : i;
  12500. result[jOffset].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
  12501. }
  12502. }
  12503. if (rawCodewordsOffset !== rawCodewords.length) {
  12504. throw new IllegalArgumentException();
  12505. }
  12506. return result;
  12507. }
  12508. getNumDataCodewords() {
  12509. return this.numDataCodewords;
  12510. }
  12511. getCodewords() {
  12512. return this.codewords;
  12513. }
  12514. }
  12515. /*
  12516. * Copyright 2007 ZXing authors
  12517. *
  12518. * Licensed under the Apache License, Version 2.0 (the "License");
  12519. * you may not use this file except in compliance with the License.
  12520. * You may obtain a copy of the License at
  12521. *
  12522. * http://www.apache.org/licenses/LICENSE-2.0
  12523. *
  12524. * Unless required by applicable law or agreed to in writing, software
  12525. * distributed under the License is distributed on an "AS IS" BASIS,
  12526. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12527. * See the License for the specific language governing permissions and
  12528. * limitations under the License.
  12529. */
  12530. /**
  12531. * <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
  12532. * number of bits read is not often a multiple of 8.</p>
  12533. *
  12534. * <p>This class is thread-safe but not reentrant -- unless the caller modifies the bytes array
  12535. * it passed in, in which case all bets are off.</p>
  12536. *
  12537. * @author Sean Owen
  12538. */
  12539. class BitSource {
  12540. /**
  12541. * @param bytes bytes from which this will read bits. Bits will be read from the first byte first.
  12542. * Bits are read within a byte from most-significant to least-significant bit.
  12543. */
  12544. constructor(bytes) {
  12545. this.bytes = bytes;
  12546. this.byteOffset = 0;
  12547. this.bitOffset = 0;
  12548. }
  12549. /**
  12550. * @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
  12551. */
  12552. getBitOffset() {
  12553. return this.bitOffset;
  12554. }
  12555. /**
  12556. * @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
  12557. */
  12558. getByteOffset() {
  12559. return this.byteOffset;
  12560. }
  12561. /**
  12562. * @param numBits number of bits to read
  12563. * @return int representing the bits read. The bits will appear as the least-significant
  12564. * bits of the int
  12565. * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available
  12566. */
  12567. readBits(numBits /*int*/) {
  12568. if (numBits < 1 || numBits > 32 || numBits > this.available()) {
  12569. throw new IllegalArgumentException('' + numBits);
  12570. }
  12571. let result = 0;
  12572. let bitOffset = this.bitOffset;
  12573. let byteOffset = this.byteOffset;
  12574. const bytes = this.bytes;
  12575. // First, read remainder from current byte
  12576. if (bitOffset > 0) {
  12577. const bitsLeft = 8 - bitOffset;
  12578. const toRead = numBits < bitsLeft ? numBits : bitsLeft;
  12579. const bitsToNotRead = bitsLeft - toRead;
  12580. const mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
  12581. result = (bytes[byteOffset] & mask) >> bitsToNotRead;
  12582. numBits -= toRead;
  12583. bitOffset += toRead;
  12584. if (bitOffset === 8) {
  12585. bitOffset = 0;
  12586. byteOffset++;
  12587. }
  12588. }
  12589. // Next read whole bytes
  12590. if (numBits > 0) {
  12591. while (numBits >= 8) {
  12592. result = (result << 8) | (bytes[byteOffset] & 0xFF);
  12593. byteOffset++;
  12594. numBits -= 8;
  12595. }
  12596. // Finally read a partial byte
  12597. if (numBits > 0) {
  12598. const bitsToNotRead = 8 - numBits;
  12599. const mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
  12600. result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
  12601. bitOffset += numBits;
  12602. }
  12603. }
  12604. this.bitOffset = bitOffset;
  12605. this.byteOffset = byteOffset;
  12606. return result;
  12607. }
  12608. /**
  12609. * @return number of bits that can be read successfully
  12610. */
  12611. available() {
  12612. return 8 * (this.bytes.length - this.byteOffset) - this.bitOffset;
  12613. }
  12614. }
  12615. /*
  12616. * Copyright 2008 ZXing authors
  12617. *
  12618. * Licensed under the Apache License, Version 2.0 (the "License");
  12619. * you may not use this file except in compliance with the License.
  12620. * You may obtain a copy of the License at
  12621. *
  12622. * http://www.apache.org/licenses/LICENSE-2.0
  12623. *
  12624. * Unless required by applicable law or agreed to in writing, software
  12625. * distributed under the License is distributed on an "AS IS" BASIS,
  12626. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12627. * See the License for the specific language governing permissions and
  12628. * limitations under the License.
  12629. */
  12630. var Mode;
  12631. (function (Mode) {
  12632. Mode[Mode["PAD_ENCODE"] = 0] = "PAD_ENCODE";
  12633. Mode[Mode["ASCII_ENCODE"] = 1] = "ASCII_ENCODE";
  12634. Mode[Mode["C40_ENCODE"] = 2] = "C40_ENCODE";
  12635. Mode[Mode["TEXT_ENCODE"] = 3] = "TEXT_ENCODE";
  12636. Mode[Mode["ANSIX12_ENCODE"] = 4] = "ANSIX12_ENCODE";
  12637. Mode[Mode["EDIFACT_ENCODE"] = 5] = "EDIFACT_ENCODE";
  12638. Mode[Mode["BASE256_ENCODE"] = 6] = "BASE256_ENCODE";
  12639. })(Mode || (Mode = {}));
  12640. /**
  12641. * <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes
  12642. * in one Data Matrix Code. This class decodes the bits back into text.</p>
  12643. *
  12644. * <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p>
  12645. *
  12646. * @author bbrown@google.com (Brian Brown)
  12647. * @author Sean Owen
  12648. */
  12649. class DecodedBitStreamParser {
  12650. static decode(bytes) {
  12651. const bits = new BitSource(bytes);
  12652. const result = new StringBuilder();
  12653. const resultTrailer = new StringBuilder();
  12654. const byteSegments = new Array();
  12655. let mode = Mode.ASCII_ENCODE;
  12656. do {
  12657. if (mode === Mode.ASCII_ENCODE) {
  12658. mode = this.decodeAsciiSegment(bits, result, resultTrailer);
  12659. }
  12660. else {
  12661. switch (mode) {
  12662. case Mode.C40_ENCODE:
  12663. this.decodeC40Segment(bits, result);
  12664. break;
  12665. case Mode.TEXT_ENCODE:
  12666. this.decodeTextSegment(bits, result);
  12667. break;
  12668. case Mode.ANSIX12_ENCODE:
  12669. this.decodeAnsiX12Segment(bits, result);
  12670. break;
  12671. case Mode.EDIFACT_ENCODE:
  12672. this.decodeEdifactSegment(bits, result);
  12673. break;
  12674. case Mode.BASE256_ENCODE:
  12675. this.decodeBase256Segment(bits, result, byteSegments);
  12676. break;
  12677. default:
  12678. throw new FormatException();
  12679. }
  12680. mode = Mode.ASCII_ENCODE;
  12681. }
  12682. } while (mode !== Mode.PAD_ENCODE && bits.available() > 0);
  12683. if (resultTrailer.length() > 0) {
  12684. result.append(resultTrailer.toString());
  12685. }
  12686. return new DecoderResult(bytes, result.toString(), byteSegments.length === 0 ? null : byteSegments, null);
  12687. }
  12688. /**
  12689. * See ISO 16022:2006, 5.2.3 and Annex C, Table C.2
  12690. */
  12691. static decodeAsciiSegment(bits, result, resultTrailer) {
  12692. let upperShift = false;
  12693. do {
  12694. let oneByte = bits.readBits(8);
  12695. if (oneByte === 0) {
  12696. throw new FormatException();
  12697. }
  12698. else if (oneByte <= 128) { // ASCII data (ASCII value + 1)
  12699. if (upperShift) {
  12700. oneByte += 128;
  12701. // upperShift = false;
  12702. }
  12703. result.append(String.fromCharCode(oneByte - 1));
  12704. return Mode.ASCII_ENCODE;
  12705. }
  12706. else if (oneByte === 129) { // Pad
  12707. return Mode.PAD_ENCODE;
  12708. }
  12709. else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130)
  12710. const value = oneByte - 130;
  12711. if (value < 10) { // pad with '0' for single digit values
  12712. result.append('0');
  12713. }
  12714. result.append('' + value);
  12715. }
  12716. else {
  12717. switch (oneByte) {
  12718. case 230: // Latch to C40 encodation
  12719. return Mode.C40_ENCODE;
  12720. case 231: // Latch to Base 256 encodation
  12721. return Mode.BASE256_ENCODE;
  12722. case 232: // FNC1
  12723. result.append(String.fromCharCode(29)); // translate as ASCII 29
  12724. break;
  12725. case 233: // Structured Append
  12726. case 234: // Reader Programming
  12727. // Ignore these symbols for now
  12728. // throw ReaderException.getInstance();
  12729. break;
  12730. case 235: // Upper Shift (shift to Extended ASCII)
  12731. upperShift = true;
  12732. break;
  12733. case 236: // 05 Macro
  12734. result.append('[)>\u001E05\u001D');
  12735. resultTrailer.insert(0, '\u001E\u0004');
  12736. break;
  12737. case 237: // 06 Macro
  12738. result.append('[)>\u001E06\u001D');
  12739. resultTrailer.insert(0, '\u001E\u0004');
  12740. break;
  12741. case 238: // Latch to ANSI X12 encodation
  12742. return Mode.ANSIX12_ENCODE;
  12743. case 239: // Latch to Text encodation
  12744. return Mode.TEXT_ENCODE;
  12745. case 240: // Latch to EDIFACT encodation
  12746. return Mode.EDIFACT_ENCODE;
  12747. case 241: // ECI Character
  12748. // TODO(bbrown): I think we need to support ECI
  12749. // throw ReaderException.getInstance();
  12750. // Ignore this symbol for now
  12751. break;
  12752. default:
  12753. // Not to be used in ASCII encodation
  12754. // but work around encoders that end with 254, latch back to ASCII
  12755. if (oneByte !== 254 || bits.available() !== 0) {
  12756. throw new FormatException();
  12757. }
  12758. break;
  12759. }
  12760. }
  12761. } while (bits.available() > 0);
  12762. return Mode.ASCII_ENCODE;
  12763. }
  12764. /**
  12765. * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1
  12766. */
  12767. static decodeC40Segment(bits, result) {
  12768. // Three C40 values are encoded in a 16-bit value as
  12769. // (1600 * C1) + (40 * C2) + C3 + 1
  12770. // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time
  12771. let upperShift = false;
  12772. const cValues = [];
  12773. let shift = 0;
  12774. do {
  12775. // If there is only one byte left then it will be encoded as ASCII
  12776. if (bits.available() === 8) {
  12777. return;
  12778. }
  12779. const firstByte = bits.readBits(8);
  12780. if (firstByte === 254) { // Unlatch codeword
  12781. return;
  12782. }
  12783. this.parseTwoBytes(firstByte, bits.readBits(8), cValues);
  12784. for (let i = 0; i < 3; i++) {
  12785. const cValue = cValues[i];
  12786. switch (shift) {
  12787. case 0:
  12788. if (cValue < 3) {
  12789. shift = cValue + 1;
  12790. }
  12791. else if (cValue < this.C40_BASIC_SET_CHARS.length) {
  12792. const c40char = this.C40_BASIC_SET_CHARS[cValue];
  12793. if (upperShift) {
  12794. result.append(String.fromCharCode(c40char.charCodeAt(0) + 128));
  12795. upperShift = false;
  12796. }
  12797. else {
  12798. result.append(c40char);
  12799. }
  12800. }
  12801. else {
  12802. throw new FormatException();
  12803. }
  12804. break;
  12805. case 1:
  12806. if (upperShift) {
  12807. result.append(String.fromCharCode(cValue + 128));
  12808. upperShift = false;
  12809. }
  12810. else {
  12811. result.append(String.fromCharCode(cValue));
  12812. }
  12813. shift = 0;
  12814. break;
  12815. case 2:
  12816. if (cValue < this.C40_SHIFT2_SET_CHARS.length) {
  12817. const c40char = this.C40_SHIFT2_SET_CHARS[cValue];
  12818. if (upperShift) {
  12819. result.append(String.fromCharCode(c40char.charCodeAt(0) + 128));
  12820. upperShift = false;
  12821. }
  12822. else {
  12823. result.append(c40char);
  12824. }
  12825. }
  12826. else {
  12827. switch (cValue) {
  12828. case 27: // FNC1
  12829. result.append(String.fromCharCode(29)); // translate as ASCII 29
  12830. break;
  12831. case 30: // Upper Shift
  12832. upperShift = true;
  12833. break;
  12834. default:
  12835. throw new FormatException();
  12836. }
  12837. }
  12838. shift = 0;
  12839. break;
  12840. case 3:
  12841. if (upperShift) {
  12842. result.append(String.fromCharCode(cValue + 224));
  12843. upperShift = false;
  12844. }
  12845. else {
  12846. result.append(String.fromCharCode(cValue + 96));
  12847. }
  12848. shift = 0;
  12849. break;
  12850. default:
  12851. throw new FormatException();
  12852. }
  12853. }
  12854. } while (bits.available() > 0);
  12855. }
  12856. /**
  12857. * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2
  12858. */
  12859. static decodeTextSegment(bits, result) {
  12860. // Three Text values are encoded in a 16-bit value as
  12861. // (1600 * C1) + (40 * C2) + C3 + 1
  12862. // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time
  12863. let upperShift = false;
  12864. let cValues = [];
  12865. let shift = 0;
  12866. do {
  12867. // If there is only one byte left then it will be encoded as ASCII
  12868. if (bits.available() === 8) {
  12869. return;
  12870. }
  12871. const firstByte = bits.readBits(8);
  12872. if (firstByte === 254) { // Unlatch codeword
  12873. return;
  12874. }
  12875. this.parseTwoBytes(firstByte, bits.readBits(8), cValues);
  12876. for (let i = 0; i < 3; i++) {
  12877. const cValue = cValues[i];
  12878. switch (shift) {
  12879. case 0:
  12880. if (cValue < 3) {
  12881. shift = cValue + 1;
  12882. }
  12883. else if (cValue < this.TEXT_BASIC_SET_CHARS.length) {
  12884. const textChar = this.TEXT_BASIC_SET_CHARS[cValue];
  12885. if (upperShift) {
  12886. result.append(String.fromCharCode(textChar.charCodeAt(0) + 128));
  12887. upperShift = false;
  12888. }
  12889. else {
  12890. result.append(textChar);
  12891. }
  12892. }
  12893. else {
  12894. throw new FormatException();
  12895. }
  12896. break;
  12897. case 1:
  12898. if (upperShift) {
  12899. result.append(String.fromCharCode(cValue + 128));
  12900. upperShift = false;
  12901. }
  12902. else {
  12903. result.append(String.fromCharCode(cValue));
  12904. }
  12905. shift = 0;
  12906. break;
  12907. case 2:
  12908. // Shift 2 for Text is the same encoding as C40
  12909. if (cValue < this.TEXT_SHIFT2_SET_CHARS.length) {
  12910. const textChar = this.TEXT_SHIFT2_SET_CHARS[cValue];
  12911. if (upperShift) {
  12912. result.append(String.fromCharCode(textChar.charCodeAt(0) + 128));
  12913. upperShift = false;
  12914. }
  12915. else {
  12916. result.append(textChar);
  12917. }
  12918. }
  12919. else {
  12920. switch (cValue) {
  12921. case 27: // FNC1
  12922. result.append(String.fromCharCode(29)); // translate as ASCII 29
  12923. break;
  12924. case 30: // Upper Shift
  12925. upperShift = true;
  12926. break;
  12927. default:
  12928. throw new FormatException();
  12929. }
  12930. }
  12931. shift = 0;
  12932. break;
  12933. case 3:
  12934. if (cValue < this.TEXT_SHIFT3_SET_CHARS.length) {
  12935. const textChar = this.TEXT_SHIFT3_SET_CHARS[cValue];
  12936. if (upperShift) {
  12937. result.append(String.fromCharCode(textChar.charCodeAt(0) + 128));
  12938. upperShift = false;
  12939. }
  12940. else {
  12941. result.append(textChar);
  12942. }
  12943. shift = 0;
  12944. }
  12945. else {
  12946. throw new FormatException();
  12947. }
  12948. break;
  12949. default:
  12950. throw new FormatException();
  12951. }
  12952. }
  12953. } while (bits.available() > 0);
  12954. }
  12955. /**
  12956. * See ISO 16022:2006, 5.2.7
  12957. */
  12958. static decodeAnsiX12Segment(bits, result) {
  12959. // Three ANSI X12 values are encoded in a 16-bit value as
  12960. // (1600 * C1) + (40 * C2) + C3 + 1
  12961. const cValues = [];
  12962. do {
  12963. // If there is only one byte left then it will be encoded as ASCII
  12964. if (bits.available() === 8) {
  12965. return;
  12966. }
  12967. const firstByte = bits.readBits(8);
  12968. if (firstByte === 254) { // Unlatch codeword
  12969. return;
  12970. }
  12971. this.parseTwoBytes(firstByte, bits.readBits(8), cValues);
  12972. for (let i = 0; i < 3; i++) {
  12973. const cValue = cValues[i];
  12974. switch (cValue) {
  12975. case 0: // X12 segment terminator <CR>
  12976. result.append('\r');
  12977. break;
  12978. case 1: // X12 segment separator *
  12979. result.append('*');
  12980. break;
  12981. case 2: // X12 sub-element separator >
  12982. result.append('>');
  12983. break;
  12984. case 3: // space
  12985. result.append(' ');
  12986. break;
  12987. default:
  12988. if (cValue < 14) { // 0 - 9
  12989. result.append(String.fromCharCode(cValue + 44));
  12990. }
  12991. else if (cValue < 40) { // A - Z
  12992. result.append(String.fromCharCode(cValue + 51));
  12993. }
  12994. else {
  12995. throw new FormatException();
  12996. }
  12997. break;
  12998. }
  12999. }
  13000. } while (bits.available() > 0);
  13001. }
  13002. static parseTwoBytes(firstByte, secondByte, result) {
  13003. let fullBitValue = (firstByte << 8) + secondByte - 1;
  13004. let temp = Math.floor(fullBitValue / 1600);
  13005. result[0] = temp;
  13006. fullBitValue -= temp * 1600;
  13007. temp = Math.floor(fullBitValue / 40);
  13008. result[1] = temp;
  13009. result[2] = fullBitValue - temp * 40;
  13010. }
  13011. /**
  13012. * See ISO 16022:2006, 5.2.8 and Annex C Table C.3
  13013. */
  13014. static decodeEdifactSegment(bits, result) {
  13015. do {
  13016. // If there is only two or less bytes left then it will be encoded as ASCII
  13017. if (bits.available() <= 16) {
  13018. return;
  13019. }
  13020. for (let i = 0; i < 4; i++) {
  13021. let edifactValue = bits.readBits(6);
  13022. // Check for the unlatch character
  13023. if (edifactValue === 0x1F) { // 011111
  13024. // Read rest of byte, which should be 0, and stop
  13025. const bitsLeft = 8 - bits.getBitOffset();
  13026. if (bitsLeft !== 8) {
  13027. bits.readBits(bitsLeft);
  13028. }
  13029. return;
  13030. }
  13031. if ((edifactValue & 0x20) === 0) { // no 1 in the leading (6th) bit
  13032. edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value
  13033. }
  13034. result.append(String.fromCharCode(edifactValue));
  13035. }
  13036. } while (bits.available() > 0);
  13037. }
  13038. /**
  13039. * See ISO 16022:2006, 5.2.9 and Annex B, B.2
  13040. */
  13041. static decodeBase256Segment(bits, result, byteSegments) {
  13042. // Figure out how long the Base 256 Segment is.
  13043. let codewordPosition = 1 + bits.getByteOffset(); // position is 1-indexed
  13044. const d1 = this.unrandomize255State(bits.readBits(8), codewordPosition++);
  13045. let count;
  13046. if (d1 === 0) { // Read the remainder of the symbol
  13047. count = bits.available() / 8 | 0;
  13048. }
  13049. else if (d1 < 250) {
  13050. count = d1;
  13051. }
  13052. else {
  13053. count = 250 * (d1 - 249) + this.unrandomize255State(bits.readBits(8), codewordPosition++);
  13054. }
  13055. // We're seeing NegativeArraySizeException errors from users.
  13056. if (count < 0) {
  13057. throw new FormatException();
  13058. }
  13059. const bytes = new Uint8Array(count);
  13060. for (let i = 0; i < count; i++) {
  13061. // Have seen this particular error in the wild, such as at
  13062. // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
  13063. if (bits.available() < 8) {
  13064. throw new FormatException();
  13065. }
  13066. bytes[i] = this.unrandomize255State(bits.readBits(8), codewordPosition++);
  13067. }
  13068. byteSegments.push(bytes);
  13069. try {
  13070. result.append(StringEncoding.decode(bytes, StringUtils.ISO88591));
  13071. }
  13072. catch (uee) {
  13073. throw new IllegalStateException('Platform does not support required encoding: ' + uee.message);
  13074. }
  13075. }
  13076. /**
  13077. * See ISO 16022:2006, Annex B, B.2
  13078. */
  13079. static unrandomize255State(randomizedBase256Codeword, base256CodewordPosition) {
  13080. const pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1;
  13081. const tempVariable = randomizedBase256Codeword - pseudoRandomNumber;
  13082. return tempVariable >= 0 ? tempVariable : tempVariable + 256;
  13083. }
  13084. }
  13085. /**
  13086. * See ISO 16022:2006, Annex C Table C.1
  13087. * The C40 Basic Character Set (*'s used for placeholders for the shift values)
  13088. */
  13089. DecodedBitStreamParser.C40_BASIC_SET_CHARS = [
  13090. '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  13091. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
  13092. 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
  13093. ];
  13094. DecodedBitStreamParser.C40_SHIFT2_SET_CHARS = [
  13095. '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.',
  13096. '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_'
  13097. ];
  13098. /**
  13099. * See ISO 16022:2006, Annex C Table C.2
  13100. * The Text Basic Character Set (*'s used for placeholders for the shift values)
  13101. */
  13102. DecodedBitStreamParser.TEXT_BASIC_SET_CHARS = [
  13103. '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  13104. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  13105. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
  13106. ];
  13107. // Shift 2 for Text is the same encoding as C40
  13108. DecodedBitStreamParser.TEXT_SHIFT2_SET_CHARS = DecodedBitStreamParser.C40_SHIFT2_SET_CHARS;
  13109. DecodedBitStreamParser.TEXT_SHIFT3_SET_CHARS = [
  13110. '`', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
  13111. 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', String.fromCharCode(127)
  13112. ];
  13113. /*
  13114. * Copyright 2007 ZXing authors
  13115. *
  13116. * Licensed under the Apache License, Version 2.0 (the "License");
  13117. * you may not use this file except in compliance with the License.
  13118. * You may obtain a copy of the License at
  13119. *
  13120. * http://www.apache.org/licenses/LICENSE-2.0
  13121. *
  13122. * Unless required by applicable law or agreed to in writing, software
  13123. * distributed under the License is distributed on an "AS IS" BASIS,
  13124. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13125. * See the License for the specific language governing permissions and
  13126. * limitations under the License.
  13127. */
  13128. /**
  13129. * <p>The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting
  13130. * the Data Matrix Code from an image.</p>
  13131. *
  13132. * @author bbrown@google.com (Brian Brown)
  13133. */
  13134. class Decoder$1 {
  13135. constructor() {
  13136. this.rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);
  13137. }
  13138. /**
  13139. * <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken
  13140. * to mean a black module.</p>
  13141. *
  13142. * @param bits booleans representing white/black Data Matrix Code modules
  13143. * @return text and bytes encoded within the Data Matrix Code
  13144. * @throws FormatException if the Data Matrix Code cannot be decoded
  13145. * @throws ChecksumException if error correction fails
  13146. */
  13147. decode(bits) {
  13148. // Construct a parser and read version, error-correction level
  13149. const parser = new BitMatrixParser(bits);
  13150. const version = parser.getVersion();
  13151. // Read codewords
  13152. const codewords = parser.readCodewords();
  13153. // Separate into data blocks
  13154. const dataBlocks = DataBlock.getDataBlocks(codewords, version);
  13155. // Count total number of data bytes
  13156. let totalBytes = 0;
  13157. for (let db of dataBlocks) {
  13158. totalBytes += db.getNumDataCodewords();
  13159. }
  13160. const resultBytes = new Uint8Array(totalBytes);
  13161. const dataBlocksCount = dataBlocks.length;
  13162. // Error-correct and copy data blocks together into a stream of bytes
  13163. for (let j = 0; j < dataBlocksCount; j++) {
  13164. const dataBlock = dataBlocks[j];
  13165. const codewordBytes = dataBlock.getCodewords();
  13166. const numDataCodewords = dataBlock.getNumDataCodewords();
  13167. this.correctErrors(codewordBytes, numDataCodewords);
  13168. for (let i = 0; i < numDataCodewords; i++) {
  13169. // De-interlace data blocks.
  13170. resultBytes[i * dataBlocksCount + j] = codewordBytes[i];
  13171. }
  13172. }
  13173. // Decode the contents of that stream of bytes
  13174. return DecodedBitStreamParser.decode(resultBytes);
  13175. }
  13176. /**
  13177. * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
  13178. * correct the errors in-place using Reed-Solomon error correction.</p>
  13179. *
  13180. * @param codewordBytes data and error correction codewords
  13181. * @param numDataCodewords number of codewords that are data bytes
  13182. * @throws ChecksumException if error correction fails
  13183. */
  13184. correctErrors(codewordBytes, numDataCodewords) {
  13185. // const numCodewords = codewordBytes.length;
  13186. // First read into an array of ints
  13187. const codewordsInts = new Int32Array(codewordBytes);
  13188. // for (let i = 0; i < numCodewords; i++) {
  13189. // codewordsInts[i] = codewordBytes[i] & 0xFF;
  13190. // }
  13191. try {
  13192. this.rsDecoder.decode(codewordsInts, codewordBytes.length - numDataCodewords);
  13193. }
  13194. catch (ignored /* ReedSolomonException */) {
  13195. throw new ChecksumException();
  13196. }
  13197. // Copy back into array of bytes -- only need to worry about the bytes that were data
  13198. // We don't care about errors in the error-correction codewords
  13199. for (let i = 0; i < numDataCodewords; i++) {
  13200. codewordBytes[i] = codewordsInts[i];
  13201. }
  13202. }
  13203. }
  13204. /*
  13205. * Copyright 2008 ZXing authors
  13206. *
  13207. * Licensed under the Apache License, Version 2.0 (the "License");
  13208. * you may not use this file except in compliance with the License.
  13209. * You may obtain a copy of the License at
  13210. *
  13211. * http://www.apache.org/licenses/LICENSE-2.0
  13212. *
  13213. * Unless required by applicable law or agreed to in writing, software
  13214. * distributed under the License is distributed on an "AS IS" BASIS,
  13215. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13216. * See the License for the specific language governing permissions and
  13217. * limitations under the License.
  13218. */
  13219. /**
  13220. * <p>Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code
  13221. * is rotated or skewed, or partially obscured.</p>
  13222. *
  13223. * @author Sean Owen
  13224. */
  13225. class Detector$1 {
  13226. constructor(image) {
  13227. this.image = image;
  13228. this.rectangleDetector = new WhiteRectangleDetector(this.image);
  13229. }
  13230. /**
  13231. * <p>Detects a Data Matrix Code in an image.</p>
  13232. *
  13233. * @return {@link DetectorResult} encapsulating results of detecting a Data Matrix Code
  13234. * @throws NotFoundException if no Data Matrix Code can be found
  13235. */
  13236. detect() {
  13237. const cornerPoints = this.rectangleDetector.detect();
  13238. let points = this.detectSolid1(cornerPoints);
  13239. points = this.detectSolid2(points);
  13240. points[3] = this.correctTopRight(points);
  13241. if (!points[3]) {
  13242. throw new NotFoundException();
  13243. }
  13244. points = this.shiftToModuleCenter(points);
  13245. const topLeft = points[0];
  13246. const bottomLeft = points[1];
  13247. const bottomRight = points[2];
  13248. const topRight = points[3];
  13249. let dimensionTop = this.transitionsBetween(topLeft, topRight) + 1;
  13250. let dimensionRight = this.transitionsBetween(bottomRight, topRight) + 1;
  13251. if ((dimensionTop & 0x01) === 1) {
  13252. dimensionTop += 1;
  13253. }
  13254. if ((dimensionRight & 0x01) === 1) {
  13255. dimensionRight += 1;
  13256. }
  13257. if (4 * dimensionTop < 7 * dimensionRight && 4 * dimensionRight < 7 * dimensionTop) {
  13258. // The matrix is square
  13259. dimensionTop = dimensionRight = Math.max(dimensionTop, dimensionRight);
  13260. }
  13261. let bits = Detector$1.sampleGrid(this.image, topLeft, bottomLeft, bottomRight, topRight, dimensionTop, dimensionRight);
  13262. return new DetectorResult(bits, [topLeft, bottomLeft, bottomRight, topRight]);
  13263. }
  13264. static shiftPoint(point, to, div) {
  13265. let x = (to.getX() - point.getX()) / (div + 1);
  13266. let y = (to.getY() - point.getY()) / (div + 1);
  13267. return new ResultPoint(point.getX() + x, point.getY() + y);
  13268. }
  13269. static moveAway(point, fromX, fromY) {
  13270. let x = point.getX();
  13271. let y = point.getY();
  13272. if (x < fromX) {
  13273. x -= 1;
  13274. }
  13275. else {
  13276. x += 1;
  13277. }
  13278. if (y < fromY) {
  13279. y -= 1;
  13280. }
  13281. else {
  13282. y += 1;
  13283. }
  13284. return new ResultPoint(x, y);
  13285. }
  13286. /**
  13287. * Detect a solid side which has minimum transition.
  13288. */
  13289. detectSolid1(cornerPoints) {
  13290. // 0 2
  13291. // 1 3
  13292. let pointA = cornerPoints[0];
  13293. let pointB = cornerPoints[1];
  13294. let pointC = cornerPoints[3];
  13295. let pointD = cornerPoints[2];
  13296. let trAB = this.transitionsBetween(pointA, pointB);
  13297. let trBC = this.transitionsBetween(pointB, pointC);
  13298. let trCD = this.transitionsBetween(pointC, pointD);
  13299. let trDA = this.transitionsBetween(pointD, pointA);
  13300. // 0..3
  13301. // : :
  13302. // 1--2
  13303. let min = trAB;
  13304. let points = [pointD, pointA, pointB, pointC];
  13305. if (min > trBC) {
  13306. min = trBC;
  13307. points[0] = pointA;
  13308. points[1] = pointB;
  13309. points[2] = pointC;
  13310. points[3] = pointD;
  13311. }
  13312. if (min > trCD) {
  13313. min = trCD;
  13314. points[0] = pointB;
  13315. points[1] = pointC;
  13316. points[2] = pointD;
  13317. points[3] = pointA;
  13318. }
  13319. if (min > trDA) {
  13320. points[0] = pointC;
  13321. points[1] = pointD;
  13322. points[2] = pointA;
  13323. points[3] = pointB;
  13324. }
  13325. return points;
  13326. }
  13327. /**
  13328. * Detect a second solid side next to first solid side.
  13329. */
  13330. detectSolid2(points) {
  13331. // A..D
  13332. // : :
  13333. // B--C
  13334. let pointA = points[0];
  13335. let pointB = points[1];
  13336. let pointC = points[2];
  13337. let pointD = points[3];
  13338. // Transition detection on the edge is not stable.
  13339. // To safely detect, shift the points to the module center.
  13340. let tr = this.transitionsBetween(pointA, pointD);
  13341. let pointBs = Detector$1.shiftPoint(pointB, pointC, (tr + 1) * 4);
  13342. let pointCs = Detector$1.shiftPoint(pointC, pointB, (tr + 1) * 4);
  13343. let trBA = this.transitionsBetween(pointBs, pointA);
  13344. let trCD = this.transitionsBetween(pointCs, pointD);
  13345. // 0..3
  13346. // | :
  13347. // 1--2
  13348. if (trBA < trCD) {
  13349. // solid sides: A-B-C
  13350. points[0] = pointA;
  13351. points[1] = pointB;
  13352. points[2] = pointC;
  13353. points[3] = pointD;
  13354. }
  13355. else {
  13356. // solid sides: B-C-D
  13357. points[0] = pointB;
  13358. points[1] = pointC;
  13359. points[2] = pointD;
  13360. points[3] = pointA;
  13361. }
  13362. return points;
  13363. }
  13364. /**
  13365. * Calculates the corner position of the white top right module.
  13366. */
  13367. correctTopRight(points) {
  13368. // A..D
  13369. // | :
  13370. // B--C
  13371. let pointA = points[0];
  13372. let pointB = points[1];
  13373. let pointC = points[2];
  13374. let pointD = points[3];
  13375. // shift points for safe transition detection.
  13376. let trTop = this.transitionsBetween(pointA, pointD);
  13377. let trRight = this.transitionsBetween(pointB, pointD);
  13378. let pointAs = Detector$1.shiftPoint(pointA, pointB, (trRight + 1) * 4);
  13379. let pointCs = Detector$1.shiftPoint(pointC, pointB, (trTop + 1) * 4);
  13380. trTop = this.transitionsBetween(pointAs, pointD);
  13381. trRight = this.transitionsBetween(pointCs, pointD);
  13382. let candidate1 = new ResultPoint(pointD.getX() + (pointC.getX() - pointB.getX()) / (trTop + 1), pointD.getY() + (pointC.getY() - pointB.getY()) / (trTop + 1));
  13383. let candidate2 = new ResultPoint(pointD.getX() + (pointA.getX() - pointB.getX()) / (trRight + 1), pointD.getY() + (pointA.getY() - pointB.getY()) / (trRight + 1));
  13384. if (!this.isValid(candidate1)) {
  13385. if (this.isValid(candidate2)) {
  13386. return candidate2;
  13387. }
  13388. return null;
  13389. }
  13390. if (!this.isValid(candidate2)) {
  13391. return candidate1;
  13392. }
  13393. let sumc1 = this.transitionsBetween(pointAs, candidate1) + this.transitionsBetween(pointCs, candidate1);
  13394. let sumc2 = this.transitionsBetween(pointAs, candidate2) + this.transitionsBetween(pointCs, candidate2);
  13395. if (sumc1 > sumc2) {
  13396. return candidate1;
  13397. }
  13398. else {
  13399. return candidate2;
  13400. }
  13401. }
  13402. /**
  13403. * Shift the edge points to the module center.
  13404. */
  13405. shiftToModuleCenter(points) {
  13406. // A..D
  13407. // | :
  13408. // B--C
  13409. let pointA = points[0];
  13410. let pointB = points[1];
  13411. let pointC = points[2];
  13412. let pointD = points[3];
  13413. // calculate pseudo dimensions
  13414. let dimH = this.transitionsBetween(pointA, pointD) + 1;
  13415. let dimV = this.transitionsBetween(pointC, pointD) + 1;
  13416. // shift points for safe dimension detection
  13417. let pointAs = Detector$1.shiftPoint(pointA, pointB, dimV * 4);
  13418. let pointCs = Detector$1.shiftPoint(pointC, pointB, dimH * 4);
  13419. // calculate more precise dimensions
  13420. dimH = this.transitionsBetween(pointAs, pointD) + 1;
  13421. dimV = this.transitionsBetween(pointCs, pointD) + 1;
  13422. if ((dimH & 0x01) === 1) {
  13423. dimH += 1;
  13424. }
  13425. if ((dimV & 0x01) === 1) {
  13426. dimV += 1;
  13427. }
  13428. // WhiteRectangleDetector returns points inside of the rectangle.
  13429. // I want points on the edges.
  13430. let centerX = (pointA.getX() + pointB.getX() + pointC.getX() + pointD.getX()) / 4;
  13431. let centerY = (pointA.getY() + pointB.getY() + pointC.getY() + pointD.getY()) / 4;
  13432. pointA = Detector$1.moveAway(pointA, centerX, centerY);
  13433. pointB = Detector$1.moveAway(pointB, centerX, centerY);
  13434. pointC = Detector$1.moveAway(pointC, centerX, centerY);
  13435. pointD = Detector$1.moveAway(pointD, centerX, centerY);
  13436. let pointBs;
  13437. let pointDs;
  13438. // shift points to the center of each modules
  13439. pointAs = Detector$1.shiftPoint(pointA, pointB, dimV * 4);
  13440. pointAs = Detector$1.shiftPoint(pointAs, pointD, dimH * 4);
  13441. pointBs = Detector$1.shiftPoint(pointB, pointA, dimV * 4);
  13442. pointBs = Detector$1.shiftPoint(pointBs, pointC, dimH * 4);
  13443. pointCs = Detector$1.shiftPoint(pointC, pointD, dimV * 4);
  13444. pointCs = Detector$1.shiftPoint(pointCs, pointB, dimH * 4);
  13445. pointDs = Detector$1.shiftPoint(pointD, pointC, dimV * 4);
  13446. pointDs = Detector$1.shiftPoint(pointDs, pointA, dimH * 4);
  13447. return [pointAs, pointBs, pointCs, pointDs];
  13448. }
  13449. isValid(p) {
  13450. return p.getX() >= 0 && p.getX() < this.image.getWidth() && p.getY() > 0 && p.getY() < this.image.getHeight();
  13451. }
  13452. static sampleGrid(image, topLeft, bottomLeft, bottomRight, topRight, dimensionX, dimensionY) {
  13453. const sampler = GridSamplerInstance.getInstance();
  13454. return sampler.sampleGrid(image, dimensionX, dimensionY, 0.5, 0.5, dimensionX - 0.5, 0.5, dimensionX - 0.5, dimensionY - 0.5, 0.5, dimensionY - 0.5, topLeft.getX(), topLeft.getY(), topRight.getX(), topRight.getY(), bottomRight.getX(), bottomRight.getY(), bottomLeft.getX(), bottomLeft.getY());
  13455. }
  13456. /**
  13457. * Counts the number of black/white transitions between two points, using something like Bresenham's algorithm.
  13458. */
  13459. transitionsBetween(from, to) {
  13460. // See QR Code Detector, sizeOfBlackWhiteBlackRun()
  13461. let fromX = Math.trunc(from.getX());
  13462. let fromY = Math.trunc(from.getY());
  13463. let toX = Math.trunc(to.getX());
  13464. let toY = Math.trunc(to.getY());
  13465. let steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
  13466. if (steep) {
  13467. let temp = fromX;
  13468. fromX = fromY;
  13469. fromY = temp;
  13470. temp = toX;
  13471. toX = toY;
  13472. toY = temp;
  13473. }
  13474. let dx = Math.abs(toX - fromX);
  13475. let dy = Math.abs(toY - fromY);
  13476. let error = -dx / 2;
  13477. let ystep = fromY < toY ? 1 : -1;
  13478. let xstep = fromX < toX ? 1 : -1;
  13479. let transitions = 0;
  13480. let inBlack = this.image.get(steep ? fromY : fromX, steep ? fromX : fromY);
  13481. for (let x = fromX, y = fromY; x !== toX; x += xstep) {
  13482. let isBlack = this.image.get(steep ? y : x, steep ? x : y);
  13483. if (isBlack !== inBlack) {
  13484. transitions++;
  13485. inBlack = isBlack;
  13486. }
  13487. error += dy;
  13488. if (error > 0) {
  13489. if (y === toY) {
  13490. break;
  13491. }
  13492. y += ystep;
  13493. error -= dx;
  13494. }
  13495. }
  13496. return transitions;
  13497. }
  13498. }
  13499. /*
  13500. * Copyright 2007 ZXing authors
  13501. *
  13502. * Licensed under the Apache License, Version 2.0 (the "License");
  13503. * you may not use this file except in compliance with the License.
  13504. * You may obtain a copy of the License at
  13505. *
  13506. * http://www.apache.org/licenses/LICENSE-2.0
  13507. *
  13508. * Unless required by applicable law or agreed to in writing, software
  13509. * distributed under the License is distributed on an "AS IS" BASIS,
  13510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13511. * See the License for the specific language governing permissions and
  13512. * limitations under the License.
  13513. */
  13514. /**
  13515. * This implementation can detect and decode Data Matrix codes in an image.
  13516. *
  13517. * @author bbrown@google.com (Brian Brown)
  13518. */
  13519. class DataMatrixReader {
  13520. constructor() {
  13521. this.decoder = new Decoder$1();
  13522. }
  13523. /**
  13524. * Locates and decodes a Data Matrix code in an image.
  13525. *
  13526. * @return a String representing the content encoded by the Data Matrix code
  13527. * @throws NotFoundException if a Data Matrix code cannot be found
  13528. * @throws FormatException if a Data Matrix code cannot be decoded
  13529. * @throws ChecksumException if error correction fails
  13530. */
  13531. // @Override
  13532. // public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException {
  13533. // return decode(image, null);
  13534. // }
  13535. // @Override
  13536. decode(image, hints = null) {
  13537. let decoderResult;
  13538. let points;
  13539. if (hints != null && hints.has(DecodeHintType$1.PURE_BARCODE)) {
  13540. const bits = DataMatrixReader.extractPureBits(image.getBlackMatrix());
  13541. decoderResult = this.decoder.decode(bits);
  13542. points = DataMatrixReader.NO_POINTS;
  13543. }
  13544. else {
  13545. const detectorResult = new Detector$1(image.getBlackMatrix()).detect();
  13546. decoderResult = this.decoder.decode(detectorResult.getBits());
  13547. points = detectorResult.getPoints();
  13548. }
  13549. const rawBytes = decoderResult.getRawBytes();
  13550. const result = new Result(decoderResult.getText(), rawBytes, 8 * rawBytes.length, points, BarcodeFormat$1.DATA_MATRIX, System.currentTimeMillis());
  13551. const byteSegments = decoderResult.getByteSegments();
  13552. if (byteSegments != null) {
  13553. result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS, byteSegments);
  13554. }
  13555. const ecLevel = decoderResult.getECLevel();
  13556. if (ecLevel != null) {
  13557. result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL, ecLevel);
  13558. }
  13559. return result;
  13560. }
  13561. // @Override
  13562. reset() {
  13563. // do nothing
  13564. }
  13565. /**
  13566. * This method detects a code in a "pure" image -- that is, pure monochrome image
  13567. * which contains only an unrotated, unskewed, image of a code, with some white border
  13568. * around it. This is a specialized method that works exceptionally fast in this special
  13569. * case.
  13570. *
  13571. * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix)
  13572. */
  13573. static extractPureBits(image) {
  13574. const leftTopBlack = image.getTopLeftOnBit();
  13575. const rightBottomBlack = image.getBottomRightOnBit();
  13576. if (leftTopBlack == null || rightBottomBlack == null) {
  13577. throw new NotFoundException();
  13578. }
  13579. const moduleSize = this.moduleSize(leftTopBlack, image);
  13580. let top = leftTopBlack[1];
  13581. const bottom = rightBottomBlack[1];
  13582. let left = leftTopBlack[0];
  13583. const right = rightBottomBlack[0];
  13584. const matrixWidth = (right - left + 1) / moduleSize;
  13585. const matrixHeight = (bottom - top + 1) / moduleSize;
  13586. if (matrixWidth <= 0 || matrixHeight <= 0) {
  13587. throw new NotFoundException();
  13588. }
  13589. // Push in the "border" by half the module width so that we start
  13590. // sampling in the middle of the module. Just in case the image is a
  13591. // little off, this will help recover.
  13592. const nudge = moduleSize / 2;
  13593. top += nudge;
  13594. left += nudge;
  13595. // Now just read off the bits
  13596. const bits = new BitMatrix(matrixWidth, matrixHeight);
  13597. for (let y = 0; y < matrixHeight; y++) {
  13598. const iOffset = top + y * moduleSize;
  13599. for (let x = 0; x < matrixWidth; x++) {
  13600. if (image.get(left + x * moduleSize, iOffset)) {
  13601. bits.set(x, y);
  13602. }
  13603. }
  13604. }
  13605. return bits;
  13606. }
  13607. static moduleSize(leftTopBlack, image) {
  13608. const width = image.getWidth();
  13609. let x = leftTopBlack[0];
  13610. const y = leftTopBlack[1];
  13611. while (x < width && image.get(x, y)) {
  13612. x++;
  13613. }
  13614. if (x === width) {
  13615. throw new NotFoundException();
  13616. }
  13617. const moduleSize = x - leftTopBlack[0];
  13618. if (moduleSize === 0) {
  13619. throw new NotFoundException();
  13620. }
  13621. return moduleSize;
  13622. }
  13623. }
  13624. DataMatrixReader.NO_POINTS = [];
  13625. /**
  13626. * @deprecated Moving to @zxing/browser
  13627. *
  13628. * QR Code reader to use from browser.
  13629. */
  13630. class BrowserDatamatrixCodeReader extends BrowserCodeReader {
  13631. /**
  13632. * Creates an instance of BrowserQRCodeReader.
  13633. * @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
  13634. */
  13635. constructor(timeBetweenScansMillis = 500) {
  13636. super(new DataMatrixReader(), timeBetweenScansMillis);
  13637. }
  13638. }
  13639. /*
  13640. * Copyright 2007 ZXing authors
  13641. *
  13642. * Licensed under the Apache License, Version 2.0 (the "License");
  13643. * you may not use this file except in compliance with the License.
  13644. * You may obtain a copy of the License at
  13645. *
  13646. * http://www.apache.org/licenses/LICENSE-2.0
  13647. *
  13648. * Unless required by applicable law or agreed to in writing, software
  13649. * distributed under the License is distributed on an "AS IS" BASIS,
  13650. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13651. * See the License for the specific language governing permissions and
  13652. * limitations under the License.
  13653. */
  13654. var ErrorCorrectionLevelValues;
  13655. (function (ErrorCorrectionLevelValues) {
  13656. ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["L"] = 0] = "L";
  13657. ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["M"] = 1] = "M";
  13658. ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["Q"] = 2] = "Q";
  13659. ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["H"] = 3] = "H";
  13660. })(ErrorCorrectionLevelValues || (ErrorCorrectionLevelValues = {}));
  13661. /**
  13662. * <p>See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels
  13663. * defined by the QR code standard.</p>
  13664. *
  13665. * @author Sean Owen
  13666. */
  13667. class ErrorCorrectionLevel {
  13668. constructor(value, stringValue, bits /*int*/) {
  13669. this.value = value;
  13670. this.stringValue = stringValue;
  13671. this.bits = bits;
  13672. ErrorCorrectionLevel.FOR_BITS.set(bits, this);
  13673. ErrorCorrectionLevel.FOR_VALUE.set(value, this);
  13674. }
  13675. getValue() {
  13676. return this.value;
  13677. }
  13678. getBits() {
  13679. return this.bits;
  13680. }
  13681. static fromString(s) {
  13682. switch (s) {
  13683. case 'L': return ErrorCorrectionLevel.L;
  13684. case 'M': return ErrorCorrectionLevel.M;
  13685. case 'Q': return ErrorCorrectionLevel.Q;
  13686. case 'H': return ErrorCorrectionLevel.H;
  13687. default: throw new ArgumentException(s + 'not available');
  13688. }
  13689. }
  13690. toString() {
  13691. return this.stringValue;
  13692. }
  13693. equals(o) {
  13694. if (!(o instanceof ErrorCorrectionLevel)) {
  13695. return false;
  13696. }
  13697. const other = o;
  13698. return this.value === other.value;
  13699. }
  13700. /**
  13701. * @param bits int containing the two bits encoding a QR Code's error correction level
  13702. * @return ErrorCorrectionLevel representing the encoded error correction level
  13703. */
  13704. static forBits(bits /*int*/) {
  13705. if (bits < 0 || bits >= ErrorCorrectionLevel.FOR_BITS.size) {
  13706. throw new IllegalArgumentException();
  13707. }
  13708. return ErrorCorrectionLevel.FOR_BITS.get(bits);
  13709. }
  13710. }
  13711. ErrorCorrectionLevel.FOR_BITS = new Map();
  13712. ErrorCorrectionLevel.FOR_VALUE = new Map();
  13713. /** L = ~7% correction */
  13714. ErrorCorrectionLevel.L = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.L, 'L', 0x01);
  13715. /** M = ~15% correction */
  13716. ErrorCorrectionLevel.M = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.M, 'M', 0x00);
  13717. /** Q = ~25% correction */
  13718. ErrorCorrectionLevel.Q = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.Q, 'Q', 0x03);
  13719. /** H = ~30% correction */
  13720. ErrorCorrectionLevel.H = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.H, 'H', 0x02);
  13721. /*
  13722. * Copyright 2007 ZXing authors
  13723. *
  13724. * Licensed under the Apache License, Version 2.0 (the "License");
  13725. * you may not use this file except in compliance with the License.
  13726. * You may obtain a copy of the License at
  13727. *
  13728. * http://www.apache.org/licenses/LICENSE-2.0
  13729. *
  13730. * Unless required by applicable law or agreed to in writing, software
  13731. * distributed under the License is distributed on an "AS IS" BASIS,
  13732. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13733. * See the License for the specific language governing permissions and
  13734. * limitations under the License.
  13735. */
  13736. /**
  13737. * <p>Encapsulates a QR Code's format information, including the data mask used and
  13738. * error correction level.</p>
  13739. *
  13740. * @author Sean Owen
  13741. * @see DataMask
  13742. * @see ErrorCorrectionLevel
  13743. */
  13744. class FormatInformation {
  13745. constructor(formatInfo /*int*/) {
  13746. // Bits 3,4
  13747. this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03);
  13748. // Bottom 3 bits
  13749. this.dataMask = /*(byte) */ (formatInfo & 0x07);
  13750. }
  13751. static numBitsDiffering(a /*int*/, b /*int*/) {
  13752. return Integer.bitCount(a ^ b);
  13753. }
  13754. /**
  13755. * @param maskedFormatInfo1 format info indicator, with mask still applied
  13756. * @param maskedFormatInfo2 second copy of same info; both are checked at the same time
  13757. * to establish best match
  13758. * @return information about the format it specifies, or {@code null}
  13759. * if doesn't seem to match any known pattern
  13760. */
  13761. static decodeFormatInformation(maskedFormatInfo1 /*int*/, maskedFormatInfo2 /*int*/) {
  13762. const formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2);
  13763. if (formatInfo !== null) {
  13764. return formatInfo;
  13765. }
  13766. // Should return null, but, some QR codes apparently
  13767. // do not mask this info. Try again by actually masking the pattern
  13768. // first
  13769. return FormatInformation.doDecodeFormatInformation(maskedFormatInfo1 ^ FormatInformation.FORMAT_INFO_MASK_QR, maskedFormatInfo2 ^ FormatInformation.FORMAT_INFO_MASK_QR);
  13770. }
  13771. static doDecodeFormatInformation(maskedFormatInfo1 /*int*/, maskedFormatInfo2 /*int*/) {
  13772. // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing
  13773. let bestDifference = Number.MAX_SAFE_INTEGER;
  13774. let bestFormatInfo = 0;
  13775. for (const decodeInfo of FormatInformation.FORMAT_INFO_DECODE_LOOKUP) {
  13776. const targetInfo = decodeInfo[0];
  13777. if (targetInfo === maskedFormatInfo1 || targetInfo === maskedFormatInfo2) {
  13778. // Found an exact match
  13779. return new FormatInformation(decodeInfo[1]);
  13780. }
  13781. let bitsDifference = FormatInformation.numBitsDiffering(maskedFormatInfo1, targetInfo);
  13782. if (bitsDifference < bestDifference) {
  13783. bestFormatInfo = decodeInfo[1];
  13784. bestDifference = bitsDifference;
  13785. }
  13786. if (maskedFormatInfo1 !== maskedFormatInfo2) {
  13787. // also try the other option
  13788. bitsDifference = FormatInformation.numBitsDiffering(maskedFormatInfo2, targetInfo);
  13789. if (bitsDifference < bestDifference) {
  13790. bestFormatInfo = decodeInfo[1];
  13791. bestDifference = bitsDifference;
  13792. }
  13793. }
  13794. }
  13795. // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits
  13796. // differing means we found a match
  13797. if (bestDifference <= 3) {
  13798. return new FormatInformation(bestFormatInfo);
  13799. }
  13800. return null;
  13801. }
  13802. getErrorCorrectionLevel() {
  13803. return this.errorCorrectionLevel;
  13804. }
  13805. getDataMask() {
  13806. return this.dataMask;
  13807. }
  13808. /*@Override*/
  13809. hashCode() {
  13810. return (this.errorCorrectionLevel.getBits() << 3) | this.dataMask;
  13811. }
  13812. /*@Override*/
  13813. equals(o) {
  13814. if (!(o instanceof FormatInformation)) {
  13815. return false;
  13816. }
  13817. const other = o;
  13818. return this.errorCorrectionLevel === other.errorCorrectionLevel &&
  13819. this.dataMask === other.dataMask;
  13820. }
  13821. }
  13822. FormatInformation.FORMAT_INFO_MASK_QR = 0x5412;
  13823. /**
  13824. * See ISO 18004:2006, Annex C, Table C.1
  13825. */
  13826. FormatInformation.FORMAT_INFO_DECODE_LOOKUP = [
  13827. Int32Array.from([0x5412, 0x00]),
  13828. Int32Array.from([0x5125, 0x01]),
  13829. Int32Array.from([0x5E7C, 0x02]),
  13830. Int32Array.from([0x5B4B, 0x03]),
  13831. Int32Array.from([0x45F9, 0x04]),
  13832. Int32Array.from([0x40CE, 0x05]),
  13833. Int32Array.from([0x4F97, 0x06]),
  13834. Int32Array.from([0x4AA0, 0x07]),
  13835. Int32Array.from([0x77C4, 0x08]),
  13836. Int32Array.from([0x72F3, 0x09]),
  13837. Int32Array.from([0x7DAA, 0x0A]),
  13838. Int32Array.from([0x789D, 0x0B]),
  13839. Int32Array.from([0x662F, 0x0C]),
  13840. Int32Array.from([0x6318, 0x0D]),
  13841. Int32Array.from([0x6C41, 0x0E]),
  13842. Int32Array.from([0x6976, 0x0F]),
  13843. Int32Array.from([0x1689, 0x10]),
  13844. Int32Array.from([0x13BE, 0x11]),
  13845. Int32Array.from([0x1CE7, 0x12]),
  13846. Int32Array.from([0x19D0, 0x13]),
  13847. Int32Array.from([0x0762, 0x14]),
  13848. Int32Array.from([0x0255, 0x15]),
  13849. Int32Array.from([0x0D0C, 0x16]),
  13850. Int32Array.from([0x083B, 0x17]),
  13851. Int32Array.from([0x355F, 0x18]),
  13852. Int32Array.from([0x3068, 0x19]),
  13853. Int32Array.from([0x3F31, 0x1A]),
  13854. Int32Array.from([0x3A06, 0x1B]),
  13855. Int32Array.from([0x24B4, 0x1C]),
  13856. Int32Array.from([0x2183, 0x1D]),
  13857. Int32Array.from([0x2EDA, 0x1E]),
  13858. Int32Array.from([0x2BED, 0x1F]),
  13859. ];
  13860. /**
  13861. * <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
  13862. * use blocks of differing sizes within one version, so, this encapsulates the parameters for
  13863. * each set of blocks. It also holds the number of error-correction codewords per block since it
  13864. * will be the same across all blocks within one version.</p>
  13865. */
  13866. class ECBlocks$1 {
  13867. constructor(ecCodewordsPerBlock /*int*/, ...ecBlocks) {
  13868. this.ecCodewordsPerBlock = ecCodewordsPerBlock;
  13869. this.ecBlocks = ecBlocks;
  13870. }
  13871. getECCodewordsPerBlock() {
  13872. return this.ecCodewordsPerBlock;
  13873. }
  13874. getNumBlocks() {
  13875. let total = 0;
  13876. const ecBlocks = this.ecBlocks;
  13877. for (const ecBlock of ecBlocks) {
  13878. total += ecBlock.getCount();
  13879. }
  13880. return total;
  13881. }
  13882. getTotalECCodewords() {
  13883. return this.ecCodewordsPerBlock * this.getNumBlocks();
  13884. }
  13885. getECBlocks() {
  13886. return this.ecBlocks;
  13887. }
  13888. }
  13889. /**
  13890. * <p>Encapsulates the parameters for one error-correction block in one symbol version.
  13891. * This includes the number of data codewords, and the number of times a block with these
  13892. * parameters is used consecutively in the QR code version's format.</p>
  13893. */
  13894. class ECB$1 {
  13895. constructor(count /*int*/, dataCodewords /*int*/) {
  13896. this.count = count;
  13897. this.dataCodewords = dataCodewords;
  13898. }
  13899. getCount() {
  13900. return this.count;
  13901. }
  13902. getDataCodewords() {
  13903. return this.dataCodewords;
  13904. }
  13905. }
  13906. /*
  13907. * Copyright 2007 ZXing authors
  13908. *
  13909. * Licensed under the Apache License, Version 2.0 (the "License");
  13910. * you may not use this file except in compliance with the License.
  13911. * You may obtain a copy of the License at
  13912. *
  13913. * http://www.apache.org/licenses/LICENSE-2.0
  13914. *
  13915. * Unless required by applicable law or agreed to in writing, software
  13916. * distributed under the License is distributed on an "AS IS" BASIS,
  13917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13918. * See the License for the specific language governing permissions and
  13919. * limitations under the License.
  13920. */
  13921. /**
  13922. * See ISO 18004:2006 Annex D
  13923. *
  13924. * @author Sean Owen
  13925. */
  13926. class Version$1 {
  13927. constructor(versionNumber /*int*/, alignmentPatternCenters, ...ecBlocks) {
  13928. this.versionNumber = versionNumber;
  13929. this.alignmentPatternCenters = alignmentPatternCenters;
  13930. this.ecBlocks = ecBlocks;
  13931. let total = 0;
  13932. const ecCodewords = ecBlocks[0].getECCodewordsPerBlock();
  13933. const ecbArray = ecBlocks[0].getECBlocks();
  13934. for (const ecBlock of ecbArray) {
  13935. total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords);
  13936. }
  13937. this.totalCodewords = total;
  13938. }
  13939. getVersionNumber() {
  13940. return this.versionNumber;
  13941. }
  13942. getAlignmentPatternCenters() {
  13943. return this.alignmentPatternCenters;
  13944. }
  13945. getTotalCodewords() {
  13946. return this.totalCodewords;
  13947. }
  13948. getDimensionForVersion() {
  13949. return 17 + 4 * this.versionNumber;
  13950. }
  13951. getECBlocksForLevel(ecLevel) {
  13952. return this.ecBlocks[ecLevel.getValue()];
  13953. // TYPESCRIPTPORT: original was using ordinal, and using the order of levels as defined in ErrorCorrectionLevel enum (LMQH)
  13954. // I will use the direct value from ErrorCorrectionLevelValues enum which in typescript goes to a number
  13955. }
  13956. /**
  13957. * <p>Deduces version information purely from QR Code dimensions.</p>
  13958. *
  13959. * @param dimension dimension in modules
  13960. * @return Version for a QR Code of that dimension
  13961. * @throws FormatException if dimension is not 1 mod 4
  13962. */
  13963. static getProvisionalVersionForDimension(dimension /*int*/) {
  13964. if (dimension % 4 !== 1) {
  13965. throw new FormatException();
  13966. }
  13967. try {
  13968. return this.getVersionForNumber((dimension - 17) / 4);
  13969. }
  13970. catch (ignored /*: IllegalArgumentException*/) {
  13971. throw new FormatException();
  13972. }
  13973. }
  13974. static getVersionForNumber(versionNumber /*int*/) {
  13975. if (versionNumber < 1 || versionNumber > 40) {
  13976. throw new IllegalArgumentException();
  13977. }
  13978. return Version$1.VERSIONS[versionNumber - 1];
  13979. }
  13980. static decodeVersionInformation(versionBits /*int*/) {
  13981. let bestDifference = Number.MAX_SAFE_INTEGER;
  13982. let bestVersion = 0;
  13983. for (let i = 0; i < Version$1.VERSION_DECODE_INFO.length; i++) {
  13984. const targetVersion = Version$1.VERSION_DECODE_INFO[i];
  13985. // Do the version info bits match exactly? done.
  13986. if (targetVersion === versionBits) {
  13987. return Version$1.getVersionForNumber(i + 7);
  13988. }
  13989. // Otherwise see if this is the closest to a real version info bit string
  13990. // we have seen so far
  13991. const bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion);
  13992. if (bitsDifference < bestDifference) {
  13993. bestVersion = i + 7;
  13994. bestDifference = bitsDifference;
  13995. }
  13996. }
  13997. // We can tolerate up to 3 bits of error since no two version info codewords will
  13998. // differ in less than 8 bits.
  13999. if (bestDifference <= 3) {
  14000. return Version$1.getVersionForNumber(bestVersion);
  14001. }
  14002. // If we didn't find a close enough match, fail
  14003. return null;
  14004. }
  14005. /**
  14006. * See ISO 18004:2006 Annex E
  14007. */
  14008. buildFunctionPattern() {
  14009. const dimension = this.getDimensionForVersion();
  14010. const bitMatrix = new BitMatrix(dimension);
  14011. // Top left finder pattern + separator + format
  14012. bitMatrix.setRegion(0, 0, 9, 9);
  14013. // Top right finder pattern + separator + format
  14014. bitMatrix.setRegion(dimension - 8, 0, 8, 9);
  14015. // Bottom left finder pattern + separator + format
  14016. bitMatrix.setRegion(0, dimension - 8, 9, 8);
  14017. // Alignment patterns
  14018. const max = this.alignmentPatternCenters.length;
  14019. for (let x = 0; x < max; x++) {
  14020. const i = this.alignmentPatternCenters[x] - 2;
  14021. for (let y = 0; y < max; y++) {
  14022. if ((x === 0 && (y === 0 || y === max - 1)) || (x === max - 1 && y === 0)) {
  14023. // No alignment patterns near the three finder patterns
  14024. continue;
  14025. }
  14026. bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5);
  14027. }
  14028. }
  14029. // Vertical timing pattern
  14030. bitMatrix.setRegion(6, 9, 1, dimension - 17);
  14031. // Horizontal timing pattern
  14032. bitMatrix.setRegion(9, 6, dimension - 17, 1);
  14033. if (this.versionNumber > 6) {
  14034. // Version info, top right
  14035. bitMatrix.setRegion(dimension - 11, 0, 3, 6);
  14036. // Version info, bottom left
  14037. bitMatrix.setRegion(0, dimension - 11, 6, 3);
  14038. }
  14039. return bitMatrix;
  14040. }
  14041. /*@Override*/
  14042. toString() {
  14043. return '' + this.versionNumber;
  14044. }
  14045. }
  14046. /**
  14047. * See ISO 18004:2006 Annex D.
  14048. * Element i represents the raw version bits that specify version i + 7
  14049. */
  14050. Version$1.VERSION_DECODE_INFO = Int32Array.from([
  14051. 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6,
  14052. 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78,
  14053. 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683,
  14054. 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB,
  14055. 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250,
  14056. 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B,
  14057. 0x2542E, 0x26A64, 0x27541, 0x28C69
  14058. ]);
  14059. /**
  14060. * See ISO 18004:2006 6.5.1 Table 9
  14061. */
  14062. Version$1.VERSIONS = [
  14063. new Version$1(1, new Int32Array(0), new ECBlocks$1(7, new ECB$1(1, 19)), new ECBlocks$1(10, new ECB$1(1, 16)), new ECBlocks$1(13, new ECB$1(1, 13)), new ECBlocks$1(17, new ECB$1(1, 9))),
  14064. new Version$1(2, Int32Array.from([6, 18]), new ECBlocks$1(10, new ECB$1(1, 34)), new ECBlocks$1(16, new ECB$1(1, 28)), new ECBlocks$1(22, new ECB$1(1, 22)), new ECBlocks$1(28, new ECB$1(1, 16))),
  14065. new Version$1(3, Int32Array.from([6, 22]), new ECBlocks$1(15, new ECB$1(1, 55)), new ECBlocks$1(26, new ECB$1(1, 44)), new ECBlocks$1(18, new ECB$1(2, 17)), new ECBlocks$1(22, new ECB$1(2, 13))),
  14066. new Version$1(4, Int32Array.from([6, 26]), new ECBlocks$1(20, new ECB$1(1, 80)), new ECBlocks$1(18, new ECB$1(2, 32)), new ECBlocks$1(26, new ECB$1(2, 24)), new ECBlocks$1(16, new ECB$1(4, 9))),
  14067. new Version$1(5, Int32Array.from([6, 30]), new ECBlocks$1(26, new ECB$1(1, 108)), new ECBlocks$1(24, new ECB$1(2, 43)), new ECBlocks$1(18, new ECB$1(2, 15), new ECB$1(2, 16)), new ECBlocks$1(22, new ECB$1(2, 11), new ECB$1(2, 12))),
  14068. new Version$1(6, Int32Array.from([6, 34]), new ECBlocks$1(18, new ECB$1(2, 68)), new ECBlocks$1(16, new ECB$1(4, 27)), new ECBlocks$1(24, new ECB$1(4, 19)), new ECBlocks$1(28, new ECB$1(4, 15))),
  14069. new Version$1(7, Int32Array.from([6, 22, 38]), new ECBlocks$1(20, new ECB$1(2, 78)), new ECBlocks$1(18, new ECB$1(4, 31)), new ECBlocks$1(18, new ECB$1(2, 14), new ECB$1(4, 15)), new ECBlocks$1(26, new ECB$1(4, 13), new ECB$1(1, 14))),
  14070. new Version$1(8, Int32Array.from([6, 24, 42]), new ECBlocks$1(24, new ECB$1(2, 97)), new ECBlocks$1(22, new ECB$1(2, 38), new ECB$1(2, 39)), new ECBlocks$1(22, new ECB$1(4, 18), new ECB$1(2, 19)), new ECBlocks$1(26, new ECB$1(4, 14), new ECB$1(2, 15))),
  14071. new Version$1(9, Int32Array.from([6, 26, 46]), new ECBlocks$1(30, new ECB$1(2, 116)), new ECBlocks$1(22, new ECB$1(3, 36), new ECB$1(2, 37)), new ECBlocks$1(20, new ECB$1(4, 16), new ECB$1(4, 17)), new ECBlocks$1(24, new ECB$1(4, 12), new ECB$1(4, 13))),
  14072. new Version$1(10, Int32Array.from([6, 28, 50]), new ECBlocks$1(18, new ECB$1(2, 68), new ECB$1(2, 69)), new ECBlocks$1(26, new ECB$1(4, 43), new ECB$1(1, 44)), new ECBlocks$1(24, new ECB$1(6, 19), new ECB$1(2, 20)), new ECBlocks$1(28, new ECB$1(6, 15), new ECB$1(2, 16))),
  14073. new Version$1(11, Int32Array.from([6, 30, 54]), new ECBlocks$1(20, new ECB$1(4, 81)), new ECBlocks$1(30, new ECB$1(1, 50), new ECB$1(4, 51)), new ECBlocks$1(28, new ECB$1(4, 22), new ECB$1(4, 23)), new ECBlocks$1(24, new ECB$1(3, 12), new ECB$1(8, 13))),
  14074. new Version$1(12, Int32Array.from([6, 32, 58]), new ECBlocks$1(24, new ECB$1(2, 92), new ECB$1(2, 93)), new ECBlocks$1(22, new ECB$1(6, 36), new ECB$1(2, 37)), new ECBlocks$1(26, new ECB$1(4, 20), new ECB$1(6, 21)), new ECBlocks$1(28, new ECB$1(7, 14), new ECB$1(4, 15))),
  14075. new Version$1(13, Int32Array.from([6, 34, 62]), new ECBlocks$1(26, new ECB$1(4, 107)), new ECBlocks$1(22, new ECB$1(8, 37), new ECB$1(1, 38)), new ECBlocks$1(24, new ECB$1(8, 20), new ECB$1(4, 21)), new ECBlocks$1(22, new ECB$1(12, 11), new ECB$1(4, 12))),
  14076. new Version$1(14, Int32Array.from([6, 26, 46, 66]), new ECBlocks$1(30, new ECB$1(3, 115), new ECB$1(1, 116)), new ECBlocks$1(24, new ECB$1(4, 40), new ECB$1(5, 41)), new ECBlocks$1(20, new ECB$1(11, 16), new ECB$1(5, 17)), new ECBlocks$1(24, new ECB$1(11, 12), new ECB$1(5, 13))),
  14077. new Version$1(15, Int32Array.from([6, 26, 48, 70]), new ECBlocks$1(22, new ECB$1(5, 87), new ECB$1(1, 88)), new ECBlocks$1(24, new ECB$1(5, 41), new ECB$1(5, 42)), new ECBlocks$1(30, new ECB$1(5, 24), new ECB$1(7, 25)), new ECBlocks$1(24, new ECB$1(11, 12), new ECB$1(7, 13))),
  14078. new Version$1(16, Int32Array.from([6, 26, 50, 74]), new ECBlocks$1(24, new ECB$1(5, 98), new ECB$1(1, 99)), new ECBlocks$1(28, new ECB$1(7, 45), new ECB$1(3, 46)), new ECBlocks$1(24, new ECB$1(15, 19), new ECB$1(2, 20)), new ECBlocks$1(30, new ECB$1(3, 15), new ECB$1(13, 16))),
  14079. new Version$1(17, Int32Array.from([6, 30, 54, 78]), new ECBlocks$1(28, new ECB$1(1, 107), new ECB$1(5, 108)), new ECBlocks$1(28, new ECB$1(10, 46), new ECB$1(1, 47)), new ECBlocks$1(28, new ECB$1(1, 22), new ECB$1(15, 23)), new ECBlocks$1(28, new ECB$1(2, 14), new ECB$1(17, 15))),
  14080. new Version$1(18, Int32Array.from([6, 30, 56, 82]), new ECBlocks$1(30, new ECB$1(5, 120), new ECB$1(1, 121)), new ECBlocks$1(26, new ECB$1(9, 43), new ECB$1(4, 44)), new ECBlocks$1(28, new ECB$1(17, 22), new ECB$1(1, 23)), new ECBlocks$1(28, new ECB$1(2, 14), new ECB$1(19, 15))),
  14081. new Version$1(19, Int32Array.from([6, 30, 58, 86]), new ECBlocks$1(28, new ECB$1(3, 113), new ECB$1(4, 114)), new ECBlocks$1(26, new ECB$1(3, 44), new ECB$1(11, 45)), new ECBlocks$1(26, new ECB$1(17, 21), new ECB$1(4, 22)), new ECBlocks$1(26, new ECB$1(9, 13), new ECB$1(16, 14))),
  14082. new Version$1(20, Int32Array.from([6, 34, 62, 90]), new ECBlocks$1(28, new ECB$1(3, 107), new ECB$1(5, 108)), new ECBlocks$1(26, new ECB$1(3, 41), new ECB$1(13, 42)), new ECBlocks$1(30, new ECB$1(15, 24), new ECB$1(5, 25)), new ECBlocks$1(28, new ECB$1(15, 15), new ECB$1(10, 16))),
  14083. new Version$1(21, Int32Array.from([6, 28, 50, 72, 94]), new ECBlocks$1(28, new ECB$1(4, 116), new ECB$1(4, 117)), new ECBlocks$1(26, new ECB$1(17, 42)), new ECBlocks$1(28, new ECB$1(17, 22), new ECB$1(6, 23)), new ECBlocks$1(30, new ECB$1(19, 16), new ECB$1(6, 17))),
  14084. new Version$1(22, Int32Array.from([6, 26, 50, 74, 98]), new ECBlocks$1(28, new ECB$1(2, 111), new ECB$1(7, 112)), new ECBlocks$1(28, new ECB$1(17, 46)), new ECBlocks$1(30, new ECB$1(7, 24), new ECB$1(16, 25)), new ECBlocks$1(24, new ECB$1(34, 13))),
  14085. new Version$1(23, Int32Array.from([6, 30, 54, 78, 102]), new ECBlocks$1(30, new ECB$1(4, 121), new ECB$1(5, 122)), new ECBlocks$1(28, new ECB$1(4, 47), new ECB$1(14, 48)), new ECBlocks$1(30, new ECB$1(11, 24), new ECB$1(14, 25)), new ECBlocks$1(30, new ECB$1(16, 15), new ECB$1(14, 16))),
  14086. new Version$1(24, Int32Array.from([6, 28, 54, 80, 106]), new ECBlocks$1(30, new ECB$1(6, 117), new ECB$1(4, 118)), new ECBlocks$1(28, new ECB$1(6, 45), new ECB$1(14, 46)), new ECBlocks$1(30, new ECB$1(11, 24), new ECB$1(16, 25)), new ECBlocks$1(30, new ECB$1(30, 16), new ECB$1(2, 17))),
  14087. new Version$1(25, Int32Array.from([6, 32, 58, 84, 110]), new ECBlocks$1(26, new ECB$1(8, 106), new ECB$1(4, 107)), new ECBlocks$1(28, new ECB$1(8, 47), new ECB$1(13, 48)), new ECBlocks$1(30, new ECB$1(7, 24), new ECB$1(22, 25)), new ECBlocks$1(30, new ECB$1(22, 15), new ECB$1(13, 16))),
  14088. new Version$1(26, Int32Array.from([6, 30, 58, 86, 114]), new ECBlocks$1(28, new ECB$1(10, 114), new ECB$1(2, 115)), new ECBlocks$1(28, new ECB$1(19, 46), new ECB$1(4, 47)), new ECBlocks$1(28, new ECB$1(28, 22), new ECB$1(6, 23)), new ECBlocks$1(30, new ECB$1(33, 16), new ECB$1(4, 17))),
  14089. new Version$1(27, Int32Array.from([6, 34, 62, 90, 118]), new ECBlocks$1(30, new ECB$1(8, 122), new ECB$1(4, 123)), new ECBlocks$1(28, new ECB$1(22, 45), new ECB$1(3, 46)), new ECBlocks$1(30, new ECB$1(8, 23), new ECB$1(26, 24)), new ECBlocks$1(30, new ECB$1(12, 15), new ECB$1(28, 16))),
  14090. new Version$1(28, Int32Array.from([6, 26, 50, 74, 98, 122]), new ECBlocks$1(30, new ECB$1(3, 117), new ECB$1(10, 118)), new ECBlocks$1(28, new ECB$1(3, 45), new ECB$1(23, 46)), new ECBlocks$1(30, new ECB$1(4, 24), new ECB$1(31, 25)), new ECBlocks$1(30, new ECB$1(11, 15), new ECB$1(31, 16))),
  14091. new Version$1(29, Int32Array.from([6, 30, 54, 78, 102, 126]), new ECBlocks$1(30, new ECB$1(7, 116), new ECB$1(7, 117)), new ECBlocks$1(28, new ECB$1(21, 45), new ECB$1(7, 46)), new ECBlocks$1(30, new ECB$1(1, 23), new ECB$1(37, 24)), new ECBlocks$1(30, new ECB$1(19, 15), new ECB$1(26, 16))),
  14092. new Version$1(30, Int32Array.from([6, 26, 52, 78, 104, 130]), new ECBlocks$1(30, new ECB$1(5, 115), new ECB$1(10, 116)), new ECBlocks$1(28, new ECB$1(19, 47), new ECB$1(10, 48)), new ECBlocks$1(30, new ECB$1(15, 24), new ECB$1(25, 25)), new ECBlocks$1(30, new ECB$1(23, 15), new ECB$1(25, 16))),
  14093. new Version$1(31, Int32Array.from([6, 30, 56, 82, 108, 134]), new ECBlocks$1(30, new ECB$1(13, 115), new ECB$1(3, 116)), new ECBlocks$1(28, new ECB$1(2, 46), new ECB$1(29, 47)), new ECBlocks$1(30, new ECB$1(42, 24), new ECB$1(1, 25)), new ECBlocks$1(30, new ECB$1(23, 15), new ECB$1(28, 16))),
  14094. new Version$1(32, Int32Array.from([6, 34, 60, 86, 112, 138]), new ECBlocks$1(30, new ECB$1(17, 115)), new ECBlocks$1(28, new ECB$1(10, 46), new ECB$1(23, 47)), new ECBlocks$1(30, new ECB$1(10, 24), new ECB$1(35, 25)), new ECBlocks$1(30, new ECB$1(19, 15), new ECB$1(35, 16))),
  14095. new Version$1(33, Int32Array.from([6, 30, 58, 86, 114, 142]), new ECBlocks$1(30, new ECB$1(17, 115), new ECB$1(1, 116)), new ECBlocks$1(28, new ECB$1(14, 46), new ECB$1(21, 47)), new ECBlocks$1(30, new ECB$1(29, 24), new ECB$1(19, 25)), new ECBlocks$1(30, new ECB$1(11, 15), new ECB$1(46, 16))),
  14096. new Version$1(34, Int32Array.from([6, 34, 62, 90, 118, 146]), new ECBlocks$1(30, new ECB$1(13, 115), new ECB$1(6, 116)), new ECBlocks$1(28, new ECB$1(14, 46), new ECB$1(23, 47)), new ECBlocks$1(30, new ECB$1(44, 24), new ECB$1(7, 25)), new ECBlocks$1(30, new ECB$1(59, 16), new ECB$1(1, 17))),
  14097. new Version$1(35, Int32Array.from([6, 30, 54, 78, 102, 126, 150]), new ECBlocks$1(30, new ECB$1(12, 121), new ECB$1(7, 122)), new ECBlocks$1(28, new ECB$1(12, 47), new ECB$1(26, 48)), new ECBlocks$1(30, new ECB$1(39, 24), new ECB$1(14, 25)), new ECBlocks$1(30, new ECB$1(22, 15), new ECB$1(41, 16))),
  14098. new Version$1(36, Int32Array.from([6, 24, 50, 76, 102, 128, 154]), new ECBlocks$1(30, new ECB$1(6, 121), new ECB$1(14, 122)), new ECBlocks$1(28, new ECB$1(6, 47), new ECB$1(34, 48)), new ECBlocks$1(30, new ECB$1(46, 24), new ECB$1(10, 25)), new ECBlocks$1(30, new ECB$1(2, 15), new ECB$1(64, 16))),
  14099. new Version$1(37, Int32Array.from([6, 28, 54, 80, 106, 132, 158]), new ECBlocks$1(30, new ECB$1(17, 122), new ECB$1(4, 123)), new ECBlocks$1(28, new ECB$1(29, 46), new ECB$1(14, 47)), new ECBlocks$1(30, new ECB$1(49, 24), new ECB$1(10, 25)), new ECBlocks$1(30, new ECB$1(24, 15), new ECB$1(46, 16))),
  14100. new Version$1(38, Int32Array.from([6, 32, 58, 84, 110, 136, 162]), new ECBlocks$1(30, new ECB$1(4, 122), new ECB$1(18, 123)), new ECBlocks$1(28, new ECB$1(13, 46), new ECB$1(32, 47)), new ECBlocks$1(30, new ECB$1(48, 24), new ECB$1(14, 25)), new ECBlocks$1(30, new ECB$1(42, 15), new ECB$1(32, 16))),
  14101. new Version$1(39, Int32Array.from([6, 26, 54, 82, 110, 138, 166]), new ECBlocks$1(30, new ECB$1(20, 117), new ECB$1(4, 118)), new ECBlocks$1(28, new ECB$1(40, 47), new ECB$1(7, 48)), new ECBlocks$1(30, new ECB$1(43, 24), new ECB$1(22, 25)), new ECBlocks$1(30, new ECB$1(10, 15), new ECB$1(67, 16))),
  14102. new Version$1(40, Int32Array.from([6, 30, 58, 86, 114, 142, 170]), new ECBlocks$1(30, new ECB$1(19, 118), new ECB$1(6, 119)), new ECBlocks$1(28, new ECB$1(18, 47), new ECB$1(31, 48)), new ECBlocks$1(30, new ECB$1(34, 24), new ECB$1(34, 25)), new ECBlocks$1(30, new ECB$1(20, 15), new ECB$1(61, 16)))
  14103. ];
  14104. /*
  14105. * Copyright 2007 ZXing authors
  14106. *
  14107. * Licensed under the Apache License, Version 2.0 (the "License");
  14108. * you may not use this file except in compliance with the License.
  14109. * You may obtain a copy of the License at
  14110. *
  14111. * http://www.apache.org/licenses/LICENSE-2.0
  14112. *
  14113. * Unless required by applicable law or agreed to in writing, software
  14114. * distributed under the License is distributed on an "AS IS" BASIS,
  14115. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14116. * See the License for the specific language governing permissions and
  14117. * limitations under the License.
  14118. */
  14119. var DataMaskValues;
  14120. (function (DataMaskValues) {
  14121. DataMaskValues[DataMaskValues["DATA_MASK_000"] = 0] = "DATA_MASK_000";
  14122. DataMaskValues[DataMaskValues["DATA_MASK_001"] = 1] = "DATA_MASK_001";
  14123. DataMaskValues[DataMaskValues["DATA_MASK_010"] = 2] = "DATA_MASK_010";
  14124. DataMaskValues[DataMaskValues["DATA_MASK_011"] = 3] = "DATA_MASK_011";
  14125. DataMaskValues[DataMaskValues["DATA_MASK_100"] = 4] = "DATA_MASK_100";
  14126. DataMaskValues[DataMaskValues["DATA_MASK_101"] = 5] = "DATA_MASK_101";
  14127. DataMaskValues[DataMaskValues["DATA_MASK_110"] = 6] = "DATA_MASK_110";
  14128. DataMaskValues[DataMaskValues["DATA_MASK_111"] = 7] = "DATA_MASK_111";
  14129. })(DataMaskValues || (DataMaskValues = {}));
  14130. /**
  14131. * <p>Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations
  14132. * of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix,
  14133. * including areas used for finder patterns, timing patterns, etc. These areas should be unused
  14134. * after the point they are unmasked anyway.</p>
  14135. *
  14136. * <p>Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position
  14137. * and j is row position. In fact, as the text says, i is row position and j is column position.</p>
  14138. *
  14139. * @author Sean Owen
  14140. */
  14141. class DataMask {
  14142. // See ISO 18004:2006 6.8.1
  14143. constructor(value, isMasked) {
  14144. this.value = value;
  14145. this.isMasked = isMasked;
  14146. }
  14147. // End of enum constants.
  14148. /**
  14149. * <p>Implementations of this method reverse the data masking process applied to a QR Code and
  14150. * make its bits ready to read.</p>
  14151. *
  14152. * @param bits representation of QR Code bits
  14153. * @param dimension dimension of QR Code, represented by bits, being unmasked
  14154. */
  14155. unmaskBitMatrix(bits, dimension /*int*/) {
  14156. for (let i = 0; i < dimension; i++) {
  14157. for (let j = 0; j < dimension; j++) {
  14158. if (this.isMasked(i, j)) {
  14159. bits.flip(j, i);
  14160. }
  14161. }
  14162. }
  14163. }
  14164. }
  14165. DataMask.values = new Map([
  14166. /**
  14167. * 000: mask bits for which (x + y) mod 2 == 0
  14168. */
  14169. [DataMaskValues.DATA_MASK_000, new DataMask(DataMaskValues.DATA_MASK_000, (i /*int*/, j /*int*/) => { return ((i + j) & 0x01) === 0; })],
  14170. /**
  14171. * 001: mask bits for which x mod 2 == 0
  14172. */
  14173. [DataMaskValues.DATA_MASK_001, new DataMask(DataMaskValues.DATA_MASK_001, (i /*int*/, j /*int*/) => { return (i & 0x01) === 0; })],
  14174. /**
  14175. * 010: mask bits for which y mod 3 == 0
  14176. */
  14177. [DataMaskValues.DATA_MASK_010, new DataMask(DataMaskValues.DATA_MASK_010, (i /*int*/, j /*int*/) => { return j % 3 === 0; })],
  14178. /**
  14179. * 011: mask bits for which (x + y) mod 3 == 0
  14180. */
  14181. [DataMaskValues.DATA_MASK_011, new DataMask(DataMaskValues.DATA_MASK_011, (i /*int*/, j /*int*/) => { return (i + j) % 3 === 0; })],
  14182. /**
  14183. * 100: mask bits for which (x/2 + y/3) mod 2 == 0
  14184. */
  14185. [DataMaskValues.DATA_MASK_100, new DataMask(DataMaskValues.DATA_MASK_100, (i /*int*/, j /*int*/) => { return ((Math.floor(i / 2) + Math.floor(j / 3)) & 0x01) === 0; })],
  14186. /**
  14187. * 101: mask bits for which xy mod 2 + xy mod 3 == 0
  14188. * equivalently, such that xy mod 6 == 0
  14189. */
  14190. [DataMaskValues.DATA_MASK_101, new DataMask(DataMaskValues.DATA_MASK_101, (i /*int*/, j /*int*/) => { return (i * j) % 6 === 0; })],
  14191. /**
  14192. * 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0
  14193. * equivalently, such that xy mod 6 < 3
  14194. */
  14195. [DataMaskValues.DATA_MASK_110, new DataMask(DataMaskValues.DATA_MASK_110, (i /*int*/, j /*int*/) => { return ((i * j) % 6) < 3; })],
  14196. /**
  14197. * 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0
  14198. * equivalently, such that (x + y + xy mod 3) mod 2 == 0
  14199. */
  14200. [DataMaskValues.DATA_MASK_111, new DataMask(DataMaskValues.DATA_MASK_111, (i /*int*/, j /*int*/) => { return ((i + j + ((i * j) % 3)) & 0x01) === 0; })],
  14201. ]);
  14202. /*
  14203. * Copyright 2007 ZXing authors
  14204. *
  14205. * Licensed under the Apache License, Version 2.0 (the "License");
  14206. * you may not use this file except in compliance with the License.
  14207. * You may obtain a copy of the License at
  14208. *
  14209. * http://www.apache.org/licenses/LICENSE-2.0
  14210. *
  14211. * Unless required by applicable law or agreed to in writing, software
  14212. * distributed under the License is distributed on an "AS IS" BASIS,
  14213. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14214. * See the License for the specific language governing permissions and
  14215. * limitations under the License.
  14216. */
  14217. /**
  14218. * @author Sean Owen
  14219. */
  14220. class BitMatrixParser$1 {
  14221. /**
  14222. * @param bitMatrix {@link BitMatrix} to parse
  14223. * @throws FormatException if dimension is not >= 21 and 1 mod 4
  14224. */
  14225. constructor(bitMatrix) {
  14226. const dimension = bitMatrix.getHeight();
  14227. if (dimension < 21 || (dimension & 0x03) !== 1) {
  14228. throw new FormatException();
  14229. }
  14230. this.bitMatrix = bitMatrix;
  14231. }
  14232. /**
  14233. * <p>Reads format information from one of its two locations within the QR Code.</p>
  14234. *
  14235. * @return {@link FormatInformation} encapsulating the QR Code's format info
  14236. * @throws FormatException if both format information locations cannot be parsed as
  14237. * the valid encoding of format information
  14238. */
  14239. readFormatInformation() {
  14240. if (this.parsedFormatInfo !== null && this.parsedFormatInfo !== undefined) {
  14241. return this.parsedFormatInfo;
  14242. }
  14243. // Read top-left format info bits
  14244. let formatInfoBits1 = 0;
  14245. for (let i = 0; i < 6; i++) {
  14246. formatInfoBits1 = this.copyBit(i, 8, formatInfoBits1);
  14247. }
  14248. // .. and skip a bit in the timing pattern ...
  14249. formatInfoBits1 = this.copyBit(7, 8, formatInfoBits1);
  14250. formatInfoBits1 = this.copyBit(8, 8, formatInfoBits1);
  14251. formatInfoBits1 = this.copyBit(8, 7, formatInfoBits1);
  14252. // .. and skip a bit in the timing pattern ...
  14253. for (let j = 5; j >= 0; j--) {
  14254. formatInfoBits1 = this.copyBit(8, j, formatInfoBits1);
  14255. }
  14256. // Read the top-right/bottom-left pattern too
  14257. const dimension = this.bitMatrix.getHeight();
  14258. let formatInfoBits2 = 0;
  14259. const jMin = dimension - 7;
  14260. for (let j = dimension - 1; j >= jMin; j--) {
  14261. formatInfoBits2 = this.copyBit(8, j, formatInfoBits2);
  14262. }
  14263. for (let i = dimension - 8; i < dimension; i++) {
  14264. formatInfoBits2 = this.copyBit(i, 8, formatInfoBits2);
  14265. }
  14266. this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits1, formatInfoBits2);
  14267. if (this.parsedFormatInfo !== null) {
  14268. return this.parsedFormatInfo;
  14269. }
  14270. throw new FormatException();
  14271. }
  14272. /**
  14273. * <p>Reads version information from one of its two locations within the QR Code.</p>
  14274. *
  14275. * @return {@link Version} encapsulating the QR Code's version
  14276. * @throws FormatException if both version information locations cannot be parsed as
  14277. * the valid encoding of version information
  14278. */
  14279. readVersion() {
  14280. if (this.parsedVersion !== null && this.parsedVersion !== undefined) {
  14281. return this.parsedVersion;
  14282. }
  14283. const dimension = this.bitMatrix.getHeight();
  14284. const provisionalVersion = Math.floor((dimension - 17) / 4);
  14285. if (provisionalVersion <= 6) {
  14286. return Version$1.getVersionForNumber(provisionalVersion);
  14287. }
  14288. // Read top-right version info: 3 wide by 6 tall
  14289. let versionBits = 0;
  14290. const ijMin = dimension - 11;
  14291. for (let j = 5; j >= 0; j--) {
  14292. for (let i = dimension - 9; i >= ijMin; i--) {
  14293. versionBits = this.copyBit(i, j, versionBits);
  14294. }
  14295. }
  14296. let theParsedVersion = Version$1.decodeVersionInformation(versionBits);
  14297. if (theParsedVersion !== null && theParsedVersion.getDimensionForVersion() === dimension) {
  14298. this.parsedVersion = theParsedVersion;
  14299. return theParsedVersion;
  14300. }
  14301. // Hmm, failed. Try bottom left: 6 wide by 3 tall
  14302. versionBits = 0;
  14303. for (let i = 5; i >= 0; i--) {
  14304. for (let j = dimension - 9; j >= ijMin; j--) {
  14305. versionBits = this.copyBit(i, j, versionBits);
  14306. }
  14307. }
  14308. theParsedVersion = Version$1.decodeVersionInformation(versionBits);
  14309. if (theParsedVersion !== null && theParsedVersion.getDimensionForVersion() === dimension) {
  14310. this.parsedVersion = theParsedVersion;
  14311. return theParsedVersion;
  14312. }
  14313. throw new FormatException();
  14314. }
  14315. copyBit(i /*int*/, j /*int*/, versionBits /*int*/) {
  14316. const bit = this.isMirror ? this.bitMatrix.get(j, i) : this.bitMatrix.get(i, j);
  14317. return bit ? (versionBits << 1) | 0x1 : versionBits << 1;
  14318. }
  14319. /**
  14320. * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
  14321. * correct order in order to reconstruct the codewords bytes contained within the
  14322. * QR Code.</p>
  14323. *
  14324. * @return bytes encoded within the QR Code
  14325. * @throws FormatException if the exact number of bytes expected is not read
  14326. */
  14327. readCodewords() {
  14328. const formatInfo = this.readFormatInformation();
  14329. const version = this.readVersion();
  14330. // Get the data mask for the format used in this QR Code. This will exclude
  14331. // some bits from reading as we wind through the bit matrix.
  14332. const dataMask = DataMask.values.get(formatInfo.getDataMask());
  14333. const dimension = this.bitMatrix.getHeight();
  14334. dataMask.unmaskBitMatrix(this.bitMatrix, dimension);
  14335. const functionPattern = version.buildFunctionPattern();
  14336. let readingUp = true;
  14337. const result = new Uint8Array(version.getTotalCodewords());
  14338. let resultOffset = 0;
  14339. let currentByte = 0;
  14340. let bitsRead = 0;
  14341. // Read columns in pairs, from right to left
  14342. for (let j = dimension - 1; j > 0; j -= 2) {
  14343. if (j === 6) {
  14344. // Skip whole column with vertical alignment pattern
  14345. // saves time and makes the other code proceed more cleanly
  14346. j--;
  14347. }
  14348. // Read alternatingly from bottom to top then top to bottom
  14349. for (let count = 0; count < dimension; count++) {
  14350. const i = readingUp ? dimension - 1 - count : count;
  14351. for (let col = 0; col < 2; col++) {
  14352. // Ignore bits covered by the function pattern
  14353. if (!functionPattern.get(j - col, i)) {
  14354. // Read a bit
  14355. bitsRead++;
  14356. currentByte <<= 1;
  14357. if (this.bitMatrix.get(j - col, i)) {
  14358. currentByte |= 1;
  14359. }
  14360. // If we've made a whole byte, save it off
  14361. if (bitsRead === 8) {
  14362. result[resultOffset++] = /*(byte) */ currentByte;
  14363. bitsRead = 0;
  14364. currentByte = 0;
  14365. }
  14366. }
  14367. }
  14368. }
  14369. readingUp = !readingUp; // readingUp ^= true; // readingUp = !readingUp; // switch directions
  14370. }
  14371. if (resultOffset !== version.getTotalCodewords()) {
  14372. throw new FormatException();
  14373. }
  14374. return result;
  14375. }
  14376. /**
  14377. * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state.
  14378. */
  14379. remask() {
  14380. if (this.parsedFormatInfo === null) {
  14381. return; // We have no format information, and have no data mask
  14382. }
  14383. const dataMask = DataMask.values[this.parsedFormatInfo.getDataMask()];
  14384. const dimension = this.bitMatrix.getHeight();
  14385. dataMask.unmaskBitMatrix(this.bitMatrix, dimension);
  14386. }
  14387. /**
  14388. * Prepare the parser for a mirrored operation.
  14389. * This flag has effect only on the {@link #readFormatInformation()} and the
  14390. * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the
  14391. * {@link #mirror()} method should be called.
  14392. *
  14393. * @param mirror Whether to read version and format information mirrored.
  14394. */
  14395. setMirror(isMirror) {
  14396. this.parsedVersion = null;
  14397. this.parsedFormatInfo = null;
  14398. this.isMirror = isMirror;
  14399. }
  14400. /** Mirror the bit matrix in order to attempt a second reading. */
  14401. mirror() {
  14402. const bitMatrix = this.bitMatrix;
  14403. for (let x = 0, width = bitMatrix.getWidth(); x < width; x++) {
  14404. for (let y = x + 1, height = bitMatrix.getHeight(); y < height; y++) {
  14405. if (bitMatrix.get(x, y) !== bitMatrix.get(y, x)) {
  14406. bitMatrix.flip(y, x);
  14407. bitMatrix.flip(x, y);
  14408. }
  14409. }
  14410. }
  14411. }
  14412. }
  14413. /*
  14414. * Copyright 2007 ZXing authors
  14415. *
  14416. * Licensed under the Apache License, Version 2.0 (the "License");
  14417. * you may not use this file except in compliance with the License.
  14418. * You may obtain a copy of the License at
  14419. *
  14420. * http://www.apache.org/licenses/LICENSE-2.0
  14421. *
  14422. * Unless required by applicable law or agreed to in writing, software
  14423. * distributed under the License is distributed on an "AS IS" BASIS,
  14424. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14425. * See the License for the specific language governing permissions and
  14426. * limitations under the License.
  14427. */
  14428. /**
  14429. * <p>Encapsulates a block of data within a QR Code. QR Codes may split their data into
  14430. * multiple blocks, each of which is a unit of data and error-correction codewords. Each
  14431. * is represented by an instance of this class.</p>
  14432. *
  14433. * @author Sean Owen
  14434. */
  14435. class DataBlock$1 {
  14436. constructor(numDataCodewords /*int*/, codewords) {
  14437. this.numDataCodewords = numDataCodewords;
  14438. this.codewords = codewords;
  14439. }
  14440. /**
  14441. * <p>When QR Codes use multiple data blocks, they are actually interleaved.
  14442. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
  14443. * method will separate the data into original blocks.</p>
  14444. *
  14445. * @param rawCodewords bytes as read directly from the QR Code
  14446. * @param version version of the QR Code
  14447. * @param ecLevel error-correction level of the QR Code
  14448. * @return DataBlocks containing original bytes, "de-interleaved" from representation in the
  14449. * QR Code
  14450. */
  14451. static getDataBlocks(rawCodewords, version, ecLevel) {
  14452. if (rawCodewords.length !== version.getTotalCodewords()) {
  14453. throw new IllegalArgumentException();
  14454. }
  14455. // Figure out the number and size of data blocks used by this version and
  14456. // error correction level
  14457. const ecBlocks = version.getECBlocksForLevel(ecLevel);
  14458. // First count the total number of data blocks
  14459. let totalBlocks = 0;
  14460. const ecBlockArray = ecBlocks.getECBlocks();
  14461. for (const ecBlock of ecBlockArray) {
  14462. totalBlocks += ecBlock.getCount();
  14463. }
  14464. // Now establish DataBlocks of the appropriate size and number of data codewords
  14465. const result = new Array(totalBlocks);
  14466. let numResultBlocks = 0;
  14467. for (const ecBlock of ecBlockArray) {
  14468. for (let i = 0; i < ecBlock.getCount(); i++) {
  14469. const numDataCodewords = ecBlock.getDataCodewords();
  14470. const numBlockCodewords = ecBlocks.getECCodewordsPerBlock() + numDataCodewords;
  14471. result[numResultBlocks++] = new DataBlock$1(numDataCodewords, new Uint8Array(numBlockCodewords));
  14472. }
  14473. }
  14474. // All blocks have the same amount of data, except that the last n
  14475. // (where n may be 0) have 1 more byte. Figure out where these start.
  14476. const shorterBlocksTotalCodewords = result[0].codewords.length;
  14477. let longerBlocksStartAt = result.length - 1;
  14478. // TYPESCRIPTPORT: check length is correct here
  14479. while (longerBlocksStartAt >= 0) {
  14480. const numCodewords = result[longerBlocksStartAt].codewords.length;
  14481. if (numCodewords === shorterBlocksTotalCodewords) {
  14482. break;
  14483. }
  14484. longerBlocksStartAt--;
  14485. }
  14486. longerBlocksStartAt++;
  14487. const shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock();
  14488. // The last elements of result may be 1 element longer
  14489. // first fill out as many elements as all of them have
  14490. let rawCodewordsOffset = 0;
  14491. for (let i = 0; i < shorterBlocksNumDataCodewords; i++) {
  14492. for (let j = 0; j < numResultBlocks; j++) {
  14493. result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
  14494. }
  14495. }
  14496. // Fill out the last data block in the longer ones
  14497. for (let j = longerBlocksStartAt; j < numResultBlocks; j++) {
  14498. result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++];
  14499. }
  14500. // Now add in error correction blocks
  14501. const max = result[0].codewords.length;
  14502. for (let i = shorterBlocksNumDataCodewords; i < max; i++) {
  14503. for (let j = 0; j < numResultBlocks; j++) {
  14504. const iOffset = j < longerBlocksStartAt ? i : i + 1;
  14505. result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
  14506. }
  14507. }
  14508. return result;
  14509. }
  14510. getNumDataCodewords() {
  14511. return this.numDataCodewords;
  14512. }
  14513. getCodewords() {
  14514. return this.codewords;
  14515. }
  14516. }
  14517. /*
  14518. * Copyright 2007 ZXing authors
  14519. *
  14520. * Licensed under the Apache License, Version 2.0 (the "License");
  14521. * you may not use this file except in compliance with the License.
  14522. * You may obtain a copy of the License at
  14523. *
  14524. * http://www.apache.org/licenses/LICENSE-2.0
  14525. *
  14526. * Unless required by applicable law or agreed to in writing, software
  14527. * distributed under the License is distributed on an "AS IS" BASIS,
  14528. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14529. * See the License for the specific language governing permissions and
  14530. * limitations under the License.
  14531. */
  14532. var ModeValues;
  14533. (function (ModeValues) {
  14534. ModeValues[ModeValues["TERMINATOR"] = 0] = "TERMINATOR";
  14535. ModeValues[ModeValues["NUMERIC"] = 1] = "NUMERIC";
  14536. ModeValues[ModeValues["ALPHANUMERIC"] = 2] = "ALPHANUMERIC";
  14537. ModeValues[ModeValues["STRUCTURED_APPEND"] = 3] = "STRUCTURED_APPEND";
  14538. ModeValues[ModeValues["BYTE"] = 4] = "BYTE";
  14539. ModeValues[ModeValues["ECI"] = 5] = "ECI";
  14540. ModeValues[ModeValues["KANJI"] = 6] = "KANJI";
  14541. ModeValues[ModeValues["FNC1_FIRST_POSITION"] = 7] = "FNC1_FIRST_POSITION";
  14542. ModeValues[ModeValues["FNC1_SECOND_POSITION"] = 8] = "FNC1_SECOND_POSITION";
  14543. /** See GBT 18284-2000; "Hanzi" is a transliteration of this mode name. */
  14544. ModeValues[ModeValues["HANZI"] = 9] = "HANZI";
  14545. })(ModeValues || (ModeValues = {}));
  14546. /**
  14547. * <p>See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which
  14548. * data can be encoded to bits in the QR code standard.</p>
  14549. *
  14550. * @author Sean Owen
  14551. */
  14552. class Mode$1 {
  14553. constructor(value, stringValue, characterCountBitsForVersions, bits /*int*/) {
  14554. this.value = value;
  14555. this.stringValue = stringValue;
  14556. this.characterCountBitsForVersions = characterCountBitsForVersions;
  14557. this.bits = bits;
  14558. Mode$1.FOR_BITS.set(bits, this);
  14559. Mode$1.FOR_VALUE.set(value, this);
  14560. }
  14561. /**
  14562. * @param bits four bits encoding a QR Code data mode
  14563. * @return Mode encoded by these bits
  14564. * @throws IllegalArgumentException if bits do not correspond to a known mode
  14565. */
  14566. static forBits(bits /*int*/) {
  14567. const mode = Mode$1.FOR_BITS.get(bits);
  14568. if (undefined === mode) {
  14569. throw new IllegalArgumentException();
  14570. }
  14571. return mode;
  14572. }
  14573. /**
  14574. * @param version version in question
  14575. * @return number of bits used, in this QR Code symbol {@link Version}, to encode the
  14576. * count of characters that will follow encoded in this Mode
  14577. */
  14578. getCharacterCountBits(version) {
  14579. const versionNumber = version.getVersionNumber();
  14580. let offset;
  14581. if (versionNumber <= 9) {
  14582. offset = 0;
  14583. }
  14584. else if (versionNumber <= 26) {
  14585. offset = 1;
  14586. }
  14587. else {
  14588. offset = 2;
  14589. }
  14590. return this.characterCountBitsForVersions[offset];
  14591. }
  14592. getValue() {
  14593. return this.value;
  14594. }
  14595. getBits() {
  14596. return this.bits;
  14597. }
  14598. equals(o) {
  14599. if (!(o instanceof Mode$1)) {
  14600. return false;
  14601. }
  14602. const other = o;
  14603. return this.value === other.value;
  14604. }
  14605. toString() {
  14606. return this.stringValue;
  14607. }
  14608. }
  14609. Mode$1.FOR_BITS = new Map();
  14610. Mode$1.FOR_VALUE = new Map();
  14611. Mode$1.TERMINATOR = new Mode$1(ModeValues.TERMINATOR, 'TERMINATOR', Int32Array.from([0, 0, 0]), 0x00); // Not really a mode...
  14612. Mode$1.NUMERIC = new Mode$1(ModeValues.NUMERIC, 'NUMERIC', Int32Array.from([10, 12, 14]), 0x01);
  14613. Mode$1.ALPHANUMERIC = new Mode$1(ModeValues.ALPHANUMERIC, 'ALPHANUMERIC', Int32Array.from([9, 11, 13]), 0x02);
  14614. Mode$1.STRUCTURED_APPEND = new Mode$1(ModeValues.STRUCTURED_APPEND, 'STRUCTURED_APPEND', Int32Array.from([0, 0, 0]), 0x03); // Not supported
  14615. Mode$1.BYTE = new Mode$1(ModeValues.BYTE, 'BYTE', Int32Array.from([8, 16, 16]), 0x04);
  14616. Mode$1.ECI = new Mode$1(ModeValues.ECI, 'ECI', Int32Array.from([0, 0, 0]), 0x07); // character counts don't apply
  14617. Mode$1.KANJI = new Mode$1(ModeValues.KANJI, 'KANJI', Int32Array.from([8, 10, 12]), 0x08);
  14618. Mode$1.FNC1_FIRST_POSITION = new Mode$1(ModeValues.FNC1_FIRST_POSITION, 'FNC1_FIRST_POSITION', Int32Array.from([0, 0, 0]), 0x05);
  14619. Mode$1.FNC1_SECOND_POSITION = new Mode$1(ModeValues.FNC1_SECOND_POSITION, 'FNC1_SECOND_POSITION', Int32Array.from([0, 0, 0]), 0x09);
  14620. /** See GBT 18284-2000; "Hanzi" is a transliteration of this mode name. */
  14621. Mode$1.HANZI = new Mode$1(ModeValues.HANZI, 'HANZI', Int32Array.from([8, 10, 12]), 0x0D);
  14622. /*
  14623. * Copyright 2007 ZXing authors
  14624. *
  14625. * Licensed under the Apache License, Version 2.0 (the "License");
  14626. * you may not use this file except in compliance with the License.
  14627. * You may obtain a copy of the License at
  14628. *
  14629. * http://www.apache.org/licenses/LICENSE-2.0
  14630. *
  14631. * Unless required by applicable law or agreed to in writing, software
  14632. * distributed under the License is distributed on an "AS IS" BASIS,
  14633. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14634. * See the License for the specific language governing permissions and
  14635. * limitations under the License.
  14636. */
  14637. /*import java.io.UnsupportedEncodingException;*/
  14638. /*import java.util.ArrayList;*/
  14639. /*import java.util.Collection;*/
  14640. /*import java.util.List;*/
  14641. /*import java.util.Map;*/
  14642. /**
  14643. * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
  14644. * in one QR Code. This class decodes the bits back into text.</p>
  14645. *
  14646. * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
  14647. *
  14648. * @author Sean Owen
  14649. */
  14650. class DecodedBitStreamParser$1 {
  14651. static decode(bytes, version, ecLevel, hints) {
  14652. const bits = new BitSource(bytes);
  14653. let result = new StringBuilder();
  14654. const byteSegments = new Array(); // 1
  14655. // TYPESCRIPTPORT: I do not use constructor with size 1 as in original Java means capacity and the array length is checked below
  14656. let symbolSequence = -1;
  14657. let parityData = -1;
  14658. try {
  14659. let currentCharacterSetECI = null;
  14660. let fc1InEffect = false;
  14661. let mode;
  14662. do {
  14663. // While still another segment to read...
  14664. if (bits.available() < 4) {
  14665. // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
  14666. mode = Mode$1.TERMINATOR;
  14667. }
  14668. else {
  14669. const modeBits = bits.readBits(4);
  14670. mode = Mode$1.forBits(modeBits); // mode is encoded by 4 bits
  14671. }
  14672. switch (mode) {
  14673. case Mode$1.TERMINATOR:
  14674. break;
  14675. case Mode$1.FNC1_FIRST_POSITION:
  14676. case Mode$1.FNC1_SECOND_POSITION:
  14677. // We do little with FNC1 except alter the parsed result a bit according to the spec
  14678. fc1InEffect = true;
  14679. break;
  14680. case Mode$1.STRUCTURED_APPEND:
  14681. if (bits.available() < 16) {
  14682. throw new FormatException();
  14683. }
  14684. // sequence number and parity is added later to the result metadata
  14685. // Read next 8 bits (symbol sequence #) and 8 bits (data: parity), then continue
  14686. symbolSequence = bits.readBits(8);
  14687. parityData = bits.readBits(8);
  14688. break;
  14689. case Mode$1.ECI:
  14690. // Count doesn't apply to ECI
  14691. const value = DecodedBitStreamParser$1.parseECIValue(bits);
  14692. currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
  14693. if (currentCharacterSetECI === null) {
  14694. throw new FormatException();
  14695. }
  14696. break;
  14697. case Mode$1.HANZI:
  14698. // First handle Hanzi mode which does not start with character count
  14699. // Chinese mode contains a sub set indicator right after mode indicator
  14700. const subset = bits.readBits(4);
  14701. const countHanzi = bits.readBits(mode.getCharacterCountBits(version));
  14702. if (subset === DecodedBitStreamParser$1.GB2312_SUBSET) {
  14703. DecodedBitStreamParser$1.decodeHanziSegment(bits, result, countHanzi);
  14704. }
  14705. break;
  14706. default:
  14707. // "Normal" QR code modes:
  14708. // How many characters will follow, encoded in this mode?
  14709. const count = bits.readBits(mode.getCharacterCountBits(version));
  14710. switch (mode) {
  14711. case Mode$1.NUMERIC:
  14712. DecodedBitStreamParser$1.decodeNumericSegment(bits, result, count);
  14713. break;
  14714. case Mode$1.ALPHANUMERIC:
  14715. DecodedBitStreamParser$1.decodeAlphanumericSegment(bits, result, count, fc1InEffect);
  14716. break;
  14717. case Mode$1.BYTE:
  14718. DecodedBitStreamParser$1.decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints);
  14719. break;
  14720. case Mode$1.KANJI:
  14721. DecodedBitStreamParser$1.decodeKanjiSegment(bits, result, count);
  14722. break;
  14723. default:
  14724. throw new FormatException();
  14725. }
  14726. break;
  14727. }
  14728. } while (mode !== Mode$1.TERMINATOR);
  14729. }
  14730. catch (iae /*: IllegalArgumentException*/) {
  14731. // from readBits() calls
  14732. throw new FormatException();
  14733. }
  14734. return new DecoderResult(bytes, result.toString(), byteSegments.length === 0 ? null : byteSegments, ecLevel === null ? null : ecLevel.toString(), symbolSequence, parityData);
  14735. }
  14736. /**
  14737. * See specification GBT 18284-2000
  14738. */
  14739. static decodeHanziSegment(bits, result, count /*int*/) {
  14740. // Don't crash trying to read more bits than we have available.
  14741. if (count * 13 > bits.available()) {
  14742. throw new FormatException();
  14743. }
  14744. // Each character will require 2 bytes. Read the characters as 2-byte pairs
  14745. // and decode as GB2312 afterwards
  14746. const buffer = new Uint8Array(2 * count);
  14747. let offset = 0;
  14748. while (count > 0) {
  14749. // Each 13 bits encodes a 2-byte character
  14750. const twoBytes = bits.readBits(13);
  14751. let assembledTwoBytes = (((twoBytes / 0x060) << 8) & 0xFFFFFFFF) | (twoBytes % 0x060);
  14752. if (assembledTwoBytes < 0x003BF) {
  14753. // In the 0xA1A1 to 0xAAFE range
  14754. assembledTwoBytes += 0x0A1A1;
  14755. }
  14756. else {
  14757. // In the 0xB0A1 to 0xFAFE range
  14758. assembledTwoBytes += 0x0A6A1;
  14759. }
  14760. buffer[offset] = /*(byte) */ ((assembledTwoBytes >> 8) & 0xFF);
  14761. buffer[offset + 1] = /*(byte) */ (assembledTwoBytes & 0xFF);
  14762. offset += 2;
  14763. count--;
  14764. }
  14765. try {
  14766. result.append(StringEncoding.decode(buffer, StringUtils.GB2312));
  14767. // TYPESCRIPTPORT: TODO: implement GB2312 decode. StringView from MDN could be a starting point
  14768. }
  14769. catch (ignored /*: UnsupportedEncodingException*/) {
  14770. throw new FormatException(ignored);
  14771. }
  14772. }
  14773. static decodeKanjiSegment(bits, result, count /*int*/) {
  14774. // Don't crash trying to read more bits than we have available.
  14775. if (count * 13 > bits.available()) {
  14776. throw new FormatException();
  14777. }
  14778. // Each character will require 2 bytes. Read the characters as 2-byte pairs
  14779. // and decode as Shift_JIS afterwards
  14780. const buffer = new Uint8Array(2 * count);
  14781. let offset = 0;
  14782. while (count > 0) {
  14783. // Each 13 bits encodes a 2-byte character
  14784. const twoBytes = bits.readBits(13);
  14785. let assembledTwoBytes = (((twoBytes / 0x0C0) << 8) & 0xFFFFFFFF) | (twoBytes % 0x0C0);
  14786. if (assembledTwoBytes < 0x01F00) {
  14787. // In the 0x8140 to 0x9FFC range
  14788. assembledTwoBytes += 0x08140;
  14789. }
  14790. else {
  14791. // In the 0xE040 to 0xEBBF range
  14792. assembledTwoBytes += 0x0C140;
  14793. }
  14794. buffer[offset] = /*(byte) */ (assembledTwoBytes >> 8);
  14795. buffer[offset + 1] = /*(byte) */ assembledTwoBytes;
  14796. offset += 2;
  14797. count--;
  14798. }
  14799. // Shift_JIS may not be supported in some environments:
  14800. try {
  14801. result.append(StringEncoding.decode(buffer, StringUtils.SHIFT_JIS));
  14802. // TYPESCRIPTPORT: TODO: implement SHIFT_JIS decode. StringView from MDN could be a starting point
  14803. }
  14804. catch (ignored /*: UnsupportedEncodingException*/) {
  14805. throw new FormatException(ignored);
  14806. }
  14807. }
  14808. static decodeByteSegment(bits, result, count /*int*/, currentCharacterSetECI, byteSegments, hints) {
  14809. // Don't crash trying to read more bits than we have available.
  14810. if (8 * count > bits.available()) {
  14811. throw new FormatException();
  14812. }
  14813. const readBytes = new Uint8Array(count);
  14814. for (let i = 0; i < count; i++) {
  14815. readBytes[i] = /*(byte) */ bits.readBits(8);
  14816. }
  14817. let encoding;
  14818. if (currentCharacterSetECI === null) {
  14819. // The spec isn't clear on this mode; see
  14820. // section 6.4.5: t does not say which encoding to assuming
  14821. // upon decoding. I have seen ISO-8859-1 used as well as
  14822. // Shift_JIS -- without anything like an ECI designator to
  14823. // give a hint.
  14824. encoding = StringUtils.guessEncoding(readBytes, hints);
  14825. }
  14826. else {
  14827. encoding = currentCharacterSetECI.getName();
  14828. }
  14829. try {
  14830. result.append(StringEncoding.decode(readBytes, encoding));
  14831. }
  14832. catch (ignored /*: UnsupportedEncodingException*/) {
  14833. throw new FormatException(ignored);
  14834. }
  14835. byteSegments.push(readBytes);
  14836. }
  14837. static toAlphaNumericChar(value /*int*/) {
  14838. if (value >= DecodedBitStreamParser$1.ALPHANUMERIC_CHARS.length) {
  14839. throw new FormatException();
  14840. }
  14841. return DecodedBitStreamParser$1.ALPHANUMERIC_CHARS[value];
  14842. }
  14843. static decodeAlphanumericSegment(bits, result, count /*int*/, fc1InEffect) {
  14844. // Read two characters at a time
  14845. const start = result.length();
  14846. while (count > 1) {
  14847. if (bits.available() < 11) {
  14848. throw new FormatException();
  14849. }
  14850. const nextTwoCharsBits = bits.readBits(11);
  14851. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(nextTwoCharsBits / 45)));
  14852. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(nextTwoCharsBits % 45));
  14853. count -= 2;
  14854. }
  14855. if (count === 1) {
  14856. // special case: one character left
  14857. if (bits.available() < 6) {
  14858. throw new FormatException();
  14859. }
  14860. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(bits.readBits(6)));
  14861. }
  14862. // See section 6.4.8.1, 6.4.8.2
  14863. if (fc1InEffect) {
  14864. // We need to massage the result a bit if in an FNC1 mode:
  14865. for (let i = start; i < result.length(); i++) {
  14866. if (result.charAt(i) === '%') {
  14867. if (i < result.length() - 1 && result.charAt(i + 1) === '%') {
  14868. // %% is rendered as %
  14869. result.deleteCharAt(i + 1);
  14870. }
  14871. else {
  14872. // In alpha mode, % should be converted to FNC1 separator 0x1D
  14873. result.setCharAt(i, String.fromCharCode(0x1D));
  14874. }
  14875. }
  14876. }
  14877. }
  14878. }
  14879. static decodeNumericSegment(bits, result, count /*int*/) {
  14880. // Read three digits at a time
  14881. while (count >= 3) {
  14882. // Each 10 bits encodes three digits
  14883. if (bits.available() < 10) {
  14884. throw new FormatException();
  14885. }
  14886. const threeDigitsBits = bits.readBits(10);
  14887. if (threeDigitsBits >= 1000) {
  14888. throw new FormatException();
  14889. }
  14890. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(threeDigitsBits / 100)));
  14891. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(threeDigitsBits / 10) % 10));
  14892. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(threeDigitsBits % 10));
  14893. count -= 3;
  14894. }
  14895. if (count === 2) {
  14896. // Two digits left over to read, encoded in 7 bits
  14897. if (bits.available() < 7) {
  14898. throw new FormatException();
  14899. }
  14900. const twoDigitsBits = bits.readBits(7);
  14901. if (twoDigitsBits >= 100) {
  14902. throw new FormatException();
  14903. }
  14904. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(twoDigitsBits / 10)));
  14905. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(twoDigitsBits % 10));
  14906. }
  14907. else if (count === 1) {
  14908. // One digit left over to read
  14909. if (bits.available() < 4) {
  14910. throw new FormatException();
  14911. }
  14912. const digitBits = bits.readBits(4);
  14913. if (digitBits >= 10) {
  14914. throw new FormatException();
  14915. }
  14916. result.append(DecodedBitStreamParser$1.toAlphaNumericChar(digitBits));
  14917. }
  14918. }
  14919. static parseECIValue(bits) {
  14920. const firstByte = bits.readBits(8);
  14921. if ((firstByte & 0x80) === 0) {
  14922. // just one byte
  14923. return firstByte & 0x7F;
  14924. }
  14925. if ((firstByte & 0xC0) === 0x80) {
  14926. // two bytes
  14927. const secondByte = bits.readBits(8);
  14928. return (((firstByte & 0x3F) << 8) & 0xFFFFFFFF) | secondByte;
  14929. }
  14930. if ((firstByte & 0xE0) === 0xC0) {
  14931. // three bytes
  14932. const secondThirdBytes = bits.readBits(16);
  14933. return (((firstByte & 0x1F) << 16) & 0xFFFFFFFF) | secondThirdBytes;
  14934. }
  14935. throw new FormatException();
  14936. }
  14937. }
  14938. /**
  14939. * See ISO 18004:2006, 6.4.4 Table 5
  14940. */
  14941. DecodedBitStreamParser$1.ALPHANUMERIC_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';
  14942. DecodedBitStreamParser$1.GB2312_SUBSET = 1;
  14943. // function Uint8ArrayToString(a: Uint8Array): string {
  14944. // const CHUNK_SZ = 0x8000;
  14945. // const c = new StringBuilder();
  14946. // for (let i = 0, length = a.length; i < length; i += CHUNK_SZ) {
  14947. // c.append(String.fromCharCode.apply(null, a.subarray(i, i + CHUNK_SZ)));
  14948. // }
  14949. // return c.toString();
  14950. // }
  14951. /*
  14952. * Copyright 2013 ZXing authors
  14953. *
  14954. * Licensed under the Apache License, Version 2.0 (the "License");
  14955. * you may not use this file except in compliance with the License.
  14956. * You may obtain a copy of the License at
  14957. *
  14958. * http://www.apache.org/licenses/LICENSE-2.0
  14959. *
  14960. * Unless required by applicable law or agreed to in writing, software
  14961. * distributed under the License is distributed on an "AS IS" BASIS,
  14962. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14963. * See the License for the specific language governing permissions and
  14964. * limitations under the License.
  14965. */
  14966. /**
  14967. * Meta-data container for QR Code decoding. Instances of this class may be used to convey information back to the
  14968. * decoding caller. Callers are expected to process this.
  14969. *
  14970. * @see com.google.zxing.common.DecoderResult#getOther()
  14971. */
  14972. class QRCodeDecoderMetaData {
  14973. constructor(mirrored) {
  14974. this.mirrored = mirrored;
  14975. }
  14976. /**
  14977. * @return true if the QR Code was mirrored.
  14978. */
  14979. isMirrored() {
  14980. return this.mirrored;
  14981. }
  14982. /**
  14983. * Apply the result points' order correction due to mirroring.
  14984. *
  14985. * @param points Array of points to apply mirror correction to.
  14986. */
  14987. applyMirroredCorrection(points) {
  14988. if (!this.mirrored || points === null || points.length < 3) {
  14989. return;
  14990. }
  14991. const bottomLeft = points[0];
  14992. points[0] = points[2];
  14993. points[2] = bottomLeft;
  14994. // No need to 'fix' top-left and alignment pattern.
  14995. }
  14996. }
  14997. /*
  14998. * Copyright 2007 ZXing authors
  14999. *
  15000. * Licensed under the Apache License, Version 2.0 (the "License");
  15001. * you may not use this file except in compliance with the License.
  15002. * You may obtain a copy of the License at
  15003. *
  15004. * http://www.apache.org/licenses/LICENSE-2.0
  15005. *
  15006. * Unless required by applicable law or agreed to in writing, software
  15007. * distributed under the License is distributed on an "AS IS" BASIS,
  15008. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15009. * See the License for the specific language governing permissions and
  15010. * limitations under the License.
  15011. */
  15012. /*import java.util.Map;*/
  15013. /**
  15014. * <p>The main class which implements QR Code decoding -- as opposed to locating and extracting
  15015. * the QR Code from an image.</p>
  15016. *
  15017. * @author Sean Owen
  15018. */
  15019. class Decoder$2 {
  15020. constructor() {
  15021. this.rsDecoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256);
  15022. }
  15023. // public decode(image: boolean[][]): DecoderResult /*throws ChecksumException, FormatException*/ {
  15024. // return decode(image, null)
  15025. // }
  15026. /**
  15027. * <p>Convenience method that can decode a QR Code represented as a 2D array of booleans.
  15028. * "true" is taken to mean a black module.</p>
  15029. *
  15030. * @param image booleans representing white/black QR Code modules
  15031. * @param hints decoding hints that should be used to influence decoding
  15032. * @return text and bytes encoded within the QR Code
  15033. * @throws FormatException if the QR Code cannot be decoded
  15034. * @throws ChecksumException if error correction fails
  15035. */
  15036. decodeBooleanArray(image, hints) {
  15037. return this.decodeBitMatrix(BitMatrix.parseFromBooleanArray(image), hints);
  15038. }
  15039. // public decodeBitMatrix(bits: BitMatrix): DecoderResult /*throws ChecksumException, FormatException*/ {
  15040. // return decode(bits, null)
  15041. // }
  15042. /**
  15043. * <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
  15044. *
  15045. * @param bits booleans representing white/black QR Code modules
  15046. * @param hints decoding hints that should be used to influence decoding
  15047. * @return text and bytes encoded within the QR Code
  15048. * @throws FormatException if the QR Code cannot be decoded
  15049. * @throws ChecksumException if error correction fails
  15050. */
  15051. decodeBitMatrix(bits, hints) {
  15052. // Construct a parser and read version, error-correction level
  15053. const parser = new BitMatrixParser$1(bits);
  15054. let ex = null;
  15055. try {
  15056. return this.decodeBitMatrixParser(parser, hints);
  15057. }
  15058. catch (e /*: FormatException, ChecksumException*/) {
  15059. ex = e;
  15060. }
  15061. try {
  15062. // Revert the bit matrix
  15063. parser.remask();
  15064. // Will be attempting a mirrored reading of the version and format info.
  15065. parser.setMirror(true);
  15066. // Preemptively read the version.
  15067. parser.readVersion();
  15068. // Preemptively read the format information.
  15069. parser.readFormatInformation();
  15070. /*
  15071. * Since we're here, this means we have successfully detected some kind
  15072. * of version and format information when mirrored. This is a good sign,
  15073. * that the QR code may be mirrored, and we should try once more with a
  15074. * mirrored content.
  15075. */
  15076. // Prepare for a mirrored reading.
  15077. parser.mirror();
  15078. const result = this.decodeBitMatrixParser(parser, hints);
  15079. // Success! Notify the caller that the code was mirrored.
  15080. result.setOther(new QRCodeDecoderMetaData(true));
  15081. return result;
  15082. }
  15083. catch (e /*FormatException | ChecksumException*/) {
  15084. // Throw the exception from the original reading
  15085. if (ex !== null) {
  15086. throw ex;
  15087. }
  15088. throw e;
  15089. }
  15090. }
  15091. decodeBitMatrixParser(parser, hints) {
  15092. const version = parser.readVersion();
  15093. const ecLevel = parser.readFormatInformation().getErrorCorrectionLevel();
  15094. // Read codewords
  15095. const codewords = parser.readCodewords();
  15096. // Separate into data blocks
  15097. const dataBlocks = DataBlock$1.getDataBlocks(codewords, version, ecLevel);
  15098. // Count total number of data bytes
  15099. let totalBytes = 0;
  15100. for (const dataBlock of dataBlocks) {
  15101. totalBytes += dataBlock.getNumDataCodewords();
  15102. }
  15103. const resultBytes = new Uint8Array(totalBytes);
  15104. let resultOffset = 0;
  15105. // Error-correct and copy data blocks together into a stream of bytes
  15106. for (const dataBlock of dataBlocks) {
  15107. const codewordBytes = dataBlock.getCodewords();
  15108. const numDataCodewords = dataBlock.getNumDataCodewords();
  15109. this.correctErrors(codewordBytes, numDataCodewords);
  15110. for (let i = 0; i < numDataCodewords; i++) {
  15111. resultBytes[resultOffset++] = codewordBytes[i];
  15112. }
  15113. }
  15114. // Decode the contents of that stream of bytes
  15115. return DecodedBitStreamParser$1.decode(resultBytes, version, ecLevel, hints);
  15116. }
  15117. /**
  15118. * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
  15119. * correct the errors in-place using Reed-Solomon error correction.</p>
  15120. *
  15121. * @param codewordBytes data and error correction codewords
  15122. * @param numDataCodewords number of codewords that are data bytes
  15123. * @throws ChecksumException if error correction fails
  15124. */
  15125. correctErrors(codewordBytes, numDataCodewords /*int*/) {
  15126. // const numCodewords = codewordBytes.length;
  15127. // First read into an array of ints
  15128. const codewordsInts = new Int32Array(codewordBytes);
  15129. // TYPESCRIPTPORT: not realy necessary to transform to ints? could redesign everything to work with unsigned bytes?
  15130. // const codewordsInts = new Int32Array(numCodewords)
  15131. // for (let i = 0; i < numCodewords; i++) {
  15132. // codewordsInts[i] = codewordBytes[i] & 0xFF
  15133. // }
  15134. try {
  15135. this.rsDecoder.decode(codewordsInts, codewordBytes.length - numDataCodewords);
  15136. }
  15137. catch (ignored /*: ReedSolomonException*/) {
  15138. throw new ChecksumException();
  15139. }
  15140. // Copy back into array of bytes -- only need to worry about the bytes that were data
  15141. // We don't care about errors in the error-correction codewords
  15142. for (let i = 0; i < numDataCodewords; i++) {
  15143. codewordBytes[i] = /*(byte) */ codewordsInts[i];
  15144. }
  15145. }
  15146. }
  15147. /*
  15148. * Copyright 2007 ZXing authors
  15149. *
  15150. * Licensed under the Apache License, Version 2.0 (the "License");
  15151. * you may not use this file except in compliance with the License.
  15152. * You may obtain a copy of the License at
  15153. *
  15154. * http://www.apache.org/licenses/LICENSE-2.0
  15155. *
  15156. * Unless required by applicable law or agreed to in writing, software
  15157. * distributed under the License is distributed on an "AS IS" BASIS,
  15158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15159. * See the License for the specific language governing permissions and
  15160. * limitations under the License.
  15161. */
  15162. /**
  15163. * <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
  15164. * all but the simplest QR Codes.</p>
  15165. *
  15166. * @author Sean Owen
  15167. */
  15168. class AlignmentPattern extends ResultPoint {
  15169. constructor(posX /*float*/, posY /*float*/, estimatedModuleSize /*float*/) {
  15170. super(posX, posY);
  15171. this.estimatedModuleSize = estimatedModuleSize;
  15172. }
  15173. /**
  15174. * <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated
  15175. * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
  15176. */
  15177. aboutEquals(moduleSize /*float*/, i /*float*/, j /*float*/) {
  15178. if (Math.abs(i - this.getY()) <= moduleSize && Math.abs(j - this.getX()) <= moduleSize) {
  15179. const moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
  15180. return moduleSizeDiff <= 1.0 || moduleSizeDiff <= this.estimatedModuleSize;
  15181. }
  15182. return false;
  15183. }
  15184. /**
  15185. * Combines this object's current estimate of a finder pattern position and module size
  15186. * with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.
  15187. */
  15188. combineEstimate(i /*float*/, j /*float*/, newModuleSize /*float*/) {
  15189. const combinedX = (this.getX() + j) / 2.0;
  15190. const combinedY = (this.getY() + i) / 2.0;
  15191. const combinedModuleSize = (this.estimatedModuleSize + newModuleSize) / 2.0;
  15192. return new AlignmentPattern(combinedX, combinedY, combinedModuleSize);
  15193. }
  15194. }
  15195. /*
  15196. * Copyright 2007 ZXing authors
  15197. *
  15198. * Licensed under the Apache License, Version 2.0 (the "License");
  15199. * you may not use this file except in compliance with the License.
  15200. * You may obtain a copy of the License at
  15201. *
  15202. * http://www.apache.org/licenses/LICENSE-2.0
  15203. *
  15204. * Unless required by applicable law or agreed to in writing, software
  15205. * distributed under the License is distributed on an "AS IS" BASIS,
  15206. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15207. * See the License for the specific language governing permissions and
  15208. * limitations under the License.
  15209. */
  15210. /*import java.util.ArrayList;*/
  15211. /*import java.util.List;*/
  15212. /**
  15213. * <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
  15214. * patterns but are smaller and appear at regular intervals throughout the image.</p>
  15215. *
  15216. * <p>At the moment this only looks for the bottom-right alignment pattern.</p>
  15217. *
  15218. * <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
  15219. * pasted and stripped down here for maximum performance but does unfortunately duplicate
  15220. * some code.</p>
  15221. *
  15222. * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
  15223. *
  15224. * @author Sean Owen
  15225. */
  15226. class AlignmentPatternFinder {
  15227. /**
  15228. * <p>Creates a finder that will look in a portion of the whole image.</p>
  15229. *
  15230. * @param image image to search
  15231. * @param startX left column from which to start searching
  15232. * @param startY top row from which to start searching
  15233. * @param width width of region to search
  15234. * @param height height of region to search
  15235. * @param moduleSize estimated module size so far
  15236. */
  15237. constructor(image, startX /*int*/, startY /*int*/, width /*int*/, height /*int*/, moduleSize /*float*/, resultPointCallback) {
  15238. this.image = image;
  15239. this.startX = startX;
  15240. this.startY = startY;
  15241. this.width = width;
  15242. this.height = height;
  15243. this.moduleSize = moduleSize;
  15244. this.resultPointCallback = resultPointCallback;
  15245. this.possibleCenters = []; // new Array<any>(5))
  15246. // TYPESCRIPTPORT: array initialization without size as the length is checked below
  15247. this.crossCheckStateCount = new Int32Array(3);
  15248. }
  15249. /**
  15250. * <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
  15251. * it's pretty performance-critical and so is written to be fast foremost.</p>
  15252. *
  15253. * @return {@link AlignmentPattern} if found
  15254. * @throws NotFoundException if not found
  15255. */
  15256. find() {
  15257. const startX = this.startX;
  15258. const height = this.height;
  15259. const width = this.width;
  15260. const maxJ = startX + width;
  15261. const middleI = this.startY + (height / 2);
  15262. // We are looking for black/white/black modules in 1:1:1 ratio
  15263. // this tracks the number of black/white/black modules seen so far
  15264. const stateCount = new Int32Array(3);
  15265. const image = this.image;
  15266. for (let iGen = 0; iGen < height; iGen++) {
  15267. // Search from middle outwards
  15268. const i = middleI + ((iGen & 0x01) === 0 ? Math.floor((iGen + 1) / 2) : -Math.floor((iGen + 1) / 2));
  15269. stateCount[0] = 0;
  15270. stateCount[1] = 0;
  15271. stateCount[2] = 0;
  15272. let j = startX;
  15273. // Burn off leading white pixels before anything else; if we start in the middle of
  15274. // a white run, it doesn't make sense to count its length, since we don't know if the
  15275. // white run continued to the left of the start point
  15276. while (j < maxJ && !image.get(j, i)) {
  15277. j++;
  15278. }
  15279. let currentState = 0;
  15280. while (j < maxJ) {
  15281. if (image.get(j, i)) {
  15282. // Black pixel
  15283. if (currentState === 1) { // Counting black pixels
  15284. stateCount[1]++;
  15285. }
  15286. else { // Counting white pixels
  15287. if (currentState === 2) { // A winner?
  15288. if (this.foundPatternCross(stateCount)) { // Yes
  15289. const confirmed = this.handlePossibleCenter(stateCount, i, j);
  15290. if (confirmed !== null) {
  15291. return confirmed;
  15292. }
  15293. }
  15294. stateCount[0] = stateCount[2];
  15295. stateCount[1] = 1;
  15296. stateCount[2] = 0;
  15297. currentState = 1;
  15298. }
  15299. else {
  15300. stateCount[++currentState]++;
  15301. }
  15302. }
  15303. }
  15304. else { // White pixel
  15305. if (currentState === 1) { // Counting black pixels
  15306. currentState++;
  15307. }
  15308. stateCount[currentState]++;
  15309. }
  15310. j++;
  15311. }
  15312. if (this.foundPatternCross(stateCount)) {
  15313. const confirmed = this.handlePossibleCenter(stateCount, i, maxJ);
  15314. if (confirmed !== null) {
  15315. return confirmed;
  15316. }
  15317. }
  15318. }
  15319. // Hmm, nothing we saw was observed and confirmed twice. If we had
  15320. // any guess at all, return it.
  15321. if (this.possibleCenters.length !== 0) {
  15322. return this.possibleCenters[0];
  15323. }
  15324. throw new NotFoundException();
  15325. }
  15326. /**
  15327. * Given a count of black/white/black pixels just seen and an end position,
  15328. * figures the location of the center of this black/white/black run.
  15329. */
  15330. static centerFromEnd(stateCount, end /*int*/) {
  15331. return (end - stateCount[2]) - stateCount[1] / 2.0;
  15332. }
  15333. /**
  15334. * @param stateCount count of black/white/black pixels just read
  15335. * @return true iff the proportions of the counts is close enough to the 1/1/1 ratios
  15336. * used by alignment patterns to be considered a match
  15337. */
  15338. foundPatternCross(stateCount) {
  15339. const moduleSize = this.moduleSize;
  15340. const maxVariance = moduleSize / 2.0;
  15341. for (let i = 0; i < 3; i++) {
  15342. if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) {
  15343. return false;
  15344. }
  15345. }
  15346. return true;
  15347. }
  15348. /**
  15349. * <p>After a horizontal scan finds a potential alignment pattern, this method
  15350. * "cross-checks" by scanning down vertically through the center of the possible
  15351. * alignment pattern to see if the same proportion is detected.</p>
  15352. *
  15353. * @param startI row where an alignment pattern was detected
  15354. * @param centerJ center of the section that appears to cross an alignment pattern
  15355. * @param maxCount maximum reasonable number of modules that should be
  15356. * observed in any reading state, based on the results of the horizontal scan
  15357. * @return vertical center of alignment pattern, or {@link Float#NaN} if not found
  15358. */
  15359. crossCheckVertical(startI /*int*/, centerJ /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {
  15360. const image = this.image;
  15361. const maxI = image.getHeight();
  15362. const stateCount = this.crossCheckStateCount;
  15363. stateCount[0] = 0;
  15364. stateCount[1] = 0;
  15365. stateCount[2] = 0;
  15366. // Start counting up from center
  15367. let i = startI;
  15368. while (i >= 0 && image.get(centerJ, i) && stateCount[1] <= maxCount) {
  15369. stateCount[1]++;
  15370. i--;
  15371. }
  15372. // If already too many modules in this state or ran off the edge:
  15373. if (i < 0 || stateCount[1] > maxCount) {
  15374. return NaN;
  15375. }
  15376. while (i >= 0 && !image.get(centerJ, i) && stateCount[0] <= maxCount) {
  15377. stateCount[0]++;
  15378. i--;
  15379. }
  15380. if (stateCount[0] > maxCount) {
  15381. return NaN;
  15382. }
  15383. // Now also count down from center
  15384. i = startI + 1;
  15385. while (i < maxI && image.get(centerJ, i) && stateCount[1] <= maxCount) {
  15386. stateCount[1]++;
  15387. i++;
  15388. }
  15389. if (i === maxI || stateCount[1] > maxCount) {
  15390. return NaN;
  15391. }
  15392. while (i < maxI && !image.get(centerJ, i) && stateCount[2] <= maxCount) {
  15393. stateCount[2]++;
  15394. i++;
  15395. }
  15396. if (stateCount[2] > maxCount) {
  15397. return NaN;
  15398. }
  15399. const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
  15400. if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
  15401. return NaN;
  15402. }
  15403. return this.foundPatternCross(stateCount) ? AlignmentPatternFinder.centerFromEnd(stateCount, i) : NaN;
  15404. }
  15405. /**
  15406. * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
  15407. * cross check with a vertical scan, and if successful, will see if this pattern had been
  15408. * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
  15409. * found the alignment pattern.</p>
  15410. *
  15411. * @param stateCount reading state module counts from horizontal scan
  15412. * @param i row where alignment pattern may be found
  15413. * @param j end of possible alignment pattern in row
  15414. * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not
  15415. */
  15416. handlePossibleCenter(stateCount, i /*int*/, j /*int*/) {
  15417. const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
  15418. const centerJ = AlignmentPatternFinder.centerFromEnd(stateCount, j);
  15419. const centerI = this.crossCheckVertical(i, /*(int) */ centerJ, 2 * stateCount[1], stateCountTotal);
  15420. if (!isNaN(centerI)) {
  15421. const estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0;
  15422. for (const center of this.possibleCenters) {
  15423. // Look for about the same center and module size:
  15424. if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
  15425. return center.combineEstimate(centerI, centerJ, estimatedModuleSize);
  15426. }
  15427. }
  15428. // Hadn't found this before; save it
  15429. const point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize);
  15430. this.possibleCenters.push(point);
  15431. if (this.resultPointCallback !== null && this.resultPointCallback !== undefined) {
  15432. this.resultPointCallback.foundPossibleResultPoint(point);
  15433. }
  15434. }
  15435. return null;
  15436. }
  15437. }
  15438. /*
  15439. * Copyright 2007 ZXing authors
  15440. *
  15441. * Licensed under the Apache License, Version 2.0 (the "License");
  15442. * you may not use this file except in compliance with the License.
  15443. * You may obtain a copy of the License at
  15444. *
  15445. * http://www.apache.org/licenses/LICENSE-2.0
  15446. *
  15447. * Unless required by applicable law or agreed to in writing, software
  15448. * distributed under the License is distributed on an "AS IS" BASIS,
  15449. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15450. * See the License for the specific language governing permissions and
  15451. * limitations under the License.
  15452. */
  15453. /**
  15454. * <p>Encapsulates a finder pattern, which are the three square patterns found in
  15455. * the corners of QR Codes. It also encapsulates a count of similar finder patterns,
  15456. * as a convenience to the finder's bookkeeping.</p>
  15457. *
  15458. * @author Sean Owen
  15459. */
  15460. class FinderPattern$1 extends ResultPoint {
  15461. // FinderPattern(posX: number/*float*/, posY: number/*float*/, estimatedModuleSize: number/*float*/) {
  15462. // this(posX, posY, estimatedModuleSize, 1)
  15463. // }
  15464. constructor(posX /*float*/, posY /*float*/, estimatedModuleSize /*float*/, count /*int*/) {
  15465. super(posX, posY);
  15466. this.estimatedModuleSize = estimatedModuleSize;
  15467. this.count = count;
  15468. if (undefined === count) {
  15469. this.count = 1;
  15470. }
  15471. }
  15472. getEstimatedModuleSize() {
  15473. return this.estimatedModuleSize;
  15474. }
  15475. getCount() {
  15476. return this.count;
  15477. }
  15478. /*
  15479. void incrementCount() {
  15480. this.count++
  15481. }
  15482. */
  15483. /**
  15484. * <p>Determines if this finder pattern "about equals" a finder pattern at the stated
  15485. * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
  15486. */
  15487. aboutEquals(moduleSize /*float*/, i /*float*/, j /*float*/) {
  15488. if (Math.abs(i - this.getY()) <= moduleSize && Math.abs(j - this.getX()) <= moduleSize) {
  15489. const moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);
  15490. return moduleSizeDiff <= 1.0 || moduleSizeDiff <= this.estimatedModuleSize;
  15491. }
  15492. return false;
  15493. }
  15494. /**
  15495. * Combines this object's current estimate of a finder pattern position and module size
  15496. * with a new estimate. It returns a new {@code FinderPattern} containing a weighted average
  15497. * based on count.
  15498. */
  15499. combineEstimate(i /*float*/, j /*float*/, newModuleSize /*float*/) {
  15500. const combinedCount = this.count + 1;
  15501. const combinedX = (this.count * this.getX() + j) / combinedCount;
  15502. const combinedY = (this.count * this.getY() + i) / combinedCount;
  15503. const combinedModuleSize = (this.count * this.estimatedModuleSize + newModuleSize) / combinedCount;
  15504. return new FinderPattern$1(combinedX, combinedY, combinedModuleSize, combinedCount);
  15505. }
  15506. }
  15507. /*
  15508. * Copyright 2007 ZXing authors
  15509. *
  15510. * Licensed under the Apache License, Version 2.0 (the "License");
  15511. * you may not use this file except in compliance with the License.
  15512. * You may obtain a copy of the License at
  15513. *
  15514. * http://www.apache.org/licenses/LICENSE-2.0
  15515. *
  15516. * Unless required by applicable law or agreed to in writing, software
  15517. * distributed under the License is distributed on an "AS IS" BASIS,
  15518. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15519. * See the License for the specific language governing permissions and
  15520. * limitations under the License.
  15521. */
  15522. /**
  15523. * <p>Encapsulates information about finder patterns in an image, including the location of
  15524. * the three finder patterns, and their estimated module size.</p>
  15525. *
  15526. * @author Sean Owen
  15527. */
  15528. class FinderPatternInfo {
  15529. constructor(patternCenters) {
  15530. this.bottomLeft = patternCenters[0];
  15531. this.topLeft = patternCenters[1];
  15532. this.topRight = patternCenters[2];
  15533. }
  15534. getBottomLeft() {
  15535. return this.bottomLeft;
  15536. }
  15537. getTopLeft() {
  15538. return this.topLeft;
  15539. }
  15540. getTopRight() {
  15541. return this.topRight;
  15542. }
  15543. }
  15544. /*
  15545. * Copyright 2007 ZXing authors
  15546. *
  15547. * Licensed under the Apache License, Version 2.0 (the "License");
  15548. * you may not use this file except in compliance with the License.
  15549. * You may obtain a copy of the License at
  15550. *
  15551. * http://www.apache.org/licenses/LICENSE-2.0
  15552. *
  15553. * Unless required by applicable law or agreed to in writing, software
  15554. * distributed under the License is distributed on an "AS IS" BASIS,
  15555. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15556. * See the License for the specific language governing permissions and
  15557. * limitations under the License.
  15558. */
  15559. /*import java.io.Serializable;*/
  15560. /*import java.util.ArrayList;*/
  15561. /*import java.util.Collections;*/
  15562. /*import java.util.Comparator;*/
  15563. /*import java.util.List;*/
  15564. /*import java.util.Map;*/
  15565. /**
  15566. * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
  15567. * markers at three corners of a QR Code.</p>
  15568. *
  15569. * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
  15570. *
  15571. * @author Sean Owen
  15572. */
  15573. class FinderPatternFinder {
  15574. /**
  15575. * <p>Creates a finder that will search the image for three finder patterns.</p>
  15576. *
  15577. * @param image image to search
  15578. */
  15579. // public constructor(image: BitMatrix) {
  15580. // this(image, null)
  15581. // }
  15582. constructor(image, resultPointCallback) {
  15583. this.image = image;
  15584. this.resultPointCallback = resultPointCallback;
  15585. this.possibleCenters = [];
  15586. this.crossCheckStateCount = new Int32Array(5);
  15587. this.resultPointCallback = resultPointCallback;
  15588. }
  15589. getImage() {
  15590. return this.image;
  15591. }
  15592. getPossibleCenters() {
  15593. return this.possibleCenters;
  15594. }
  15595. find(hints) {
  15596. const tryHarder = (hints !== null && hints !== undefined) && undefined !== hints.get(DecodeHintType$1.TRY_HARDER);
  15597. const pureBarcode = (hints !== null && hints !== undefined) && undefined !== hints.get(DecodeHintType$1.PURE_BARCODE);
  15598. const image = this.image;
  15599. const maxI = image.getHeight();
  15600. const maxJ = image.getWidth();
  15601. // We are looking for black/white/black/white/black modules in
  15602. // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
  15603. // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
  15604. // image, and then account for the center being 3 modules in size. This gives the smallest
  15605. // number of pixels the center could be, so skip this often. When trying harder, look for all
  15606. // QR versions regardless of how dense they are.
  15607. let iSkip = Math.floor((3 * maxI) / (4 * FinderPatternFinder.MAX_MODULES));
  15608. if (iSkip < FinderPatternFinder.MIN_SKIP || tryHarder) {
  15609. iSkip = FinderPatternFinder.MIN_SKIP;
  15610. }
  15611. let done = false;
  15612. const stateCount = new Int32Array(5);
  15613. for (let i = iSkip - 1; i < maxI && !done; i += iSkip) {
  15614. // Get a row of black/white values
  15615. stateCount[0] = 0;
  15616. stateCount[1] = 0;
  15617. stateCount[2] = 0;
  15618. stateCount[3] = 0;
  15619. stateCount[4] = 0;
  15620. let currentState = 0;
  15621. for (let j = 0; j < maxJ; j++) {
  15622. if (image.get(j, i)) {
  15623. // Black pixel
  15624. if ((currentState & 1) === 1) { // Counting white pixels
  15625. currentState++;
  15626. }
  15627. stateCount[currentState]++;
  15628. }
  15629. else { // White pixel
  15630. if ((currentState & 1) === 0) { // Counting black pixels
  15631. if (currentState === 4) { // A winner?
  15632. if (FinderPatternFinder.foundPatternCross(stateCount)) { // Yes
  15633. const confirmed = this.handlePossibleCenter(stateCount, i, j, pureBarcode);
  15634. if (confirmed === true) {
  15635. // Start examining every other line. Checking each line turned out to be too
  15636. // expensive and didn't improve performance.
  15637. iSkip = 2;
  15638. if (this.hasSkipped === true) {
  15639. done = this.haveMultiplyConfirmedCenters();
  15640. }
  15641. else {
  15642. const rowSkip = this.findRowSkip();
  15643. if (rowSkip > stateCount[2]) {
  15644. // Skip rows between row of lower confirmed center
  15645. // and top of presumed third confirmed center
  15646. // but back up a bit to get a full chance of detecting
  15647. // it, entire width of center of finder pattern
  15648. // Skip by rowSkip, but back off by stateCount[2] (size of last center
  15649. // of pattern we saw) to be conservative, and also back off by iSkip which
  15650. // is about to be re-added
  15651. i += rowSkip - stateCount[2] - iSkip;
  15652. j = maxJ - 1;
  15653. }
  15654. }
  15655. }
  15656. else {
  15657. stateCount[0] = stateCount[2];
  15658. stateCount[1] = stateCount[3];
  15659. stateCount[2] = stateCount[4];
  15660. stateCount[3] = 1;
  15661. stateCount[4] = 0;
  15662. currentState = 3;
  15663. continue;
  15664. }
  15665. // Clear state to start looking again
  15666. currentState = 0;
  15667. stateCount[0] = 0;
  15668. stateCount[1] = 0;
  15669. stateCount[2] = 0;
  15670. stateCount[3] = 0;
  15671. stateCount[4] = 0;
  15672. }
  15673. else { // No, shift counts back by two
  15674. stateCount[0] = stateCount[2];
  15675. stateCount[1] = stateCount[3];
  15676. stateCount[2] = stateCount[4];
  15677. stateCount[3] = 1;
  15678. stateCount[4] = 0;
  15679. currentState = 3;
  15680. }
  15681. }
  15682. else {
  15683. stateCount[++currentState]++;
  15684. }
  15685. }
  15686. else { // Counting white pixels
  15687. stateCount[currentState]++;
  15688. }
  15689. }
  15690. }
  15691. if (FinderPatternFinder.foundPatternCross(stateCount)) {
  15692. const confirmed = this.handlePossibleCenter(stateCount, i, maxJ, pureBarcode);
  15693. if (confirmed === true) {
  15694. iSkip = stateCount[0];
  15695. if (this.hasSkipped) {
  15696. // Found a third one
  15697. done = this.haveMultiplyConfirmedCenters();
  15698. }
  15699. }
  15700. }
  15701. }
  15702. const patternInfo = this.selectBestPatterns();
  15703. ResultPoint.orderBestPatterns(patternInfo);
  15704. return new FinderPatternInfo(patternInfo);
  15705. }
  15706. /**
  15707. * Given a count of black/white/black/white/black pixels just seen and an end position,
  15708. * figures the location of the center of this run.
  15709. */
  15710. static centerFromEnd(stateCount, end /*int*/) {
  15711. return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0;
  15712. }
  15713. /**
  15714. * @param stateCount count of black/white/black/white/black pixels just read
  15715. * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
  15716. * used by finder patterns to be considered a match
  15717. */
  15718. static foundPatternCross(stateCount) {
  15719. let totalModuleSize = 0;
  15720. for (let i = 0; i < 5; i++) {
  15721. const count = stateCount[i];
  15722. if (count === 0) {
  15723. return false;
  15724. }
  15725. totalModuleSize += count;
  15726. }
  15727. if (totalModuleSize < 7) {
  15728. return false;
  15729. }
  15730. const moduleSize = totalModuleSize / 7.0;
  15731. const maxVariance = moduleSize / 2.0;
  15732. // Allow less than 50% variance from 1-1-3-1-1 proportions
  15733. return Math.abs(moduleSize - stateCount[0]) < maxVariance &&
  15734. Math.abs(moduleSize - stateCount[1]) < maxVariance &&
  15735. Math.abs(3.0 * moduleSize - stateCount[2]) < 3 * maxVariance &&
  15736. Math.abs(moduleSize - stateCount[3]) < maxVariance &&
  15737. Math.abs(moduleSize - stateCount[4]) < maxVariance;
  15738. }
  15739. getCrossCheckStateCount() {
  15740. const crossCheckStateCount = this.crossCheckStateCount;
  15741. crossCheckStateCount[0] = 0;
  15742. crossCheckStateCount[1] = 0;
  15743. crossCheckStateCount[2] = 0;
  15744. crossCheckStateCount[3] = 0;
  15745. crossCheckStateCount[4] = 0;
  15746. return crossCheckStateCount;
  15747. }
  15748. /**
  15749. * After a vertical and horizontal scan finds a potential finder pattern, this method
  15750. * "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
  15751. * finder pattern to see if the same proportion is detected.
  15752. *
  15753. * @param startI row where a finder pattern was detected
  15754. * @param centerJ center of the section that appears to cross a finder pattern
  15755. * @param maxCount maximum reasonable number of modules that should be
  15756. * observed in any reading state, based on the results of the horizontal scan
  15757. * @param originalStateCountTotal The original state count total.
  15758. * @return true if proportions are withing expected limits
  15759. */
  15760. crossCheckDiagonal(startI /*int*/, centerJ /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {
  15761. const stateCount = this.getCrossCheckStateCount();
  15762. // Start counting up, left from center finding black center mass
  15763. let i = 0;
  15764. const image = this.image;
  15765. while (startI >= i && centerJ >= i && image.get(centerJ - i, startI - i)) {
  15766. stateCount[2]++;
  15767. i++;
  15768. }
  15769. if (startI < i || centerJ < i) {
  15770. return false;
  15771. }
  15772. // Continue up, left finding white space
  15773. while (startI >= i && centerJ >= i && !image.get(centerJ - i, startI - i) &&
  15774. stateCount[1] <= maxCount) {
  15775. stateCount[1]++;
  15776. i++;
  15777. }
  15778. // If already too many modules in this state or ran off the edge:
  15779. if (startI < i || centerJ < i || stateCount[1] > maxCount) {
  15780. return false;
  15781. }
  15782. // Continue up, left finding black border
  15783. while (startI >= i && centerJ >= i && image.get(centerJ - i, startI - i) &&
  15784. stateCount[0] <= maxCount) {
  15785. stateCount[0]++;
  15786. i++;
  15787. }
  15788. if (stateCount[0] > maxCount) {
  15789. return false;
  15790. }
  15791. const maxI = image.getHeight();
  15792. const maxJ = image.getWidth();
  15793. // Now also count down, right from center
  15794. i = 1;
  15795. while (startI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, startI + i)) {
  15796. stateCount[2]++;
  15797. i++;
  15798. }
  15799. // Ran off the edge?
  15800. if (startI + i >= maxI || centerJ + i >= maxJ) {
  15801. return false;
  15802. }
  15803. while (startI + i < maxI && centerJ + i < maxJ && !image.get(centerJ + i, startI + i) &&
  15804. stateCount[3] < maxCount) {
  15805. stateCount[3]++;
  15806. i++;
  15807. }
  15808. if (startI + i >= maxI || centerJ + i >= maxJ || stateCount[3] >= maxCount) {
  15809. return false;
  15810. }
  15811. while (startI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, startI + i) &&
  15812. stateCount[4] < maxCount) {
  15813. stateCount[4]++;
  15814. i++;
  15815. }
  15816. if (stateCount[4] >= maxCount) {
  15817. return false;
  15818. }
  15819. // If we found a finder-pattern-like section, but its size is more than 100% different than
  15820. // the original, assume it's a false positive
  15821. const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
  15822. return Math.abs(stateCountTotal - originalStateCountTotal) < 2 * originalStateCountTotal &&
  15823. FinderPatternFinder.foundPatternCross(stateCount);
  15824. }
  15825. /**
  15826. * <p>After a horizontal scan finds a potential finder pattern, this method
  15827. * "cross-checks" by scanning down vertically through the center of the possible
  15828. * finder pattern to see if the same proportion is detected.</p>
  15829. *
  15830. * @param startI row where a finder pattern was detected
  15831. * @param centerJ center of the section that appears to cross a finder pattern
  15832. * @param maxCount maximum reasonable number of modules that should be
  15833. * observed in any reading state, based on the results of the horizontal scan
  15834. * @return vertical center of finder pattern, or {@link Float#NaN} if not found
  15835. */
  15836. crossCheckVertical(startI /*int*/, centerJ /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {
  15837. const image = this.image;
  15838. const maxI = image.getHeight();
  15839. const stateCount = this.getCrossCheckStateCount();
  15840. // Start counting up from center
  15841. let i = startI;
  15842. while (i >= 0 && image.get(centerJ, i)) {
  15843. stateCount[2]++;
  15844. i--;
  15845. }
  15846. if (i < 0) {
  15847. return NaN;
  15848. }
  15849. while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {
  15850. stateCount[1]++;
  15851. i--;
  15852. }
  15853. // If already too many modules in this state or ran off the edge:
  15854. if (i < 0 || stateCount[1] > maxCount) {
  15855. return NaN;
  15856. }
  15857. while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {
  15858. stateCount[0]++;
  15859. i--;
  15860. }
  15861. if (stateCount[0] > maxCount) {
  15862. return NaN;
  15863. }
  15864. // Now also count down from center
  15865. i = startI + 1;
  15866. while (i < maxI && image.get(centerJ, i)) {
  15867. stateCount[2]++;
  15868. i++;
  15869. }
  15870. if (i === maxI) {
  15871. return NaN;
  15872. }
  15873. while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {
  15874. stateCount[3]++;
  15875. i++;
  15876. }
  15877. if (i === maxI || stateCount[3] >= maxCount) {
  15878. return NaN;
  15879. }
  15880. while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {
  15881. stateCount[4]++;
  15882. i++;
  15883. }
  15884. if (stateCount[4] >= maxCount) {
  15885. return NaN;
  15886. }
  15887. // If we found a finder-pattern-like section, but its size is more than 40% different than
  15888. // the original, assume it's a false positive
  15889. const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
  15890. stateCount[4];
  15891. if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
  15892. return NaN;
  15893. }
  15894. return FinderPatternFinder.foundPatternCross(stateCount) ? FinderPatternFinder.centerFromEnd(stateCount, i) : NaN;
  15895. }
  15896. /**
  15897. * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
  15898. * except it reads horizontally instead of vertically. This is used to cross-cross
  15899. * check a vertical cross check and locate the real center of the alignment pattern.</p>
  15900. */
  15901. crossCheckHorizontal(startJ /*int*/, centerI /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {
  15902. const image = this.image;
  15903. const maxJ = image.getWidth();
  15904. const stateCount = this.getCrossCheckStateCount();
  15905. let j = startJ;
  15906. while (j >= 0 && image.get(j, centerI)) {
  15907. stateCount[2]++;
  15908. j--;
  15909. }
  15910. if (j < 0) {
  15911. return NaN;
  15912. }
  15913. while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {
  15914. stateCount[1]++;
  15915. j--;
  15916. }
  15917. if (j < 0 || stateCount[1] > maxCount) {
  15918. return NaN;
  15919. }
  15920. while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {
  15921. stateCount[0]++;
  15922. j--;
  15923. }
  15924. if (stateCount[0] > maxCount) {
  15925. return NaN;
  15926. }
  15927. j = startJ + 1;
  15928. while (j < maxJ && image.get(j, centerI)) {
  15929. stateCount[2]++;
  15930. j++;
  15931. }
  15932. if (j === maxJ) {
  15933. return NaN;
  15934. }
  15935. while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {
  15936. stateCount[3]++;
  15937. j++;
  15938. }
  15939. if (j === maxJ || stateCount[3] >= maxCount) {
  15940. return NaN;
  15941. }
  15942. while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {
  15943. stateCount[4]++;
  15944. j++;
  15945. }
  15946. if (stateCount[4] >= maxCount) {
  15947. return NaN;
  15948. }
  15949. // If we found a finder-pattern-like section, but its size is significantly different than
  15950. // the original, assume it's a false positive
  15951. const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
  15952. stateCount[4];
  15953. if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
  15954. return NaN;
  15955. }
  15956. return FinderPatternFinder.foundPatternCross(stateCount) ? FinderPatternFinder.centerFromEnd(stateCount, j) : NaN;
  15957. }
  15958. /**
  15959. * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
  15960. * cross check with a vertical scan, and if successful, will, ah, cross-cross-check
  15961. * with another horizontal scan. This is needed primarily to locate the real horizontal
  15962. * center of the pattern in cases of extreme skew.
  15963. * And then we cross-cross-cross check with another diagonal scan.</p>
  15964. *
  15965. * <p>If that succeeds the finder pattern location is added to a list that tracks
  15966. * the number of times each location has been nearly-matched as a finder pattern.
  15967. * Each additional find is more evidence that the location is in fact a finder
  15968. * pattern center
  15969. *
  15970. * @param stateCount reading state module counts from horizontal scan
  15971. * @param i row where finder pattern may be found
  15972. * @param j end of possible finder pattern in row
  15973. * @param pureBarcode true if in "pure barcode" mode
  15974. * @return true if a finder pattern candidate was found this time
  15975. */
  15976. handlePossibleCenter(stateCount, i /*int*/, j /*int*/, pureBarcode) {
  15977. const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
  15978. stateCount[4];
  15979. let centerJ = FinderPatternFinder.centerFromEnd(stateCount, j);
  15980. let centerI = this.crossCheckVertical(i, /*(int) */ Math.floor(centerJ), stateCount[2], stateCountTotal);
  15981. if (!isNaN(centerI)) {
  15982. // Re-cross check
  15983. centerJ = this.crossCheckHorizontal(/*(int) */ Math.floor(centerJ), /*(int) */ Math.floor(centerI), stateCount[2], stateCountTotal);
  15984. if (!isNaN(centerJ) &&
  15985. (!pureBarcode || this.crossCheckDiagonal(/*(int) */ Math.floor(centerI), /*(int) */ Math.floor(centerJ), stateCount[2], stateCountTotal))) {
  15986. const estimatedModuleSize = stateCountTotal / 7.0;
  15987. let found = false;
  15988. const possibleCenters = this.possibleCenters;
  15989. for (let index = 0, length = possibleCenters.length; index < length; index++) {
  15990. const center = possibleCenters[index];
  15991. // Look for about the same center and module size:
  15992. if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
  15993. possibleCenters[index] = center.combineEstimate(centerI, centerJ, estimatedModuleSize);
  15994. found = true;
  15995. break;
  15996. }
  15997. }
  15998. if (!found) {
  15999. const point = new FinderPattern$1(centerJ, centerI, estimatedModuleSize);
  16000. possibleCenters.push(point);
  16001. if (this.resultPointCallback !== null && this.resultPointCallback !== undefined) {
  16002. this.resultPointCallback.foundPossibleResultPoint(point);
  16003. }
  16004. }
  16005. return true;
  16006. }
  16007. }
  16008. return false;
  16009. }
  16010. /**
  16011. * @return number of rows we could safely skip during scanning, based on the first
  16012. * two finder patterns that have been located. In some cases their position will
  16013. * allow us to infer that the third pattern must lie below a certain point farther
  16014. * down in the image.
  16015. */
  16016. findRowSkip() {
  16017. const max = this.possibleCenters.length;
  16018. if (max <= 1) {
  16019. return 0;
  16020. }
  16021. let firstConfirmedCenter = null;
  16022. for (const center of this.possibleCenters) {
  16023. if (center.getCount() >= FinderPatternFinder.CENTER_QUORUM) {
  16024. if (firstConfirmedCenter == null) {
  16025. firstConfirmedCenter = center;
  16026. }
  16027. else {
  16028. // We have two confirmed centers
  16029. // How far down can we skip before resuming looking for the next
  16030. // pattern? In the worst case, only the difference between the
  16031. // difference in the x / y coordinates of the two centers.
  16032. // This is the case where you find top left last.
  16033. this.hasSkipped = true;
  16034. return /*(int) */ Math.floor((Math.abs(firstConfirmedCenter.getX() - center.getX()) -
  16035. Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2);
  16036. }
  16037. }
  16038. }
  16039. return 0;
  16040. }
  16041. /**
  16042. * @return true iff we have found at least 3 finder patterns that have been detected
  16043. * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
  16044. * candidates is "pretty similar"
  16045. */
  16046. haveMultiplyConfirmedCenters() {
  16047. let confirmedCount = 0;
  16048. let totalModuleSize = 0.0;
  16049. const max = this.possibleCenters.length;
  16050. for (const pattern of this.possibleCenters) {
  16051. if (pattern.getCount() >= FinderPatternFinder.CENTER_QUORUM) {
  16052. confirmedCount++;
  16053. totalModuleSize += pattern.getEstimatedModuleSize();
  16054. }
  16055. }
  16056. if (confirmedCount < 3) {
  16057. return false;
  16058. }
  16059. // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
  16060. // and that we need to keep looking. We detect this by asking if the estimated module sizes
  16061. // vary too much. We arbitrarily say that when the total deviation from average exceeds
  16062. // 5% of the total module size estimates, it's too much.
  16063. const average = totalModuleSize / max;
  16064. let totalDeviation = 0.0;
  16065. for (const pattern of this.possibleCenters) {
  16066. totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);
  16067. }
  16068. return totalDeviation <= 0.05 * totalModuleSize;
  16069. }
  16070. /**
  16071. * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
  16072. * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
  16073. * size differs from the average among those patterns the least
  16074. * @throws NotFoundException if 3 such finder patterns do not exist
  16075. */
  16076. selectBestPatterns() {
  16077. const startSize = this.possibleCenters.length;
  16078. if (startSize < 3) {
  16079. // Couldn't find enough finder patterns
  16080. throw new NotFoundException();
  16081. }
  16082. const possibleCenters = this.possibleCenters;
  16083. let average;
  16084. // Filter outlier possibilities whose module size is too different
  16085. if (startSize > 3) {
  16086. // But we can only afford to do so if we have at least 4 possibilities to choose from
  16087. let totalModuleSize = 0.0;
  16088. let square = 0.0;
  16089. for (const center of this.possibleCenters) {
  16090. const size = center.getEstimatedModuleSize();
  16091. totalModuleSize += size;
  16092. square += size * size;
  16093. }
  16094. average = totalModuleSize / startSize;
  16095. let stdDev = Math.sqrt(square / startSize - average * average);
  16096. possibleCenters.sort(
  16097. /**
  16098. * <p>Orders by furthest from average</p>
  16099. */
  16100. // FurthestFromAverageComparator implements Comparator<FinderPattern>
  16101. (center1, center2) => {
  16102. const dA = Math.abs(center2.getEstimatedModuleSize() - average);
  16103. const dB = Math.abs(center1.getEstimatedModuleSize() - average);
  16104. return dA < dB ? -1 : dA > dB ? 1 : 0;
  16105. });
  16106. const limit = Math.max(0.2 * average, stdDev);
  16107. for (let i = 0; i < possibleCenters.length && possibleCenters.length > 3; i++) {
  16108. const pattern = possibleCenters[i];
  16109. if (Math.abs(pattern.getEstimatedModuleSize() - average) > limit) {
  16110. possibleCenters.splice(i, 1);
  16111. i--;
  16112. }
  16113. }
  16114. }
  16115. if (possibleCenters.length > 3) {
  16116. // Throw away all but those first size candidate points we found.
  16117. let totalModuleSize = 0.0;
  16118. for (const possibleCenter of possibleCenters) {
  16119. totalModuleSize += possibleCenter.getEstimatedModuleSize();
  16120. }
  16121. average = totalModuleSize / possibleCenters.length;
  16122. possibleCenters.sort(
  16123. /**
  16124. * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
  16125. */
  16126. // CenterComparator implements Comparator<FinderPattern>
  16127. (center1, center2) => {
  16128. if (center2.getCount() === center1.getCount()) {
  16129. const dA = Math.abs(center2.getEstimatedModuleSize() - average);
  16130. const dB = Math.abs(center1.getEstimatedModuleSize() - average);
  16131. return dA < dB ? 1 : dA > dB ? -1 : 0;
  16132. }
  16133. else {
  16134. return center2.getCount() - center1.getCount();
  16135. }
  16136. });
  16137. possibleCenters.splice(3); // this is not realy necessary as we only return first 3 anyway
  16138. }
  16139. return [
  16140. possibleCenters[0],
  16141. possibleCenters[1],
  16142. possibleCenters[2]
  16143. ];
  16144. }
  16145. }
  16146. FinderPatternFinder.CENTER_QUORUM = 2;
  16147. FinderPatternFinder.MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
  16148. FinderPatternFinder.MAX_MODULES = 57; // support up to version 10 for mobile clients
  16149. /*
  16150. * Copyright 2007 ZXing authors
  16151. *
  16152. * Licensed under the Apache License, Version 2.0 (the "License");
  16153. * you may not use this file except in compliance with the License.
  16154. * You may obtain a copy of the License at
  16155. *
  16156. * http://www.apache.org/licenses/LICENSE-2.0
  16157. *
  16158. * Unless required by applicable law or agreed to in writing, software
  16159. * distributed under the License is distributed on an "AS IS" BASIS,
  16160. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16161. * See the License for the specific language governing permissions and
  16162. * limitations under the License.
  16163. */
  16164. /*import java.util.Map;*/
  16165. /**
  16166. * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
  16167. * is rotated or skewed, or partially obscured.</p>
  16168. *
  16169. * @author Sean Owen
  16170. */
  16171. class Detector$2 {
  16172. constructor(image) {
  16173. this.image = image;
  16174. }
  16175. getImage() {
  16176. return this.image;
  16177. }
  16178. getResultPointCallback() {
  16179. return this.resultPointCallback;
  16180. }
  16181. /**
  16182. * <p>Detects a QR Code in an image.</p>
  16183. *
  16184. * @return {@link DetectorResult} encapsulating results of detecting a QR Code
  16185. * @throws NotFoundException if QR Code cannot be found
  16186. * @throws FormatException if a QR Code cannot be decoded
  16187. */
  16188. // public detect(): DetectorResult /*throws NotFoundException, FormatException*/ {
  16189. // return detect(null)
  16190. // }
  16191. /**
  16192. * <p>Detects a QR Code in an image.</p>
  16193. *
  16194. * @param hints optional hints to detector
  16195. * @return {@link DetectorResult} encapsulating results of detecting a QR Code
  16196. * @throws NotFoundException if QR Code cannot be found
  16197. * @throws FormatException if a QR Code cannot be decoded
  16198. */
  16199. detect(hints) {
  16200. this.resultPointCallback = (hints === null || hints === undefined) ? null :
  16201. /*(ResultPointCallback) */ hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);
  16202. const finder = new FinderPatternFinder(this.image, this.resultPointCallback);
  16203. const info = finder.find(hints);
  16204. return this.processFinderPatternInfo(info);
  16205. }
  16206. processFinderPatternInfo(info) {
  16207. const topLeft = info.getTopLeft();
  16208. const topRight = info.getTopRight();
  16209. const bottomLeft = info.getBottomLeft();
  16210. const moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft);
  16211. if (moduleSize < 1.0) {
  16212. throw new NotFoundException('No pattern found in proccess finder.');
  16213. }
  16214. const dimension = Detector$2.computeDimension(topLeft, topRight, bottomLeft, moduleSize);
  16215. const provisionalVersion = Version$1.getProvisionalVersionForDimension(dimension);
  16216. const modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
  16217. let alignmentPattern = null;
  16218. // Anything above version 1 has an alignment pattern
  16219. if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
  16220. // Guess where a "bottom right" finder pattern would have been
  16221. const bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
  16222. const bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
  16223. // Estimate that alignment pattern is closer by 3 modules
  16224. // from "bottom right" to known top left location
  16225. const correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters;
  16226. const estAlignmentX = /*(int) */ Math.floor(topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
  16227. const estAlignmentY = /*(int) */ Math.floor(topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
  16228. // Kind of arbitrary -- expand search radius before giving up
  16229. for (let i = 4; i <= 16; i <<= 1) {
  16230. try {
  16231. alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i);
  16232. break;
  16233. }
  16234. catch (re /*NotFoundException*/) {
  16235. if (!(re instanceof NotFoundException)) {
  16236. throw re;
  16237. }
  16238. // try next round
  16239. }
  16240. }
  16241. // If we didn't find alignment pattern... well try anyway without it
  16242. }
  16243. const transform = Detector$2.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
  16244. const bits = Detector$2.sampleGrid(this.image, transform, dimension);
  16245. let points;
  16246. if (alignmentPattern === null) {
  16247. points = [bottomLeft, topLeft, topRight];
  16248. }
  16249. else {
  16250. points = [bottomLeft, topLeft, topRight, alignmentPattern];
  16251. }
  16252. return new DetectorResult(bits, points);
  16253. }
  16254. static createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension /*int*/) {
  16255. const dimMinusThree = dimension - 3.5;
  16256. let bottomRightX; /*float*/
  16257. let bottomRightY; /*float*/
  16258. let sourceBottomRightX; /*float*/
  16259. let sourceBottomRightY; /*float*/
  16260. if (alignmentPattern !== null) {
  16261. bottomRightX = alignmentPattern.getX();
  16262. bottomRightY = alignmentPattern.getY();
  16263. sourceBottomRightX = dimMinusThree - 3.0;
  16264. sourceBottomRightY = sourceBottomRightX;
  16265. }
  16266. else {
  16267. // Don't have an alignment pattern, just make up the bottom-right point
  16268. bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX();
  16269. bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY();
  16270. sourceBottomRightX = dimMinusThree;
  16271. sourceBottomRightY = dimMinusThree;
  16272. }
  16273. return PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.getX(), topLeft.getY(), topRight.getX(), topRight.getY(), bottomRightX, bottomRightY, bottomLeft.getX(), bottomLeft.getY());
  16274. }
  16275. static sampleGrid(image, transform, dimension /*int*/) {
  16276. const sampler = GridSamplerInstance.getInstance();
  16277. return sampler.sampleGridWithTransform(image, dimension, dimension, transform);
  16278. }
  16279. /**
  16280. * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
  16281. * of the finder patterns and estimated module size.</p>
  16282. */
  16283. static computeDimension(topLeft, topRight, bottomLeft, moduleSize /*float*/) {
  16284. const tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
  16285. const tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
  16286. let dimension = Math.floor((tltrCentersDimension + tlblCentersDimension) / 2) + 7;
  16287. switch (dimension & 0x03) { // mod 4
  16288. case 0:
  16289. dimension++;
  16290. break;
  16291. // 1? do nothing
  16292. case 2:
  16293. dimension--;
  16294. break;
  16295. case 3:
  16296. throw new NotFoundException('Dimensions could be not found.');
  16297. }
  16298. return dimension;
  16299. }
  16300. /**
  16301. * <p>Computes an average estimated module size based on estimated derived from the positions
  16302. * of the three finder patterns.</p>
  16303. *
  16304. * @param topLeft detected top-left finder pattern center
  16305. * @param topRight detected top-right finder pattern center
  16306. * @param bottomLeft detected bottom-left finder pattern center
  16307. * @return estimated module size
  16308. */
  16309. calculateModuleSize(topLeft, topRight, bottomLeft) {
  16310. // Take the average
  16311. return (this.calculateModuleSizeOneWay(topLeft, topRight) +
  16312. this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0;
  16313. }
  16314. /**
  16315. * <p>Estimates module size based on two finder patterns -- it uses
  16316. * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
  16317. * width of each, measuring along the axis between their centers.</p>
  16318. */
  16319. calculateModuleSizeOneWay(pattern, otherPattern) {
  16320. const moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */ Math.floor(pattern.getX()),
  16321. /*(int) */ Math.floor(pattern.getY()),
  16322. /*(int) */ Math.floor(otherPattern.getX()),
  16323. /*(int) */ Math.floor(otherPattern.getY()));
  16324. const moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */ Math.floor(otherPattern.getX()),
  16325. /*(int) */ Math.floor(otherPattern.getY()),
  16326. /*(int) */ Math.floor(pattern.getX()),
  16327. /*(int) */ Math.floor(pattern.getY()));
  16328. if (isNaN(moduleSizeEst1)) {
  16329. return moduleSizeEst2 / 7.0;
  16330. }
  16331. if (isNaN(moduleSizeEst2)) {
  16332. return moduleSizeEst1 / 7.0;
  16333. }
  16334. // Average them, and divide by 7 since we've counted the width of 3 black modules,
  16335. // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
  16336. return (moduleSizeEst1 + moduleSizeEst2) / 14.0;
  16337. }
  16338. /**
  16339. * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
  16340. * a finder pattern by looking for a black-white-black run from the center in the direction
  16341. * of another point (another finder pattern center), and in the opposite direction too.
  16342. */
  16343. sizeOfBlackWhiteBlackRunBothWays(fromX /*int*/, fromY /*int*/, toX /*int*/, toY /*int*/) {
  16344. let result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
  16345. // Now count other way -- don't run off image though of course
  16346. let scale = 1.0;
  16347. let otherToX = fromX - (toX - fromX);
  16348. if (otherToX < 0) {
  16349. scale = fromX / /*(float) */ (fromX - otherToX);
  16350. otherToX = 0;
  16351. }
  16352. else if (otherToX >= this.image.getWidth()) {
  16353. scale = (this.image.getWidth() - 1 - fromX) / /*(float) */ (otherToX - fromX);
  16354. otherToX = this.image.getWidth() - 1;
  16355. }
  16356. let otherToY = /*(int) */ Math.floor(fromY - (toY - fromY) * scale);
  16357. scale = 1.0;
  16358. if (otherToY < 0) {
  16359. scale = fromY / /*(float) */ (fromY - otherToY);
  16360. otherToY = 0;
  16361. }
  16362. else if (otherToY >= this.image.getHeight()) {
  16363. scale = (this.image.getHeight() - 1 - fromY) / /*(float) */ (otherToY - fromY);
  16364. otherToY = this.image.getHeight() - 1;
  16365. }
  16366. otherToX = /*(int) */ Math.floor(fromX + (otherToX - fromX) * scale);
  16367. result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
  16368. // Middle pixel is double-counted this way; subtract 1
  16369. return result - 1.0;
  16370. }
  16371. /**
  16372. * <p>This method traces a line from a point in the image, in the direction towards another point.
  16373. * It begins in a black region, and keeps going until it finds white, then black, then white again.
  16374. * It reports the distance from the start to this point.</p>
  16375. *
  16376. * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
  16377. * may be skewed or rotated.</p>
  16378. */
  16379. sizeOfBlackWhiteBlackRun(fromX /*int*/, fromY /*int*/, toX /*int*/, toY /*int*/) {
  16380. // Mild variant of Bresenham's algorithm
  16381. // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
  16382. const steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
  16383. if (steep) {
  16384. let temp = fromX;
  16385. fromX = fromY;
  16386. fromY = temp;
  16387. temp = toX;
  16388. toX = toY;
  16389. toY = temp;
  16390. }
  16391. const dx = Math.abs(toX - fromX);
  16392. const dy = Math.abs(toY - fromY);
  16393. let error = -dx / 2;
  16394. const xstep = fromX < toX ? 1 : -1;
  16395. const ystep = fromY < toY ? 1 : -1;
  16396. // In black pixels, looking for white, first or second time.
  16397. let state = 0;
  16398. // Loop up until x == toX, but not beyond
  16399. const xLimit = toX + xstep;
  16400. for (let x = fromX, y = fromY; x !== xLimit; x += xstep) {
  16401. const realX = steep ? y : x;
  16402. const realY = steep ? x : y;
  16403. // Does current pixel mean we have moved white to black or vice versa?
  16404. // Scanning black in state 0,2 and white in state 1, so if we find the wrong
  16405. // color, advance to next state or end if we are in state 2 already
  16406. if ((state === 1) === this.image.get(realX, realY)) {
  16407. if (state === 2) {
  16408. return MathUtils.distance(x, y, fromX, fromY);
  16409. }
  16410. state++;
  16411. }
  16412. error += dy;
  16413. if (error > 0) {
  16414. if (y === toY) {
  16415. break;
  16416. }
  16417. y += ystep;
  16418. error -= dx;
  16419. }
  16420. }
  16421. // Found black-white-black; give the benefit of the doubt that the next pixel outside the image
  16422. // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
  16423. // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
  16424. if (state === 2) {
  16425. return MathUtils.distance(toX + xstep, toY, fromX, fromY);
  16426. }
  16427. // else we didn't find even black-white-black; no estimate is really possible
  16428. return NaN;
  16429. }
  16430. /**
  16431. * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
  16432. * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
  16433. *
  16434. * @param overallEstModuleSize estimated module size so far
  16435. * @param estAlignmentX x coordinate of center of area probably containing alignment pattern
  16436. * @param estAlignmentY y coordinate of above
  16437. * @param allowanceFactor number of pixels in all directions to search from the center
  16438. * @return {@link AlignmentPattern} if found, or null otherwise
  16439. * @throws NotFoundException if an unexpected error occurs during detection
  16440. */
  16441. findAlignmentInRegion(overallEstModuleSize /*float*/, estAlignmentX /*int*/, estAlignmentY /*int*/, allowanceFactor /*float*/) {
  16442. // Look for an alignment pattern (3 modules in size) around where it
  16443. // should be
  16444. const allowance = /*(int) */ Math.floor(allowanceFactor * overallEstModuleSize);
  16445. const alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
  16446. const alignmentAreaRightX = Math.min(this.image.getWidth() - 1, estAlignmentX + allowance);
  16447. if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {
  16448. throw new NotFoundException('Alignment top exceeds estimated module size.');
  16449. }
  16450. const alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
  16451. const alignmentAreaBottomY = Math.min(this.image.getHeight() - 1, estAlignmentY + allowance);
  16452. if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) {
  16453. throw new NotFoundException('Alignment bottom exceeds estimated module size.');
  16454. }
  16455. const alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback);
  16456. return alignmentFinder.find();
  16457. }
  16458. }
  16459. /*
  16460. * Copyright 2007 ZXing authors
  16461. *
  16462. * Licensed under the Apache License, Version 2.0 (the "License");
  16463. * you may not use this file except in compliance with the License.
  16464. * You may obtain a copy of the License at
  16465. *
  16466. * http://www.apache.org/licenses/LICENSE-2.0
  16467. *
  16468. * Unless required by applicable law or agreed to in writing, software
  16469. * distributed under the License is distributed on an "AS IS" BASIS,
  16470. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16471. * See the License for the specific language governing permissions and
  16472. * limitations under the License.
  16473. */
  16474. /*import java.util.List;*/
  16475. /*import java.util.Map;*/
  16476. /**
  16477. * This implementation can detect and decode QR Codes in an image.
  16478. *
  16479. * @author Sean Owen
  16480. */
  16481. class QRCodeReader {
  16482. constructor() {
  16483. this.decoder = new Decoder$2();
  16484. }
  16485. getDecoder() {
  16486. return this.decoder;
  16487. }
  16488. /**
  16489. * Locates and decodes a QR code in an image.
  16490. *
  16491. * @return a representing: string the content encoded by the QR code
  16492. * @throws NotFoundException if a QR code cannot be found
  16493. * @throws FormatException if a QR code cannot be decoded
  16494. * @throws ChecksumException if error correction fails
  16495. */
  16496. /*@Override*/
  16497. // public decode(image: BinaryBitmap): Result /*throws NotFoundException, ChecksumException, FormatException */ {
  16498. // return this.decode(image, null)
  16499. // }
  16500. /*@Override*/
  16501. decode(image, hints) {
  16502. let decoderResult;
  16503. let points;
  16504. if (hints !== undefined && hints !== null && undefined !== hints.get(DecodeHintType$1.PURE_BARCODE)) {
  16505. const bits = QRCodeReader.extractPureBits(image.getBlackMatrix());
  16506. decoderResult = this.decoder.decodeBitMatrix(bits, hints);
  16507. points = QRCodeReader.NO_POINTS;
  16508. }
  16509. else {
  16510. const detectorResult = new Detector$2(image.getBlackMatrix()).detect(hints);
  16511. decoderResult = this.decoder.decodeBitMatrix(detectorResult.getBits(), hints);
  16512. points = detectorResult.getPoints();
  16513. }
  16514. // If the code was mirrored: swap the bottom-left and the top-right points.
  16515. if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {
  16516. decoderResult.getOther().applyMirroredCorrection(points);
  16517. }
  16518. const result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), undefined, points, BarcodeFormat$1.QR_CODE, undefined);
  16519. const byteSegments = decoderResult.getByteSegments();
  16520. if (byteSegments !== null) {
  16521. result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS, byteSegments);
  16522. }
  16523. const ecLevel = decoderResult.getECLevel();
  16524. if (ecLevel !== null) {
  16525. result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL, ecLevel);
  16526. }
  16527. if (decoderResult.hasStructuredAppend()) {
  16528. result.putMetadata(ResultMetadataType$1.STRUCTURED_APPEND_SEQUENCE, decoderResult.getStructuredAppendSequenceNumber());
  16529. result.putMetadata(ResultMetadataType$1.STRUCTURED_APPEND_PARITY, decoderResult.getStructuredAppendParity());
  16530. }
  16531. return result;
  16532. }
  16533. /*@Override*/
  16534. reset() {
  16535. // do nothing
  16536. }
  16537. /**
  16538. * This method detects a code in a "pure" image -- that is, pure monochrome image
  16539. * which contains only an unrotated, unskewed, image of a code, with some white border
  16540. * around it. This is a specialized method that works exceptionally fast in this special
  16541. * case.
  16542. *
  16543. * @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)
  16544. */
  16545. static extractPureBits(image) {
  16546. const leftTopBlack = image.getTopLeftOnBit();
  16547. const rightBottomBlack = image.getBottomRightOnBit();
  16548. if (leftTopBlack === null || rightBottomBlack === null) {
  16549. throw new NotFoundException();
  16550. }
  16551. const moduleSize = this.moduleSize(leftTopBlack, image);
  16552. let top = leftTopBlack[1];
  16553. let bottom = rightBottomBlack[1];
  16554. let left = leftTopBlack[0];
  16555. let right = rightBottomBlack[0];
  16556. // Sanity check!
  16557. if (left >= right || top >= bottom) {
  16558. throw new NotFoundException();
  16559. }
  16560. if (bottom - top !== right - left) {
  16561. // Special case, where bottom-right module wasn't black so we found something else in the last row
  16562. // Assume it's a square, so use height as the width
  16563. right = left + (bottom - top);
  16564. if (right >= image.getWidth()) {
  16565. // Abort if that would not make sense -- off image
  16566. throw new NotFoundException();
  16567. }
  16568. }
  16569. const matrixWidth = Math.round((right - left + 1) / moduleSize);
  16570. const matrixHeight = Math.round((bottom - top + 1) / moduleSize);
  16571. if (matrixWidth <= 0 || matrixHeight <= 0) {
  16572. throw new NotFoundException();
  16573. }
  16574. if (matrixHeight !== matrixWidth) {
  16575. // Only possibly decode square regions
  16576. throw new NotFoundException();
  16577. }
  16578. // Push in the "border" by half the module width so that we start
  16579. // sampling in the middle of the module. Just in case the image is a
  16580. // little off, this will help recover.
  16581. const nudge = /*(int) */ Math.floor(moduleSize / 2.0);
  16582. top += nudge;
  16583. left += nudge;
  16584. // But careful that this does not sample off the edge
  16585. // "right" is the farthest-right valid pixel location -- right+1 is not necessarily
  16586. // This is positive by how much the inner x loop below would be too large
  16587. const nudgedTooFarRight = left + /*(int) */ Math.floor((matrixWidth - 1) * moduleSize) - right;
  16588. if (nudgedTooFarRight > 0) {
  16589. if (nudgedTooFarRight > nudge) {
  16590. // Neither way fits; abort
  16591. throw new NotFoundException();
  16592. }
  16593. left -= nudgedTooFarRight;
  16594. }
  16595. // See logic above
  16596. const nudgedTooFarDown = top + /*(int) */ Math.floor((matrixHeight - 1) * moduleSize) - bottom;
  16597. if (nudgedTooFarDown > 0) {
  16598. if (nudgedTooFarDown > nudge) {
  16599. // Neither way fits; abort
  16600. throw new NotFoundException();
  16601. }
  16602. top -= nudgedTooFarDown;
  16603. }
  16604. // Now just read off the bits
  16605. const bits = new BitMatrix(matrixWidth, matrixHeight);
  16606. for (let y = 0; y < matrixHeight; y++) {
  16607. const iOffset = top + /*(int) */ Math.floor(y * moduleSize);
  16608. for (let x = 0; x < matrixWidth; x++) {
  16609. if (image.get(left + /*(int) */ Math.floor(x * moduleSize), iOffset)) {
  16610. bits.set(x, y);
  16611. }
  16612. }
  16613. }
  16614. return bits;
  16615. }
  16616. static moduleSize(leftTopBlack, image) {
  16617. const height = image.getHeight();
  16618. const width = image.getWidth();
  16619. let x = leftTopBlack[0];
  16620. let y = leftTopBlack[1];
  16621. let inBlack = true;
  16622. let transitions = 0;
  16623. while (x < width && y < height) {
  16624. if (inBlack !== image.get(x, y)) {
  16625. if (++transitions === 5) {
  16626. break;
  16627. }
  16628. inBlack = !inBlack;
  16629. }
  16630. x++;
  16631. y++;
  16632. }
  16633. if (x === width || y === height) {
  16634. throw new NotFoundException();
  16635. }
  16636. return (x - leftTopBlack[0]) / 7.0;
  16637. }
  16638. }
  16639. QRCodeReader.NO_POINTS = new Array();
  16640. /*
  16641. * Copyright 2009 ZXing authors
  16642. *
  16643. * Licensed under the Apache License, Version 2.0 (the "License");
  16644. * you may not use this file except in compliance with the License.
  16645. * You may obtain a copy of the License at
  16646. *
  16647. * http://www.apache.org/licenses/LICENSE-2.0
  16648. *
  16649. * Unless required by applicable law or agreed to in writing, software
  16650. * distributed under the License is distributed on an "AS IS" BASIS,
  16651. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16652. * See the License for the specific language governing permissions and
  16653. * limitations under the License.
  16654. */
  16655. /**
  16656. * @author SITA Lab (kevin.osullivan@sita.aero)
  16657. * @author Guenther Grau
  16658. */
  16659. /*public final*/ class PDF417Common {
  16660. PDF417Common() {
  16661. }
  16662. /**
  16663. * @param moduleBitCount values to sum
  16664. * @return sum of values
  16665. * @deprecated call {@link MathUtils#sum(int[])}
  16666. */
  16667. // @Deprecated
  16668. static getBitCountSum(moduleBitCount) {
  16669. return MathUtils.sum(moduleBitCount);
  16670. }
  16671. static toIntArray(list) {
  16672. if (list == null || !list.length) {
  16673. return PDF417Common.EMPTY_INT_ARRAY;
  16674. }
  16675. const result = new Int32Array(list.length);
  16676. let i = 0;
  16677. for (const integer of list) {
  16678. result[i++] = integer;
  16679. }
  16680. return result;
  16681. }
  16682. /**
  16683. * @param symbol encoded symbol to translate to a codeword
  16684. * @return the codeword corresponding to the symbol.
  16685. */
  16686. static getCodeword(symbol /*int*/) {
  16687. const i = Arrays.binarySearch(PDF417Common.SYMBOL_TABLE, symbol & 0x3FFFF);
  16688. if (i < 0) {
  16689. return -1;
  16690. }
  16691. return (PDF417Common.CODEWORD_TABLE[i] - 1) % PDF417Common.NUMBER_OF_CODEWORDS;
  16692. }
  16693. }
  16694. PDF417Common.NUMBER_OF_CODEWORDS = 929;
  16695. // Maximum Codewords (Data + Error).
  16696. PDF417Common.MAX_CODEWORDS_IN_BARCODE = PDF417Common.NUMBER_OF_CODEWORDS - 1;
  16697. PDF417Common.MIN_ROWS_IN_BARCODE = 3;
  16698. PDF417Common.MAX_ROWS_IN_BARCODE = 90;
  16699. // One left row indication column + max 30 data columns + one right row indicator column
  16700. // public static /*final*/ MAX_CODEWORDS_IN_ROW: /*int*/ number = 32;
  16701. PDF417Common.MODULES_IN_CODEWORD = 17;
  16702. PDF417Common.MODULES_IN_STOP_PATTERN = 18;
  16703. PDF417Common.BARS_IN_MODULE = 8;
  16704. PDF417Common.EMPTY_INT_ARRAY = new Int32Array([]);
  16705. /**
  16706. * The sorted table of all possible symbols. Extracted from the PDF417
  16707. * specification. The index of a symbol in this table corresponds to the
  16708. * index into the codeword table.
  16709. */
  16710. PDF417Common.SYMBOL_TABLE = Int32Array.from([
  16711. 0x1025e, 0x1027a, 0x1029e, 0x102bc, 0x102f2, 0x102f4, 0x1032e, 0x1034e, 0x1035c, 0x10396, 0x103a6, 0x103ac,
  16712. 0x10422, 0x10428, 0x10436, 0x10442, 0x10444, 0x10448, 0x10450, 0x1045e, 0x10466, 0x1046c, 0x1047a, 0x10482,
  16713. 0x1049e, 0x104a0, 0x104bc, 0x104c6, 0x104d8, 0x104ee, 0x104f2, 0x104f4, 0x10504, 0x10508, 0x10510, 0x1051e,
  16714. 0x10520, 0x1053c, 0x10540, 0x10578, 0x10586, 0x1058c, 0x10598, 0x105b0, 0x105be, 0x105ce, 0x105dc, 0x105e2,
  16715. 0x105e4, 0x105e8, 0x105f6, 0x1062e, 0x1064e, 0x1065c, 0x1068e, 0x1069c, 0x106b8, 0x106de, 0x106fa, 0x10716,
  16716. 0x10726, 0x1072c, 0x10746, 0x1074c, 0x10758, 0x1076e, 0x10792, 0x10794, 0x107a2, 0x107a4, 0x107a8, 0x107b6,
  16717. 0x10822, 0x10828, 0x10842, 0x10848, 0x10850, 0x1085e, 0x10866, 0x1086c, 0x1087a, 0x10882, 0x10884, 0x10890,
  16718. 0x1089e, 0x108a0, 0x108bc, 0x108c6, 0x108cc, 0x108d8, 0x108ee, 0x108f2, 0x108f4, 0x10902, 0x10908, 0x1091e,
  16719. 0x10920, 0x1093c, 0x10940, 0x10978, 0x10986, 0x10998, 0x109b0, 0x109be, 0x109ce, 0x109dc, 0x109e2, 0x109e4,
  16720. 0x109e8, 0x109f6, 0x10a08, 0x10a10, 0x10a1e, 0x10a20, 0x10a3c, 0x10a40, 0x10a78, 0x10af0, 0x10b06, 0x10b0c,
  16721. 0x10b18, 0x10b30, 0x10b3e, 0x10b60, 0x10b7c, 0x10b8e, 0x10b9c, 0x10bb8, 0x10bc2, 0x10bc4, 0x10bc8, 0x10bd0,
  16722. 0x10bde, 0x10be6, 0x10bec, 0x10c2e, 0x10c4e, 0x10c5c, 0x10c62, 0x10c64, 0x10c68, 0x10c76, 0x10c8e, 0x10c9c,
  16723. 0x10cb8, 0x10cc2, 0x10cc4, 0x10cc8, 0x10cd0, 0x10cde, 0x10ce6, 0x10cec, 0x10cfa, 0x10d0e, 0x10d1c, 0x10d38,
  16724. 0x10d70, 0x10d7e, 0x10d82, 0x10d84, 0x10d88, 0x10d90, 0x10d9e, 0x10da0, 0x10dbc, 0x10dc6, 0x10dcc, 0x10dd8,
  16725. 0x10dee, 0x10df2, 0x10df4, 0x10e16, 0x10e26, 0x10e2c, 0x10e46, 0x10e58, 0x10e6e, 0x10e86, 0x10e8c, 0x10e98,
  16726. 0x10eb0, 0x10ebe, 0x10ece, 0x10edc, 0x10f0a, 0x10f12, 0x10f14, 0x10f22, 0x10f28, 0x10f36, 0x10f42, 0x10f44,
  16727. 0x10f48, 0x10f50, 0x10f5e, 0x10f66, 0x10f6c, 0x10fb2, 0x10fb4, 0x11022, 0x11028, 0x11042, 0x11048, 0x11050,
  16728. 0x1105e, 0x1107a, 0x11082, 0x11084, 0x11090, 0x1109e, 0x110a0, 0x110bc, 0x110c6, 0x110cc, 0x110d8, 0x110ee,
  16729. 0x110f2, 0x110f4, 0x11102, 0x1111e, 0x11120, 0x1113c, 0x11140, 0x11178, 0x11186, 0x11198, 0x111b0, 0x111be,
  16730. 0x111ce, 0x111dc, 0x111e2, 0x111e4, 0x111e8, 0x111f6, 0x11208, 0x1121e, 0x11220, 0x11278, 0x112f0, 0x1130c,
  16731. 0x11330, 0x1133e, 0x11360, 0x1137c, 0x1138e, 0x1139c, 0x113b8, 0x113c2, 0x113c8, 0x113d0, 0x113de, 0x113e6,
  16732. 0x113ec, 0x11408, 0x11410, 0x1141e, 0x11420, 0x1143c, 0x11440, 0x11478, 0x114f0, 0x115e0, 0x1160c, 0x11618,
  16733. 0x11630, 0x1163e, 0x11660, 0x1167c, 0x116c0, 0x116f8, 0x1171c, 0x11738, 0x11770, 0x1177e, 0x11782, 0x11784,
  16734. 0x11788, 0x11790, 0x1179e, 0x117a0, 0x117bc, 0x117c6, 0x117cc, 0x117d8, 0x117ee, 0x1182e, 0x11834, 0x1184e,
  16735. 0x1185c, 0x11862, 0x11864, 0x11868, 0x11876, 0x1188e, 0x1189c, 0x118b8, 0x118c2, 0x118c8, 0x118d0, 0x118de,
  16736. 0x118e6, 0x118ec, 0x118fa, 0x1190e, 0x1191c, 0x11938, 0x11970, 0x1197e, 0x11982, 0x11984, 0x11990, 0x1199e,
  16737. 0x119a0, 0x119bc, 0x119c6, 0x119cc, 0x119d8, 0x119ee, 0x119f2, 0x119f4, 0x11a0e, 0x11a1c, 0x11a38, 0x11a70,
  16738. 0x11a7e, 0x11ae0, 0x11afc, 0x11b08, 0x11b10, 0x11b1e, 0x11b20, 0x11b3c, 0x11b40, 0x11b78, 0x11b8c, 0x11b98,
  16739. 0x11bb0, 0x11bbe, 0x11bce, 0x11bdc, 0x11be2, 0x11be4, 0x11be8, 0x11bf6, 0x11c16, 0x11c26, 0x11c2c, 0x11c46,
  16740. 0x11c4c, 0x11c58, 0x11c6e, 0x11c86, 0x11c98, 0x11cb0, 0x11cbe, 0x11cce, 0x11cdc, 0x11ce2, 0x11ce4, 0x11ce8,
  16741. 0x11cf6, 0x11d06, 0x11d0c, 0x11d18, 0x11d30, 0x11d3e, 0x11d60, 0x11d7c, 0x11d8e, 0x11d9c, 0x11db8, 0x11dc4,
  16742. 0x11dc8, 0x11dd0, 0x11dde, 0x11de6, 0x11dec, 0x11dfa, 0x11e0a, 0x11e12, 0x11e14, 0x11e22, 0x11e24, 0x11e28,
  16743. 0x11e36, 0x11e42, 0x11e44, 0x11e50, 0x11e5e, 0x11e66, 0x11e6c, 0x11e82, 0x11e84, 0x11e88, 0x11e90, 0x11e9e,
  16744. 0x11ea0, 0x11ebc, 0x11ec6, 0x11ecc, 0x11ed8, 0x11eee, 0x11f1a, 0x11f2e, 0x11f32, 0x11f34, 0x11f4e, 0x11f5c,
  16745. 0x11f62, 0x11f64, 0x11f68, 0x11f76, 0x12048, 0x1205e, 0x12082, 0x12084, 0x12090, 0x1209e, 0x120a0, 0x120bc,
  16746. 0x120d8, 0x120f2, 0x120f4, 0x12108, 0x1211e, 0x12120, 0x1213c, 0x12140, 0x12178, 0x12186, 0x12198, 0x121b0,
  16747. 0x121be, 0x121e2, 0x121e4, 0x121e8, 0x121f6, 0x12204, 0x12210, 0x1221e, 0x12220, 0x12278, 0x122f0, 0x12306,
  16748. 0x1230c, 0x12330, 0x1233e, 0x12360, 0x1237c, 0x1238e, 0x1239c, 0x123b8, 0x123c2, 0x123c8, 0x123d0, 0x123e6,
  16749. 0x123ec, 0x1241e, 0x12420, 0x1243c, 0x124f0, 0x125e0, 0x12618, 0x1263e, 0x12660, 0x1267c, 0x126c0, 0x126f8,
  16750. 0x12738, 0x12770, 0x1277e, 0x12782, 0x12784, 0x12790, 0x1279e, 0x127a0, 0x127bc, 0x127c6, 0x127cc, 0x127d8,
  16751. 0x127ee, 0x12820, 0x1283c, 0x12840, 0x12878, 0x128f0, 0x129e0, 0x12bc0, 0x12c18, 0x12c30, 0x12c3e, 0x12c60,
  16752. 0x12c7c, 0x12cc0, 0x12cf8, 0x12df0, 0x12e1c, 0x12e38, 0x12e70, 0x12e7e, 0x12ee0, 0x12efc, 0x12f04, 0x12f08,
  16753. 0x12f10, 0x12f20, 0x12f3c, 0x12f40, 0x12f78, 0x12f86, 0x12f8c, 0x12f98, 0x12fb0, 0x12fbe, 0x12fce, 0x12fdc,
  16754. 0x1302e, 0x1304e, 0x1305c, 0x13062, 0x13068, 0x1308e, 0x1309c, 0x130b8, 0x130c2, 0x130c8, 0x130d0, 0x130de,
  16755. 0x130ec, 0x130fa, 0x1310e, 0x13138, 0x13170, 0x1317e, 0x13182, 0x13184, 0x13190, 0x1319e, 0x131a0, 0x131bc,
  16756. 0x131c6, 0x131cc, 0x131d8, 0x131f2, 0x131f4, 0x1320e, 0x1321c, 0x13270, 0x1327e, 0x132e0, 0x132fc, 0x13308,
  16757. 0x1331e, 0x13320, 0x1333c, 0x13340, 0x13378, 0x13386, 0x13398, 0x133b0, 0x133be, 0x133ce, 0x133dc, 0x133e2,
  16758. 0x133e4, 0x133e8, 0x133f6, 0x1340e, 0x1341c, 0x13438, 0x13470, 0x1347e, 0x134e0, 0x134fc, 0x135c0, 0x135f8,
  16759. 0x13608, 0x13610, 0x1361e, 0x13620, 0x1363c, 0x13640, 0x13678, 0x136f0, 0x1370c, 0x13718, 0x13730, 0x1373e,
  16760. 0x13760, 0x1377c, 0x1379c, 0x137b8, 0x137c2, 0x137c4, 0x137c8, 0x137d0, 0x137de, 0x137e6, 0x137ec, 0x13816,
  16761. 0x13826, 0x1382c, 0x13846, 0x1384c, 0x13858, 0x1386e, 0x13874, 0x13886, 0x13898, 0x138b0, 0x138be, 0x138ce,
  16762. 0x138dc, 0x138e2, 0x138e4, 0x138e8, 0x13906, 0x1390c, 0x13930, 0x1393e, 0x13960, 0x1397c, 0x1398e, 0x1399c,
  16763. 0x139b8, 0x139c8, 0x139d0, 0x139de, 0x139e6, 0x139ec, 0x139fa, 0x13a06, 0x13a0c, 0x13a18, 0x13a30, 0x13a3e,
  16764. 0x13a60, 0x13a7c, 0x13ac0, 0x13af8, 0x13b0e, 0x13b1c, 0x13b38, 0x13b70, 0x13b7e, 0x13b88, 0x13b90, 0x13b9e,
  16765. 0x13ba0, 0x13bbc, 0x13bcc, 0x13bd8, 0x13bee, 0x13bf2, 0x13bf4, 0x13c12, 0x13c14, 0x13c22, 0x13c24, 0x13c28,
  16766. 0x13c36, 0x13c42, 0x13c48, 0x13c50, 0x13c5e, 0x13c66, 0x13c6c, 0x13c82, 0x13c84, 0x13c90, 0x13c9e, 0x13ca0,
  16767. 0x13cbc, 0x13cc6, 0x13ccc, 0x13cd8, 0x13cee, 0x13d02, 0x13d04, 0x13d08, 0x13d10, 0x13d1e, 0x13d20, 0x13d3c,
  16768. 0x13d40, 0x13d78, 0x13d86, 0x13d8c, 0x13d98, 0x13db0, 0x13dbe, 0x13dce, 0x13ddc, 0x13de4, 0x13de8, 0x13df6,
  16769. 0x13e1a, 0x13e2e, 0x13e32, 0x13e34, 0x13e4e, 0x13e5c, 0x13e62, 0x13e64, 0x13e68, 0x13e76, 0x13e8e, 0x13e9c,
  16770. 0x13eb8, 0x13ec2, 0x13ec4, 0x13ec8, 0x13ed0, 0x13ede, 0x13ee6, 0x13eec, 0x13f26, 0x13f2c, 0x13f3a, 0x13f46,
  16771. 0x13f4c, 0x13f58, 0x13f6e, 0x13f72, 0x13f74, 0x14082, 0x1409e, 0x140a0, 0x140bc, 0x14104, 0x14108, 0x14110,
  16772. 0x1411e, 0x14120, 0x1413c, 0x14140, 0x14178, 0x1418c, 0x14198, 0x141b0, 0x141be, 0x141e2, 0x141e4, 0x141e8,
  16773. 0x14208, 0x14210, 0x1421e, 0x14220, 0x1423c, 0x14240, 0x14278, 0x142f0, 0x14306, 0x1430c, 0x14318, 0x14330,
  16774. 0x1433e, 0x14360, 0x1437c, 0x1438e, 0x143c2, 0x143c4, 0x143c8, 0x143d0, 0x143e6, 0x143ec, 0x14408, 0x14410,
  16775. 0x1441e, 0x14420, 0x1443c, 0x14440, 0x14478, 0x144f0, 0x145e0, 0x1460c, 0x14618, 0x14630, 0x1463e, 0x14660,
  16776. 0x1467c, 0x146c0, 0x146f8, 0x1471c, 0x14738, 0x14770, 0x1477e, 0x14782, 0x14784, 0x14788, 0x14790, 0x147a0,
  16777. 0x147bc, 0x147c6, 0x147cc, 0x147d8, 0x147ee, 0x14810, 0x14820, 0x1483c, 0x14840, 0x14878, 0x148f0, 0x149e0,
  16778. 0x14bc0, 0x14c30, 0x14c3e, 0x14c60, 0x14c7c, 0x14cc0, 0x14cf8, 0x14df0, 0x14e38, 0x14e70, 0x14e7e, 0x14ee0,
  16779. 0x14efc, 0x14f04, 0x14f08, 0x14f10, 0x14f1e, 0x14f20, 0x14f3c, 0x14f40, 0x14f78, 0x14f86, 0x14f8c, 0x14f98,
  16780. 0x14fb0, 0x14fce, 0x14fdc, 0x15020, 0x15040, 0x15078, 0x150f0, 0x151e0, 0x153c0, 0x15860, 0x1587c, 0x158c0,
  16781. 0x158f8, 0x159f0, 0x15be0, 0x15c70, 0x15c7e, 0x15ce0, 0x15cfc, 0x15dc0, 0x15df8, 0x15e08, 0x15e10, 0x15e20,
  16782. 0x15e40, 0x15e78, 0x15ef0, 0x15f0c, 0x15f18, 0x15f30, 0x15f60, 0x15f7c, 0x15f8e, 0x15f9c, 0x15fb8, 0x1604e,
  16783. 0x1605c, 0x1608e, 0x1609c, 0x160b8, 0x160c2, 0x160c4, 0x160c8, 0x160de, 0x1610e, 0x1611c, 0x16138, 0x16170,
  16784. 0x1617e, 0x16184, 0x16188, 0x16190, 0x1619e, 0x161a0, 0x161bc, 0x161c6, 0x161cc, 0x161d8, 0x161f2, 0x161f4,
  16785. 0x1620e, 0x1621c, 0x16238, 0x16270, 0x1627e, 0x162e0, 0x162fc, 0x16304, 0x16308, 0x16310, 0x1631e, 0x16320,
  16786. 0x1633c, 0x16340, 0x16378, 0x16386, 0x1638c, 0x16398, 0x163b0, 0x163be, 0x163ce, 0x163dc, 0x163e2, 0x163e4,
  16787. 0x163e8, 0x163f6, 0x1640e, 0x1641c, 0x16438, 0x16470, 0x1647e, 0x164e0, 0x164fc, 0x165c0, 0x165f8, 0x16610,
  16788. 0x1661e, 0x16620, 0x1663c, 0x16640, 0x16678, 0x166f0, 0x16718, 0x16730, 0x1673e, 0x16760, 0x1677c, 0x1678e,
  16789. 0x1679c, 0x167b8, 0x167c2, 0x167c4, 0x167c8, 0x167d0, 0x167de, 0x167e6, 0x167ec, 0x1681c, 0x16838, 0x16870,
  16790. 0x168e0, 0x168fc, 0x169c0, 0x169f8, 0x16bf0, 0x16c10, 0x16c1e, 0x16c20, 0x16c3c, 0x16c40, 0x16c78, 0x16cf0,
  16791. 0x16de0, 0x16e18, 0x16e30, 0x16e3e, 0x16e60, 0x16e7c, 0x16ec0, 0x16ef8, 0x16f1c, 0x16f38, 0x16f70, 0x16f7e,
  16792. 0x16f84, 0x16f88, 0x16f90, 0x16f9e, 0x16fa0, 0x16fbc, 0x16fc6, 0x16fcc, 0x16fd8, 0x17026, 0x1702c, 0x17046,
  16793. 0x1704c, 0x17058, 0x1706e, 0x17086, 0x1708c, 0x17098, 0x170b0, 0x170be, 0x170ce, 0x170dc, 0x170e8, 0x17106,
  16794. 0x1710c, 0x17118, 0x17130, 0x1713e, 0x17160, 0x1717c, 0x1718e, 0x1719c, 0x171b8, 0x171c2, 0x171c4, 0x171c8,
  16795. 0x171d0, 0x171de, 0x171e6, 0x171ec, 0x171fa, 0x17206, 0x1720c, 0x17218, 0x17230, 0x1723e, 0x17260, 0x1727c,
  16796. 0x172c0, 0x172f8, 0x1730e, 0x1731c, 0x17338, 0x17370, 0x1737e, 0x17388, 0x17390, 0x1739e, 0x173a0, 0x173bc,
  16797. 0x173cc, 0x173d8, 0x173ee, 0x173f2, 0x173f4, 0x1740c, 0x17418, 0x17430, 0x1743e, 0x17460, 0x1747c, 0x174c0,
  16798. 0x174f8, 0x175f0, 0x1760e, 0x1761c, 0x17638, 0x17670, 0x1767e, 0x176e0, 0x176fc, 0x17708, 0x17710, 0x1771e,
  16799. 0x17720, 0x1773c, 0x17740, 0x17778, 0x17798, 0x177b0, 0x177be, 0x177dc, 0x177e2, 0x177e4, 0x177e8, 0x17822,
  16800. 0x17824, 0x17828, 0x17836, 0x17842, 0x17844, 0x17848, 0x17850, 0x1785e, 0x17866, 0x1786c, 0x17882, 0x17884,
  16801. 0x17888, 0x17890, 0x1789e, 0x178a0, 0x178bc, 0x178c6, 0x178cc, 0x178d8, 0x178ee, 0x178f2, 0x178f4, 0x17902,
  16802. 0x17904, 0x17908, 0x17910, 0x1791e, 0x17920, 0x1793c, 0x17940, 0x17978, 0x17986, 0x1798c, 0x17998, 0x179b0,
  16803. 0x179be, 0x179ce, 0x179dc, 0x179e2, 0x179e4, 0x179e8, 0x179f6, 0x17a04, 0x17a08, 0x17a10, 0x17a1e, 0x17a20,
  16804. 0x17a3c, 0x17a40, 0x17a78, 0x17af0, 0x17b06, 0x17b0c, 0x17b18, 0x17b30, 0x17b3e, 0x17b60, 0x17b7c, 0x17b8e,
  16805. 0x17b9c, 0x17bb8, 0x17bc4, 0x17bc8, 0x17bd0, 0x17bde, 0x17be6, 0x17bec, 0x17c2e, 0x17c32, 0x17c34, 0x17c4e,
  16806. 0x17c5c, 0x17c62, 0x17c64, 0x17c68, 0x17c76, 0x17c8e, 0x17c9c, 0x17cb8, 0x17cc2, 0x17cc4, 0x17cc8, 0x17cd0,
  16807. 0x17cde, 0x17ce6, 0x17cec, 0x17d0e, 0x17d1c, 0x17d38, 0x17d70, 0x17d82, 0x17d84, 0x17d88, 0x17d90, 0x17d9e,
  16808. 0x17da0, 0x17dbc, 0x17dc6, 0x17dcc, 0x17dd8, 0x17dee, 0x17e26, 0x17e2c, 0x17e3a, 0x17e46, 0x17e4c, 0x17e58,
  16809. 0x17e6e, 0x17e72, 0x17e74, 0x17e86, 0x17e8c, 0x17e98, 0x17eb0, 0x17ece, 0x17edc, 0x17ee2, 0x17ee4, 0x17ee8,
  16810. 0x17ef6, 0x1813a, 0x18172, 0x18174, 0x18216, 0x18226, 0x1823a, 0x1824c, 0x18258, 0x1826e, 0x18272, 0x18274,
  16811. 0x18298, 0x182be, 0x182e2, 0x182e4, 0x182e8, 0x182f6, 0x1835e, 0x1837a, 0x183ae, 0x183d6, 0x18416, 0x18426,
  16812. 0x1842c, 0x1843a, 0x18446, 0x18458, 0x1846e, 0x18472, 0x18474, 0x18486, 0x184b0, 0x184be, 0x184ce, 0x184dc,
  16813. 0x184e2, 0x184e4, 0x184e8, 0x184f6, 0x18506, 0x1850c, 0x18518, 0x18530, 0x1853e, 0x18560, 0x1857c, 0x1858e,
  16814. 0x1859c, 0x185b8, 0x185c2, 0x185c4, 0x185c8, 0x185d0, 0x185de, 0x185e6, 0x185ec, 0x185fa, 0x18612, 0x18614,
  16815. 0x18622, 0x18628, 0x18636, 0x18642, 0x18650, 0x1865e, 0x1867a, 0x18682, 0x18684, 0x18688, 0x18690, 0x1869e,
  16816. 0x186a0, 0x186bc, 0x186c6, 0x186cc, 0x186d8, 0x186ee, 0x186f2, 0x186f4, 0x1872e, 0x1874e, 0x1875c, 0x18796,
  16817. 0x187a6, 0x187ac, 0x187d2, 0x187d4, 0x18826, 0x1882c, 0x1883a, 0x18846, 0x1884c, 0x18858, 0x1886e, 0x18872,
  16818. 0x18874, 0x18886, 0x18898, 0x188b0, 0x188be, 0x188ce, 0x188dc, 0x188e2, 0x188e4, 0x188e8, 0x188f6, 0x1890c,
  16819. 0x18930, 0x1893e, 0x18960, 0x1897c, 0x1898e, 0x189b8, 0x189c2, 0x189c8, 0x189d0, 0x189de, 0x189e6, 0x189ec,
  16820. 0x189fa, 0x18a18, 0x18a30, 0x18a3e, 0x18a60, 0x18a7c, 0x18ac0, 0x18af8, 0x18b1c, 0x18b38, 0x18b70, 0x18b7e,
  16821. 0x18b82, 0x18b84, 0x18b88, 0x18b90, 0x18b9e, 0x18ba0, 0x18bbc, 0x18bc6, 0x18bcc, 0x18bd8, 0x18bee, 0x18bf2,
  16822. 0x18bf4, 0x18c22, 0x18c24, 0x18c28, 0x18c36, 0x18c42, 0x18c48, 0x18c50, 0x18c5e, 0x18c66, 0x18c7a, 0x18c82,
  16823. 0x18c84, 0x18c90, 0x18c9e, 0x18ca0, 0x18cbc, 0x18ccc, 0x18cf2, 0x18cf4, 0x18d04, 0x18d08, 0x18d10, 0x18d1e,
  16824. 0x18d20, 0x18d3c, 0x18d40, 0x18d78, 0x18d86, 0x18d98, 0x18dce, 0x18de2, 0x18de4, 0x18de8, 0x18e2e, 0x18e32,
  16825. 0x18e34, 0x18e4e, 0x18e5c, 0x18e62, 0x18e64, 0x18e68, 0x18e8e, 0x18e9c, 0x18eb8, 0x18ec2, 0x18ec4, 0x18ec8,
  16826. 0x18ed0, 0x18efa, 0x18f16, 0x18f26, 0x18f2c, 0x18f46, 0x18f4c, 0x18f58, 0x18f6e, 0x18f8a, 0x18f92, 0x18f94,
  16827. 0x18fa2, 0x18fa4, 0x18fa8, 0x18fb6, 0x1902c, 0x1903a, 0x19046, 0x1904c, 0x19058, 0x19072, 0x19074, 0x19086,
  16828. 0x19098, 0x190b0, 0x190be, 0x190ce, 0x190dc, 0x190e2, 0x190e8, 0x190f6, 0x19106, 0x1910c, 0x19130, 0x1913e,
  16829. 0x19160, 0x1917c, 0x1918e, 0x1919c, 0x191b8, 0x191c2, 0x191c8, 0x191d0, 0x191de, 0x191e6, 0x191ec, 0x191fa,
  16830. 0x19218, 0x1923e, 0x19260, 0x1927c, 0x192c0, 0x192f8, 0x19338, 0x19370, 0x1937e, 0x19382, 0x19384, 0x19390,
  16831. 0x1939e, 0x193a0, 0x193bc, 0x193c6, 0x193cc, 0x193d8, 0x193ee, 0x193f2, 0x193f4, 0x19430, 0x1943e, 0x19460,
  16832. 0x1947c, 0x194c0, 0x194f8, 0x195f0, 0x19638, 0x19670, 0x1967e, 0x196e0, 0x196fc, 0x19702, 0x19704, 0x19708,
  16833. 0x19710, 0x19720, 0x1973c, 0x19740, 0x19778, 0x19786, 0x1978c, 0x19798, 0x197b0, 0x197be, 0x197ce, 0x197dc,
  16834. 0x197e2, 0x197e4, 0x197e8, 0x19822, 0x19824, 0x19842, 0x19848, 0x19850, 0x1985e, 0x19866, 0x1987a, 0x19882,
  16835. 0x19884, 0x19890, 0x1989e, 0x198a0, 0x198bc, 0x198cc, 0x198f2, 0x198f4, 0x19902, 0x19908, 0x1991e, 0x19920,
  16836. 0x1993c, 0x19940, 0x19978, 0x19986, 0x19998, 0x199ce, 0x199e2, 0x199e4, 0x199e8, 0x19a08, 0x19a10, 0x19a1e,
  16837. 0x19a20, 0x19a3c, 0x19a40, 0x19a78, 0x19af0, 0x19b18, 0x19b3e, 0x19b60, 0x19b9c, 0x19bc2, 0x19bc4, 0x19bc8,
  16838. 0x19bd0, 0x19be6, 0x19c2e, 0x19c34, 0x19c4e, 0x19c5c, 0x19c62, 0x19c64, 0x19c68, 0x19c8e, 0x19c9c, 0x19cb8,
  16839. 0x19cc2, 0x19cc8, 0x19cd0, 0x19ce6, 0x19cfa, 0x19d0e, 0x19d1c, 0x19d38, 0x19d70, 0x19d7e, 0x19d82, 0x19d84,
  16840. 0x19d88, 0x19d90, 0x19da0, 0x19dcc, 0x19df2, 0x19df4, 0x19e16, 0x19e26, 0x19e2c, 0x19e46, 0x19e4c, 0x19e58,
  16841. 0x19e74, 0x19e86, 0x19e8c, 0x19e98, 0x19eb0, 0x19ebe, 0x19ece, 0x19ee2, 0x19ee4, 0x19ee8, 0x19f0a, 0x19f12,
  16842. 0x19f14, 0x19f22, 0x19f24, 0x19f28, 0x19f42, 0x19f44, 0x19f48, 0x19f50, 0x19f5e, 0x19f6c, 0x19f9a, 0x19fae,
  16843. 0x19fb2, 0x19fb4, 0x1a046, 0x1a04c, 0x1a072, 0x1a074, 0x1a086, 0x1a08c, 0x1a098, 0x1a0b0, 0x1a0be, 0x1a0e2,
  16844. 0x1a0e4, 0x1a0e8, 0x1a0f6, 0x1a106, 0x1a10c, 0x1a118, 0x1a130, 0x1a13e, 0x1a160, 0x1a17c, 0x1a18e, 0x1a19c,
  16845. 0x1a1b8, 0x1a1c2, 0x1a1c4, 0x1a1c8, 0x1a1d0, 0x1a1de, 0x1a1e6, 0x1a1ec, 0x1a218, 0x1a230, 0x1a23e, 0x1a260,
  16846. 0x1a27c, 0x1a2c0, 0x1a2f8, 0x1a31c, 0x1a338, 0x1a370, 0x1a37e, 0x1a382, 0x1a384, 0x1a388, 0x1a390, 0x1a39e,
  16847. 0x1a3a0, 0x1a3bc, 0x1a3c6, 0x1a3cc, 0x1a3d8, 0x1a3ee, 0x1a3f2, 0x1a3f4, 0x1a418, 0x1a430, 0x1a43e, 0x1a460,
  16848. 0x1a47c, 0x1a4c0, 0x1a4f8, 0x1a5f0, 0x1a61c, 0x1a638, 0x1a670, 0x1a67e, 0x1a6e0, 0x1a6fc, 0x1a702, 0x1a704,
  16849. 0x1a708, 0x1a710, 0x1a71e, 0x1a720, 0x1a73c, 0x1a740, 0x1a778, 0x1a786, 0x1a78c, 0x1a798, 0x1a7b0, 0x1a7be,
  16850. 0x1a7ce, 0x1a7dc, 0x1a7e2, 0x1a7e4, 0x1a7e8, 0x1a830, 0x1a860, 0x1a87c, 0x1a8c0, 0x1a8f8, 0x1a9f0, 0x1abe0,
  16851. 0x1ac70, 0x1ac7e, 0x1ace0, 0x1acfc, 0x1adc0, 0x1adf8, 0x1ae04, 0x1ae08, 0x1ae10, 0x1ae20, 0x1ae3c, 0x1ae40,
  16852. 0x1ae78, 0x1aef0, 0x1af06, 0x1af0c, 0x1af18, 0x1af30, 0x1af3e, 0x1af60, 0x1af7c, 0x1af8e, 0x1af9c, 0x1afb8,
  16853. 0x1afc4, 0x1afc8, 0x1afd0, 0x1afde, 0x1b042, 0x1b05e, 0x1b07a, 0x1b082, 0x1b084, 0x1b088, 0x1b090, 0x1b09e,
  16854. 0x1b0a0, 0x1b0bc, 0x1b0cc, 0x1b0f2, 0x1b0f4, 0x1b102, 0x1b104, 0x1b108, 0x1b110, 0x1b11e, 0x1b120, 0x1b13c,
  16855. 0x1b140, 0x1b178, 0x1b186, 0x1b198, 0x1b1ce, 0x1b1e2, 0x1b1e4, 0x1b1e8, 0x1b204, 0x1b208, 0x1b210, 0x1b21e,
  16856. 0x1b220, 0x1b23c, 0x1b240, 0x1b278, 0x1b2f0, 0x1b30c, 0x1b33e, 0x1b360, 0x1b39c, 0x1b3c2, 0x1b3c4, 0x1b3c8,
  16857. 0x1b3d0, 0x1b3e6, 0x1b410, 0x1b41e, 0x1b420, 0x1b43c, 0x1b440, 0x1b478, 0x1b4f0, 0x1b5e0, 0x1b618, 0x1b660,
  16858. 0x1b67c, 0x1b6c0, 0x1b738, 0x1b782, 0x1b784, 0x1b788, 0x1b790, 0x1b79e, 0x1b7a0, 0x1b7cc, 0x1b82e, 0x1b84e,
  16859. 0x1b85c, 0x1b88e, 0x1b89c, 0x1b8b8, 0x1b8c2, 0x1b8c4, 0x1b8c8, 0x1b8d0, 0x1b8e6, 0x1b8fa, 0x1b90e, 0x1b91c,
  16860. 0x1b938, 0x1b970, 0x1b97e, 0x1b982, 0x1b984, 0x1b988, 0x1b990, 0x1b99e, 0x1b9a0, 0x1b9cc, 0x1b9f2, 0x1b9f4,
  16861. 0x1ba0e, 0x1ba1c, 0x1ba38, 0x1ba70, 0x1ba7e, 0x1bae0, 0x1bafc, 0x1bb08, 0x1bb10, 0x1bb20, 0x1bb3c, 0x1bb40,
  16862. 0x1bb98, 0x1bbce, 0x1bbe2, 0x1bbe4, 0x1bbe8, 0x1bc16, 0x1bc26, 0x1bc2c, 0x1bc46, 0x1bc4c, 0x1bc58, 0x1bc72,
  16863. 0x1bc74, 0x1bc86, 0x1bc8c, 0x1bc98, 0x1bcb0, 0x1bcbe, 0x1bcce, 0x1bce2, 0x1bce4, 0x1bce8, 0x1bd06, 0x1bd0c,
  16864. 0x1bd18, 0x1bd30, 0x1bd3e, 0x1bd60, 0x1bd7c, 0x1bd9c, 0x1bdc2, 0x1bdc4, 0x1bdc8, 0x1bdd0, 0x1bde6, 0x1bdfa,
  16865. 0x1be12, 0x1be14, 0x1be22, 0x1be24, 0x1be28, 0x1be42, 0x1be44, 0x1be48, 0x1be50, 0x1be5e, 0x1be66, 0x1be82,
  16866. 0x1be84, 0x1be88, 0x1be90, 0x1be9e, 0x1bea0, 0x1bebc, 0x1becc, 0x1bef4, 0x1bf1a, 0x1bf2e, 0x1bf32, 0x1bf34,
  16867. 0x1bf4e, 0x1bf5c, 0x1bf62, 0x1bf64, 0x1bf68, 0x1c09a, 0x1c0b2, 0x1c0b4, 0x1c11a, 0x1c132, 0x1c134, 0x1c162,
  16868. 0x1c164, 0x1c168, 0x1c176, 0x1c1ba, 0x1c21a, 0x1c232, 0x1c234, 0x1c24e, 0x1c25c, 0x1c262, 0x1c264, 0x1c268,
  16869. 0x1c276, 0x1c28e, 0x1c2c2, 0x1c2c4, 0x1c2c8, 0x1c2d0, 0x1c2de, 0x1c2e6, 0x1c2ec, 0x1c2fa, 0x1c316, 0x1c326,
  16870. 0x1c33a, 0x1c346, 0x1c34c, 0x1c372, 0x1c374, 0x1c41a, 0x1c42e, 0x1c432, 0x1c434, 0x1c44e, 0x1c45c, 0x1c462,
  16871. 0x1c464, 0x1c468, 0x1c476, 0x1c48e, 0x1c49c, 0x1c4b8, 0x1c4c2, 0x1c4c8, 0x1c4d0, 0x1c4de, 0x1c4e6, 0x1c4ec,
  16872. 0x1c4fa, 0x1c51c, 0x1c538, 0x1c570, 0x1c57e, 0x1c582, 0x1c584, 0x1c588, 0x1c590, 0x1c59e, 0x1c5a0, 0x1c5bc,
  16873. 0x1c5c6, 0x1c5cc, 0x1c5d8, 0x1c5ee, 0x1c5f2, 0x1c5f4, 0x1c616, 0x1c626, 0x1c62c, 0x1c63a, 0x1c646, 0x1c64c,
  16874. 0x1c658, 0x1c66e, 0x1c672, 0x1c674, 0x1c686, 0x1c68c, 0x1c698, 0x1c6b0, 0x1c6be, 0x1c6ce, 0x1c6dc, 0x1c6e2,
  16875. 0x1c6e4, 0x1c6e8, 0x1c712, 0x1c714, 0x1c722, 0x1c728, 0x1c736, 0x1c742, 0x1c744, 0x1c748, 0x1c750, 0x1c75e,
  16876. 0x1c766, 0x1c76c, 0x1c77a, 0x1c7ae, 0x1c7d6, 0x1c7ea, 0x1c81a, 0x1c82e, 0x1c832, 0x1c834, 0x1c84e, 0x1c85c,
  16877. 0x1c862, 0x1c864, 0x1c868, 0x1c876, 0x1c88e, 0x1c89c, 0x1c8b8, 0x1c8c2, 0x1c8c8, 0x1c8d0, 0x1c8de, 0x1c8e6,
  16878. 0x1c8ec, 0x1c8fa, 0x1c90e, 0x1c938, 0x1c970, 0x1c97e, 0x1c982, 0x1c984, 0x1c990, 0x1c99e, 0x1c9a0, 0x1c9bc,
  16879. 0x1c9c6, 0x1c9cc, 0x1c9d8, 0x1c9ee, 0x1c9f2, 0x1c9f4, 0x1ca38, 0x1ca70, 0x1ca7e, 0x1cae0, 0x1cafc, 0x1cb02,
  16880. 0x1cb04, 0x1cb08, 0x1cb10, 0x1cb20, 0x1cb3c, 0x1cb40, 0x1cb78, 0x1cb86, 0x1cb8c, 0x1cb98, 0x1cbb0, 0x1cbbe,
  16881. 0x1cbce, 0x1cbdc, 0x1cbe2, 0x1cbe4, 0x1cbe8, 0x1cbf6, 0x1cc16, 0x1cc26, 0x1cc2c, 0x1cc3a, 0x1cc46, 0x1cc58,
  16882. 0x1cc72, 0x1cc74, 0x1cc86, 0x1ccb0, 0x1ccbe, 0x1ccce, 0x1cce2, 0x1cce4, 0x1cce8, 0x1cd06, 0x1cd0c, 0x1cd18,
  16883. 0x1cd30, 0x1cd3e, 0x1cd60, 0x1cd7c, 0x1cd9c, 0x1cdc2, 0x1cdc4, 0x1cdc8, 0x1cdd0, 0x1cdde, 0x1cde6, 0x1cdfa,
  16884. 0x1ce22, 0x1ce28, 0x1ce42, 0x1ce50, 0x1ce5e, 0x1ce66, 0x1ce7a, 0x1ce82, 0x1ce84, 0x1ce88, 0x1ce90, 0x1ce9e,
  16885. 0x1cea0, 0x1cebc, 0x1cecc, 0x1cef2, 0x1cef4, 0x1cf2e, 0x1cf32, 0x1cf34, 0x1cf4e, 0x1cf5c, 0x1cf62, 0x1cf64,
  16886. 0x1cf68, 0x1cf96, 0x1cfa6, 0x1cfac, 0x1cfca, 0x1cfd2, 0x1cfd4, 0x1d02e, 0x1d032, 0x1d034, 0x1d04e, 0x1d05c,
  16887. 0x1d062, 0x1d064, 0x1d068, 0x1d076, 0x1d08e, 0x1d09c, 0x1d0b8, 0x1d0c2, 0x1d0c4, 0x1d0c8, 0x1d0d0, 0x1d0de,
  16888. 0x1d0e6, 0x1d0ec, 0x1d0fa, 0x1d11c, 0x1d138, 0x1d170, 0x1d17e, 0x1d182, 0x1d184, 0x1d188, 0x1d190, 0x1d19e,
  16889. 0x1d1a0, 0x1d1bc, 0x1d1c6, 0x1d1cc, 0x1d1d8, 0x1d1ee, 0x1d1f2, 0x1d1f4, 0x1d21c, 0x1d238, 0x1d270, 0x1d27e,
  16890. 0x1d2e0, 0x1d2fc, 0x1d302, 0x1d304, 0x1d308, 0x1d310, 0x1d31e, 0x1d320, 0x1d33c, 0x1d340, 0x1d378, 0x1d386,
  16891. 0x1d38c, 0x1d398, 0x1d3b0, 0x1d3be, 0x1d3ce, 0x1d3dc, 0x1d3e2, 0x1d3e4, 0x1d3e8, 0x1d3f6, 0x1d470, 0x1d47e,
  16892. 0x1d4e0, 0x1d4fc, 0x1d5c0, 0x1d5f8, 0x1d604, 0x1d608, 0x1d610, 0x1d620, 0x1d640, 0x1d678, 0x1d6f0, 0x1d706,
  16893. 0x1d70c, 0x1d718, 0x1d730, 0x1d73e, 0x1d760, 0x1d77c, 0x1d78e, 0x1d79c, 0x1d7b8, 0x1d7c2, 0x1d7c4, 0x1d7c8,
  16894. 0x1d7d0, 0x1d7de, 0x1d7e6, 0x1d7ec, 0x1d826, 0x1d82c, 0x1d83a, 0x1d846, 0x1d84c, 0x1d858, 0x1d872, 0x1d874,
  16895. 0x1d886, 0x1d88c, 0x1d898, 0x1d8b0, 0x1d8be, 0x1d8ce, 0x1d8e2, 0x1d8e4, 0x1d8e8, 0x1d8f6, 0x1d90c, 0x1d918,
  16896. 0x1d930, 0x1d93e, 0x1d960, 0x1d97c, 0x1d99c, 0x1d9c2, 0x1d9c4, 0x1d9c8, 0x1d9d0, 0x1d9e6, 0x1d9fa, 0x1da0c,
  16897. 0x1da18, 0x1da30, 0x1da3e, 0x1da60, 0x1da7c, 0x1dac0, 0x1daf8, 0x1db38, 0x1db82, 0x1db84, 0x1db88, 0x1db90,
  16898. 0x1db9e, 0x1dba0, 0x1dbcc, 0x1dbf2, 0x1dbf4, 0x1dc22, 0x1dc42, 0x1dc44, 0x1dc48, 0x1dc50, 0x1dc5e, 0x1dc66,
  16899. 0x1dc7a, 0x1dc82, 0x1dc84, 0x1dc88, 0x1dc90, 0x1dc9e, 0x1dca0, 0x1dcbc, 0x1dccc, 0x1dcf2, 0x1dcf4, 0x1dd04,
  16900. 0x1dd08, 0x1dd10, 0x1dd1e, 0x1dd20, 0x1dd3c, 0x1dd40, 0x1dd78, 0x1dd86, 0x1dd98, 0x1ddce, 0x1dde2, 0x1dde4,
  16901. 0x1dde8, 0x1de2e, 0x1de32, 0x1de34, 0x1de4e, 0x1de5c, 0x1de62, 0x1de64, 0x1de68, 0x1de8e, 0x1de9c, 0x1deb8,
  16902. 0x1dec2, 0x1dec4, 0x1dec8, 0x1ded0, 0x1dee6, 0x1defa, 0x1df16, 0x1df26, 0x1df2c, 0x1df46, 0x1df4c, 0x1df58,
  16903. 0x1df72, 0x1df74, 0x1df8a, 0x1df92, 0x1df94, 0x1dfa2, 0x1dfa4, 0x1dfa8, 0x1e08a, 0x1e092, 0x1e094, 0x1e0a2,
  16904. 0x1e0a4, 0x1e0a8, 0x1e0b6, 0x1e0da, 0x1e10a, 0x1e112, 0x1e114, 0x1e122, 0x1e124, 0x1e128, 0x1e136, 0x1e142,
  16905. 0x1e144, 0x1e148, 0x1e150, 0x1e166, 0x1e16c, 0x1e17a, 0x1e19a, 0x1e1b2, 0x1e1b4, 0x1e20a, 0x1e212, 0x1e214,
  16906. 0x1e222, 0x1e224, 0x1e228, 0x1e236, 0x1e242, 0x1e248, 0x1e250, 0x1e25e, 0x1e266, 0x1e26c, 0x1e27a, 0x1e282,
  16907. 0x1e284, 0x1e288, 0x1e290, 0x1e2a0, 0x1e2bc, 0x1e2c6, 0x1e2cc, 0x1e2d8, 0x1e2ee, 0x1e2f2, 0x1e2f4, 0x1e31a,
  16908. 0x1e332, 0x1e334, 0x1e35c, 0x1e362, 0x1e364, 0x1e368, 0x1e3ba, 0x1e40a, 0x1e412, 0x1e414, 0x1e422, 0x1e428,
  16909. 0x1e436, 0x1e442, 0x1e448, 0x1e450, 0x1e45e, 0x1e466, 0x1e46c, 0x1e47a, 0x1e482, 0x1e484, 0x1e490, 0x1e49e,
  16910. 0x1e4a0, 0x1e4bc, 0x1e4c6, 0x1e4cc, 0x1e4d8, 0x1e4ee, 0x1e4f2, 0x1e4f4, 0x1e502, 0x1e504, 0x1e508, 0x1e510,
  16911. 0x1e51e, 0x1e520, 0x1e53c, 0x1e540, 0x1e578, 0x1e586, 0x1e58c, 0x1e598, 0x1e5b0, 0x1e5be, 0x1e5ce, 0x1e5dc,
  16912. 0x1e5e2, 0x1e5e4, 0x1e5e8, 0x1e5f6, 0x1e61a, 0x1e62e, 0x1e632, 0x1e634, 0x1e64e, 0x1e65c, 0x1e662, 0x1e668,
  16913. 0x1e68e, 0x1e69c, 0x1e6b8, 0x1e6c2, 0x1e6c4, 0x1e6c8, 0x1e6d0, 0x1e6e6, 0x1e6fa, 0x1e716, 0x1e726, 0x1e72c,
  16914. 0x1e73a, 0x1e746, 0x1e74c, 0x1e758, 0x1e772, 0x1e774, 0x1e792, 0x1e794, 0x1e7a2, 0x1e7a4, 0x1e7a8, 0x1e7b6,
  16915. 0x1e812, 0x1e814, 0x1e822, 0x1e824, 0x1e828, 0x1e836, 0x1e842, 0x1e844, 0x1e848, 0x1e850, 0x1e85e, 0x1e866,
  16916. 0x1e86c, 0x1e87a, 0x1e882, 0x1e884, 0x1e888, 0x1e890, 0x1e89e, 0x1e8a0, 0x1e8bc, 0x1e8c6, 0x1e8cc, 0x1e8d8,
  16917. 0x1e8ee, 0x1e8f2, 0x1e8f4, 0x1e902, 0x1e904, 0x1e908, 0x1e910, 0x1e920, 0x1e93c, 0x1e940, 0x1e978, 0x1e986,
  16918. 0x1e98c, 0x1e998, 0x1e9b0, 0x1e9be, 0x1e9ce, 0x1e9dc, 0x1e9e2, 0x1e9e4, 0x1e9e8, 0x1e9f6, 0x1ea04, 0x1ea08,
  16919. 0x1ea10, 0x1ea20, 0x1ea40, 0x1ea78, 0x1eaf0, 0x1eb06, 0x1eb0c, 0x1eb18, 0x1eb30, 0x1eb3e, 0x1eb60, 0x1eb7c,
  16920. 0x1eb8e, 0x1eb9c, 0x1ebb8, 0x1ebc2, 0x1ebc4, 0x1ebc8, 0x1ebd0, 0x1ebde, 0x1ebe6, 0x1ebec, 0x1ec1a, 0x1ec2e,
  16921. 0x1ec32, 0x1ec34, 0x1ec4e, 0x1ec5c, 0x1ec62, 0x1ec64, 0x1ec68, 0x1ec8e, 0x1ec9c, 0x1ecb8, 0x1ecc2, 0x1ecc4,
  16922. 0x1ecc8, 0x1ecd0, 0x1ece6, 0x1ecfa, 0x1ed0e, 0x1ed1c, 0x1ed38, 0x1ed70, 0x1ed7e, 0x1ed82, 0x1ed84, 0x1ed88,
  16923. 0x1ed90, 0x1ed9e, 0x1eda0, 0x1edcc, 0x1edf2, 0x1edf4, 0x1ee16, 0x1ee26, 0x1ee2c, 0x1ee3a, 0x1ee46, 0x1ee4c,
  16924. 0x1ee58, 0x1ee6e, 0x1ee72, 0x1ee74, 0x1ee86, 0x1ee8c, 0x1ee98, 0x1eeb0, 0x1eebe, 0x1eece, 0x1eedc, 0x1eee2,
  16925. 0x1eee4, 0x1eee8, 0x1ef12, 0x1ef22, 0x1ef24, 0x1ef28, 0x1ef36, 0x1ef42, 0x1ef44, 0x1ef48, 0x1ef50, 0x1ef5e,
  16926. 0x1ef66, 0x1ef6c, 0x1ef7a, 0x1efae, 0x1efb2, 0x1efb4, 0x1efd6, 0x1f096, 0x1f0a6, 0x1f0ac, 0x1f0ba, 0x1f0ca,
  16927. 0x1f0d2, 0x1f0d4, 0x1f116, 0x1f126, 0x1f12c, 0x1f13a, 0x1f146, 0x1f14c, 0x1f158, 0x1f16e, 0x1f172, 0x1f174,
  16928. 0x1f18a, 0x1f192, 0x1f194, 0x1f1a2, 0x1f1a4, 0x1f1a8, 0x1f1da, 0x1f216, 0x1f226, 0x1f22c, 0x1f23a, 0x1f246,
  16929. 0x1f258, 0x1f26e, 0x1f272, 0x1f274, 0x1f286, 0x1f28c, 0x1f298, 0x1f2b0, 0x1f2be, 0x1f2ce, 0x1f2dc, 0x1f2e2,
  16930. 0x1f2e4, 0x1f2e8, 0x1f2f6, 0x1f30a, 0x1f312, 0x1f314, 0x1f322, 0x1f328, 0x1f342, 0x1f344, 0x1f348, 0x1f350,
  16931. 0x1f35e, 0x1f366, 0x1f37a, 0x1f39a, 0x1f3ae, 0x1f3b2, 0x1f3b4, 0x1f416, 0x1f426, 0x1f42c, 0x1f43a, 0x1f446,
  16932. 0x1f44c, 0x1f458, 0x1f46e, 0x1f472, 0x1f474, 0x1f486, 0x1f48c, 0x1f498, 0x1f4b0, 0x1f4be, 0x1f4ce, 0x1f4dc,
  16933. 0x1f4e2, 0x1f4e4, 0x1f4e8, 0x1f4f6, 0x1f506, 0x1f50c, 0x1f518, 0x1f530, 0x1f53e, 0x1f560, 0x1f57c, 0x1f58e,
  16934. 0x1f59c, 0x1f5b8, 0x1f5c2, 0x1f5c4, 0x1f5c8, 0x1f5d0, 0x1f5de, 0x1f5e6, 0x1f5ec, 0x1f5fa, 0x1f60a, 0x1f612,
  16935. 0x1f614, 0x1f622, 0x1f624, 0x1f628, 0x1f636, 0x1f642, 0x1f644, 0x1f648, 0x1f650, 0x1f65e, 0x1f666, 0x1f67a,
  16936. 0x1f682, 0x1f684, 0x1f688, 0x1f690, 0x1f69e, 0x1f6a0, 0x1f6bc, 0x1f6cc, 0x1f6f2, 0x1f6f4, 0x1f71a, 0x1f72e,
  16937. 0x1f732, 0x1f734, 0x1f74e, 0x1f75c, 0x1f762, 0x1f764, 0x1f768, 0x1f776, 0x1f796, 0x1f7a6, 0x1f7ac, 0x1f7ba,
  16938. 0x1f7d2, 0x1f7d4, 0x1f89a, 0x1f8ae, 0x1f8b2, 0x1f8b4, 0x1f8d6, 0x1f8ea, 0x1f91a, 0x1f92e, 0x1f932, 0x1f934,
  16939. 0x1f94e, 0x1f95c, 0x1f962, 0x1f964, 0x1f968, 0x1f976, 0x1f996, 0x1f9a6, 0x1f9ac, 0x1f9ba, 0x1f9ca, 0x1f9d2,
  16940. 0x1f9d4, 0x1fa1a, 0x1fa2e, 0x1fa32, 0x1fa34, 0x1fa4e, 0x1fa5c, 0x1fa62, 0x1fa64, 0x1fa68, 0x1fa76, 0x1fa8e,
  16941. 0x1fa9c, 0x1fab8, 0x1fac2, 0x1fac4, 0x1fac8, 0x1fad0, 0x1fade, 0x1fae6, 0x1faec, 0x1fb16, 0x1fb26, 0x1fb2c,
  16942. 0x1fb3a, 0x1fb46, 0x1fb4c, 0x1fb58, 0x1fb6e, 0x1fb72, 0x1fb74, 0x1fb8a, 0x1fb92, 0x1fb94, 0x1fba2, 0x1fba4,
  16943. 0x1fba8, 0x1fbb6, 0x1fbda
  16944. ]);
  16945. /**
  16946. * This table contains to codewords for all symbols.
  16947. */
  16948. PDF417Common.CODEWORD_TABLE = Int32Array.from([
  16949. 2627, 1819, 2622, 2621, 1813, 1812, 2729, 2724, 2723, 2779, 2774, 2773, 902, 896, 908, 868, 865, 861, 859, 2511,
  16950. 873, 871, 1780, 835, 2493, 825, 2491, 842, 837, 844, 1764, 1762, 811, 810, 809, 2483, 807, 2482, 806, 2480, 815,
  16951. 814, 813, 812, 2484, 817, 816, 1745, 1744, 1742, 1746, 2655, 2637, 2635, 2626, 2625, 2623, 2628, 1820, 2752,
  16952. 2739, 2737, 2728, 2727, 2725, 2730, 2785, 2783, 2778, 2777, 2775, 2780, 787, 781, 747, 739, 736, 2413, 754, 752,
  16953. 1719, 692, 689, 681, 2371, 678, 2369, 700, 697, 694, 703, 1688, 1686, 642, 638, 2343, 631, 2341, 627, 2338, 651,
  16954. 646, 643, 2345, 654, 652, 1652, 1650, 1647, 1654, 601, 599, 2322, 596, 2321, 594, 2319, 2317, 611, 610, 608, 606,
  16955. 2324, 603, 2323, 615, 614, 612, 1617, 1616, 1614, 1612, 616, 1619, 1618, 2575, 2538, 2536, 905, 901, 898, 909,
  16956. 2509, 2507, 2504, 870, 867, 864, 860, 2512, 875, 872, 1781, 2490, 2489, 2487, 2485, 1748, 836, 834, 832, 830,
  16957. 2494, 827, 2492, 843, 841, 839, 845, 1765, 1763, 2701, 2676, 2674, 2653, 2648, 2656, 2634, 2633, 2631, 2629,
  16958. 1821, 2638, 2636, 2770, 2763, 2761, 2750, 2745, 2753, 2736, 2735, 2733, 2731, 1848, 2740, 2738, 2786, 2784, 591,
  16959. 588, 576, 569, 566, 2296, 1590, 537, 534, 526, 2276, 522, 2274, 545, 542, 539, 548, 1572, 1570, 481, 2245, 466,
  16960. 2242, 462, 2239, 492, 485, 482, 2249, 496, 494, 1534, 1531, 1528, 1538, 413, 2196, 406, 2191, 2188, 425, 419,
  16961. 2202, 415, 2199, 432, 430, 427, 1472, 1467, 1464, 433, 1476, 1474, 368, 367, 2160, 365, 2159, 362, 2157, 2155,
  16962. 2152, 378, 377, 375, 2166, 372, 2165, 369, 2162, 383, 381, 379, 2168, 1419, 1418, 1416, 1414, 385, 1411, 384,
  16963. 1423, 1422, 1420, 1424, 2461, 802, 2441, 2439, 790, 786, 783, 794, 2409, 2406, 2403, 750, 742, 738, 2414, 756,
  16964. 753, 1720, 2367, 2365, 2362, 2359, 1663, 693, 691, 684, 2373, 680, 2370, 702, 699, 696, 704, 1690, 1687, 2337,
  16965. 2336, 2334, 2332, 1624, 2329, 1622, 640, 637, 2344, 634, 2342, 630, 2340, 650, 648, 645, 2346, 655, 653, 1653,
  16966. 1651, 1649, 1655, 2612, 2597, 2595, 2571, 2568, 2565, 2576, 2534, 2529, 2526, 1787, 2540, 2537, 907, 904, 900,
  16967. 910, 2503, 2502, 2500, 2498, 1768, 2495, 1767, 2510, 2508, 2506, 869, 866, 863, 2513, 876, 874, 1782, 2720, 2713,
  16968. 2711, 2697, 2694, 2691, 2702, 2672, 2670, 2664, 1828, 2678, 2675, 2647, 2646, 2644, 2642, 1823, 2639, 1822, 2654,
  16969. 2652, 2650, 2657, 2771, 1855, 2765, 2762, 1850, 1849, 2751, 2749, 2747, 2754, 353, 2148, 344, 342, 336, 2142,
  16970. 332, 2140, 345, 1375, 1373, 306, 2130, 299, 2128, 295, 2125, 319, 314, 311, 2132, 1354, 1352, 1349, 1356, 262,
  16971. 257, 2101, 253, 2096, 2093, 274, 273, 267, 2107, 263, 2104, 280, 278, 275, 1316, 1311, 1308, 1320, 1318, 2052,
  16972. 202, 2050, 2044, 2040, 219, 2063, 212, 2060, 208, 2055, 224, 221, 2066, 1260, 1258, 1252, 231, 1248, 229, 1266,
  16973. 1264, 1261, 1268, 155, 1998, 153, 1996, 1994, 1991, 1988, 165, 164, 2007, 162, 2006, 159, 2003, 2000, 172, 171,
  16974. 169, 2012, 166, 2010, 1186, 1184, 1182, 1179, 175, 1176, 173, 1192, 1191, 1189, 1187, 176, 1194, 1193, 2313,
  16975. 2307, 2305, 592, 589, 2294, 2292, 2289, 578, 572, 568, 2297, 580, 1591, 2272, 2267, 2264, 1547, 538, 536, 529,
  16976. 2278, 525, 2275, 547, 544, 541, 1574, 1571, 2237, 2235, 2229, 1493, 2225, 1489, 478, 2247, 470, 2244, 465, 2241,
  16977. 493, 488, 484, 2250, 498, 495, 1536, 1533, 1530, 1539, 2187, 2186, 2184, 2182, 1432, 2179, 1430, 2176, 1427, 414,
  16978. 412, 2197, 409, 2195, 405, 2193, 2190, 426, 424, 421, 2203, 418, 2201, 431, 429, 1473, 1471, 1469, 1466, 434,
  16979. 1477, 1475, 2478, 2472, 2470, 2459, 2457, 2454, 2462, 803, 2437, 2432, 2429, 1726, 2443, 2440, 792, 789, 785,
  16980. 2401, 2399, 2393, 1702, 2389, 1699, 2411, 2408, 2405, 745, 741, 2415, 758, 755, 1721, 2358, 2357, 2355, 2353,
  16981. 1661, 2350, 1660, 2347, 1657, 2368, 2366, 2364, 2361, 1666, 690, 687, 2374, 683, 2372, 701, 698, 705, 1691, 1689,
  16982. 2619, 2617, 2610, 2608, 2605, 2613, 2593, 2588, 2585, 1803, 2599, 2596, 2563, 2561, 2555, 1797, 2551, 1795, 2573,
  16983. 2570, 2567, 2577, 2525, 2524, 2522, 2520, 1786, 2517, 1785, 2514, 1783, 2535, 2533, 2531, 2528, 1788, 2541, 2539,
  16984. 906, 903, 911, 2721, 1844, 2715, 2712, 1838, 1836, 2699, 2696, 2693, 2703, 1827, 1826, 1824, 2673, 2671, 2669,
  16985. 2666, 1829, 2679, 2677, 1858, 1857, 2772, 1854, 1853, 1851, 1856, 2766, 2764, 143, 1987, 139, 1986, 135, 133,
  16986. 131, 1984, 128, 1983, 125, 1981, 138, 137, 136, 1985, 1133, 1132, 1130, 112, 110, 1974, 107, 1973, 104, 1971,
  16987. 1969, 122, 121, 119, 117, 1977, 114, 1976, 124, 1115, 1114, 1112, 1110, 1117, 1116, 84, 83, 1953, 81, 1952, 78,
  16988. 1950, 1948, 1945, 94, 93, 91, 1959, 88, 1958, 85, 1955, 99, 97, 95, 1961, 1086, 1085, 1083, 1081, 1078, 100,
  16989. 1090, 1089, 1087, 1091, 49, 47, 1917, 44, 1915, 1913, 1910, 1907, 59, 1926, 56, 1925, 53, 1922, 1919, 66, 64,
  16990. 1931, 61, 1929, 1042, 1040, 1038, 71, 1035, 70, 1032, 68, 1048, 1047, 1045, 1043, 1050, 1049, 12, 10, 1869, 1867,
  16991. 1864, 1861, 21, 1880, 19, 1877, 1874, 1871, 28, 1888, 25, 1886, 22, 1883, 982, 980, 977, 974, 32, 30, 991, 989,
  16992. 987, 984, 34, 995, 994, 992, 2151, 2150, 2147, 2146, 2144, 356, 355, 354, 2149, 2139, 2138, 2136, 2134, 1359,
  16993. 343, 341, 338, 2143, 335, 2141, 348, 347, 346, 1376, 1374, 2124, 2123, 2121, 2119, 1326, 2116, 1324, 310, 308,
  16994. 305, 2131, 302, 2129, 298, 2127, 320, 318, 316, 313, 2133, 322, 321, 1355, 1353, 1351, 1357, 2092, 2091, 2089,
  16995. 2087, 1276, 2084, 1274, 2081, 1271, 259, 2102, 256, 2100, 252, 2098, 2095, 272, 269, 2108, 266, 2106, 281, 279,
  16996. 277, 1317, 1315, 1313, 1310, 282, 1321, 1319, 2039, 2037, 2035, 2032, 1203, 2029, 1200, 1197, 207, 2053, 205,
  16997. 2051, 201, 2049, 2046, 2043, 220, 218, 2064, 215, 2062, 211, 2059, 228, 226, 223, 2069, 1259, 1257, 1254, 232,
  16998. 1251, 230, 1267, 1265, 1263, 2316, 2315, 2312, 2311, 2309, 2314, 2304, 2303, 2301, 2299, 1593, 2308, 2306, 590,
  16999. 2288, 2287, 2285, 2283, 1578, 2280, 1577, 2295, 2293, 2291, 579, 577, 574, 571, 2298, 582, 581, 1592, 2263, 2262,
  17000. 2260, 2258, 1545, 2255, 1544, 2252, 1541, 2273, 2271, 2269, 2266, 1550, 535, 532, 2279, 528, 2277, 546, 543, 549,
  17001. 1575, 1573, 2224, 2222, 2220, 1486, 2217, 1485, 2214, 1482, 1479, 2238, 2236, 2234, 2231, 1496, 2228, 1492, 480,
  17002. 477, 2248, 473, 2246, 469, 2243, 490, 487, 2251, 497, 1537, 1535, 1532, 2477, 2476, 2474, 2479, 2469, 2468, 2466,
  17003. 2464, 1730, 2473, 2471, 2453, 2452, 2450, 2448, 1729, 2445, 1728, 2460, 2458, 2456, 2463, 805, 804, 2428, 2427,
  17004. 2425, 2423, 1725, 2420, 1724, 2417, 1722, 2438, 2436, 2434, 2431, 1727, 2444, 2442, 793, 791, 788, 795, 2388,
  17005. 2386, 2384, 1697, 2381, 1696, 2378, 1694, 1692, 2402, 2400, 2398, 2395, 1703, 2392, 1701, 2412, 2410, 2407, 751,
  17006. 748, 744, 2416, 759, 757, 1807, 2620, 2618, 1806, 1805, 2611, 2609, 2607, 2614, 1802, 1801, 1799, 2594, 2592,
  17007. 2590, 2587, 1804, 2600, 2598, 1794, 1793, 1791, 1789, 2564, 2562, 2560, 2557, 1798, 2554, 1796, 2574, 2572, 2569,
  17008. 2578, 1847, 1846, 2722, 1843, 1842, 1840, 1845, 2716, 2714, 1835, 1834, 1832, 1830, 1839, 1837, 2700, 2698, 2695,
  17009. 2704, 1817, 1811, 1810, 897, 862, 1777, 829, 826, 838, 1760, 1758, 808, 2481, 1741, 1740, 1738, 1743, 2624, 1818,
  17010. 2726, 2776, 782, 740, 737, 1715, 686, 679, 695, 1682, 1680, 639, 628, 2339, 647, 644, 1645, 1643, 1640, 1648,
  17011. 602, 600, 597, 595, 2320, 593, 2318, 609, 607, 604, 1611, 1610, 1608, 1606, 613, 1615, 1613, 2328, 926, 924, 892,
  17012. 886, 899, 857, 850, 2505, 1778, 824, 823, 821, 819, 2488, 818, 2486, 833, 831, 828, 840, 1761, 1759, 2649, 2632,
  17013. 2630, 2746, 2734, 2732, 2782, 2781, 570, 567, 1587, 531, 527, 523, 540, 1566, 1564, 476, 467, 463, 2240, 486,
  17014. 483, 1524, 1521, 1518, 1529, 411, 403, 2192, 399, 2189, 423, 416, 1462, 1457, 1454, 428, 1468, 1465, 2210, 366,
  17015. 363, 2158, 360, 2156, 357, 2153, 376, 373, 370, 2163, 1410, 1409, 1407, 1405, 382, 1402, 380, 1417, 1415, 1412,
  17016. 1421, 2175, 2174, 777, 774, 771, 784, 732, 725, 722, 2404, 743, 1716, 676, 674, 668, 2363, 665, 2360, 685, 1684,
  17017. 1681, 626, 624, 622, 2335, 620, 2333, 617, 2330, 641, 635, 649, 1646, 1644, 1642, 2566, 928, 925, 2530, 2527,
  17018. 894, 891, 888, 2501, 2499, 2496, 858, 856, 854, 851, 1779, 2692, 2668, 2665, 2645, 2643, 2640, 2651, 2768, 2759,
  17019. 2757, 2744, 2743, 2741, 2748, 352, 1382, 340, 337, 333, 1371, 1369, 307, 300, 296, 2126, 315, 312, 1347, 1342,
  17020. 1350, 261, 258, 250, 2097, 246, 2094, 271, 268, 264, 1306, 1301, 1298, 276, 1312, 1309, 2115, 203, 2048, 195,
  17021. 2045, 191, 2041, 213, 209, 2056, 1246, 1244, 1238, 225, 1234, 222, 1256, 1253, 1249, 1262, 2080, 2079, 154, 1997,
  17022. 150, 1995, 147, 1992, 1989, 163, 160, 2004, 156, 2001, 1175, 1174, 1172, 1170, 1167, 170, 1164, 167, 1185, 1183,
  17023. 1180, 1177, 174, 1190, 1188, 2025, 2024, 2022, 587, 586, 564, 559, 556, 2290, 573, 1588, 520, 518, 512, 2268,
  17024. 508, 2265, 530, 1568, 1565, 461, 457, 2233, 450, 2230, 446, 2226, 479, 471, 489, 1526, 1523, 1520, 397, 395,
  17025. 2185, 392, 2183, 389, 2180, 2177, 410, 2194, 402, 422, 1463, 1461, 1459, 1456, 1470, 2455, 799, 2433, 2430, 779,
  17026. 776, 773, 2397, 2394, 2390, 734, 728, 724, 746, 1717, 2356, 2354, 2351, 2348, 1658, 677, 675, 673, 670, 667, 688,
  17027. 1685, 1683, 2606, 2589, 2586, 2559, 2556, 2552, 927, 2523, 2521, 2518, 2515, 1784, 2532, 895, 893, 890, 2718,
  17028. 2709, 2707, 2689, 2687, 2684, 2663, 2662, 2660, 2658, 1825, 2667, 2769, 1852, 2760, 2758, 142, 141, 1139, 1138,
  17029. 134, 132, 129, 126, 1982, 1129, 1128, 1126, 1131, 113, 111, 108, 105, 1972, 101, 1970, 120, 118, 115, 1109, 1108,
  17030. 1106, 1104, 123, 1113, 1111, 82, 79, 1951, 75, 1949, 72, 1946, 92, 89, 86, 1956, 1077, 1076, 1074, 1072, 98,
  17031. 1069, 96, 1084, 1082, 1079, 1088, 1968, 1967, 48, 45, 1916, 42, 1914, 39, 1911, 1908, 60, 57, 54, 1923, 50, 1920,
  17032. 1031, 1030, 1028, 1026, 67, 1023, 65, 1020, 62, 1041, 1039, 1036, 1033, 69, 1046, 1044, 1944, 1943, 1941, 11, 9,
  17033. 1868, 7, 1865, 1862, 1859, 20, 1878, 16, 1875, 13, 1872, 970, 968, 966, 963, 29, 960, 26, 23, 983, 981, 978, 975,
  17034. 33, 971, 31, 990, 988, 985, 1906, 1904, 1902, 993, 351, 2145, 1383, 331, 330, 328, 326, 2137, 323, 2135, 339,
  17035. 1372, 1370, 294, 293, 291, 289, 2122, 286, 2120, 283, 2117, 309, 303, 317, 1348, 1346, 1344, 245, 244, 242, 2090,
  17036. 239, 2088, 236, 2085, 2082, 260, 2099, 249, 270, 1307, 1305, 1303, 1300, 1314, 189, 2038, 186, 2036, 183, 2033,
  17037. 2030, 2026, 206, 198, 2047, 194, 216, 1247, 1245, 1243, 1240, 227, 1237, 1255, 2310, 2302, 2300, 2286, 2284,
  17038. 2281, 565, 563, 561, 558, 575, 1589, 2261, 2259, 2256, 2253, 1542, 521, 519, 517, 514, 2270, 511, 533, 1569,
  17039. 1567, 2223, 2221, 2218, 2215, 1483, 2211, 1480, 459, 456, 453, 2232, 449, 474, 491, 1527, 1525, 1522, 2475, 2467,
  17040. 2465, 2451, 2449, 2446, 801, 800, 2426, 2424, 2421, 2418, 1723, 2435, 780, 778, 775, 2387, 2385, 2382, 2379,
  17041. 1695, 2375, 1693, 2396, 735, 733, 730, 727, 749, 1718, 2616, 2615, 2604, 2603, 2601, 2584, 2583, 2581, 2579,
  17042. 1800, 2591, 2550, 2549, 2547, 2545, 1792, 2542, 1790, 2558, 929, 2719, 1841, 2710, 2708, 1833, 1831, 2690, 2688,
  17043. 2686, 1815, 1809, 1808, 1774, 1756, 1754, 1737, 1736, 1734, 1739, 1816, 1711, 1676, 1674, 633, 629, 1638, 1636,
  17044. 1633, 1641, 598, 1605, 1604, 1602, 1600, 605, 1609, 1607, 2327, 887, 853, 1775, 822, 820, 1757, 1755, 1584, 524,
  17045. 1560, 1558, 468, 464, 1514, 1511, 1508, 1519, 408, 404, 400, 1452, 1447, 1444, 417, 1458, 1455, 2208, 364, 361,
  17046. 358, 2154, 1401, 1400, 1398, 1396, 374, 1393, 371, 1408, 1406, 1403, 1413, 2173, 2172, 772, 726, 723, 1712, 672,
  17047. 669, 666, 682, 1678, 1675, 625, 623, 621, 618, 2331, 636, 632, 1639, 1637, 1635, 920, 918, 884, 880, 889, 849,
  17048. 848, 847, 846, 2497, 855, 852, 1776, 2641, 2742, 2787, 1380, 334, 1367, 1365, 301, 297, 1340, 1338, 1335, 1343,
  17049. 255, 251, 247, 1296, 1291, 1288, 265, 1302, 1299, 2113, 204, 196, 192, 2042, 1232, 1230, 1224, 214, 1220, 210,
  17050. 1242, 1239, 1235, 1250, 2077, 2075, 151, 148, 1993, 144, 1990, 1163, 1162, 1160, 1158, 1155, 161, 1152, 157,
  17051. 1173, 1171, 1168, 1165, 168, 1181, 1178, 2021, 2020, 2018, 2023, 585, 560, 557, 1585, 516, 509, 1562, 1559, 458,
  17052. 447, 2227, 472, 1516, 1513, 1510, 398, 396, 393, 390, 2181, 386, 2178, 407, 1453, 1451, 1449, 1446, 420, 1460,
  17053. 2209, 769, 764, 720, 712, 2391, 729, 1713, 664, 663, 661, 659, 2352, 656, 2349, 671, 1679, 1677, 2553, 922, 919,
  17054. 2519, 2516, 885, 883, 881, 2685, 2661, 2659, 2767, 2756, 2755, 140, 1137, 1136, 130, 127, 1125, 1124, 1122, 1127,
  17055. 109, 106, 102, 1103, 1102, 1100, 1098, 116, 1107, 1105, 1980, 80, 76, 73, 1947, 1068, 1067, 1065, 1063, 90, 1060,
  17056. 87, 1075, 1073, 1070, 1080, 1966, 1965, 46, 43, 40, 1912, 36, 1909, 1019, 1018, 1016, 1014, 58, 1011, 55, 1008,
  17057. 51, 1029, 1027, 1024, 1021, 63, 1037, 1034, 1940, 1939, 1937, 1942, 8, 1866, 4, 1863, 1, 1860, 956, 954, 952,
  17058. 949, 946, 17, 14, 969, 967, 964, 961, 27, 957, 24, 979, 976, 972, 1901, 1900, 1898, 1896, 986, 1905, 1903, 350,
  17059. 349, 1381, 329, 327, 324, 1368, 1366, 292, 290, 287, 284, 2118, 304, 1341, 1339, 1337, 1345, 243, 240, 237, 2086,
  17060. 233, 2083, 254, 1297, 1295, 1293, 1290, 1304, 2114, 190, 187, 184, 2034, 180, 2031, 177, 2027, 199, 1233, 1231,
  17061. 1229, 1226, 217, 1223, 1241, 2078, 2076, 584, 555, 554, 552, 550, 2282, 562, 1586, 507, 506, 504, 502, 2257, 499,
  17062. 2254, 515, 1563, 1561, 445, 443, 441, 2219, 438, 2216, 435, 2212, 460, 454, 475, 1517, 1515, 1512, 2447, 798,
  17063. 797, 2422, 2419, 770, 768, 766, 2383, 2380, 2376, 721, 719, 717, 714, 731, 1714, 2602, 2582, 2580, 2548, 2546,
  17064. 2543, 923, 921, 2717, 2706, 2705, 2683, 2682, 2680, 1771, 1752, 1750, 1733, 1732, 1731, 1735, 1814, 1707, 1670,
  17065. 1668, 1631, 1629, 1626, 1634, 1599, 1598, 1596, 1594, 1603, 1601, 2326, 1772, 1753, 1751, 1581, 1554, 1552, 1504,
  17066. 1501, 1498, 1509, 1442, 1437, 1434, 401, 1448, 1445, 2206, 1392, 1391, 1389, 1387, 1384, 359, 1399, 1397, 1394,
  17067. 1404, 2171, 2170, 1708, 1672, 1669, 619, 1632, 1630, 1628, 1773, 1378, 1363, 1361, 1333, 1328, 1336, 1286, 1281,
  17068. 1278, 248, 1292, 1289, 2111, 1218, 1216, 1210, 197, 1206, 193, 1228, 1225, 1221, 1236, 2073, 2071, 1151, 1150,
  17069. 1148, 1146, 152, 1143, 149, 1140, 145, 1161, 1159, 1156, 1153, 158, 1169, 1166, 2017, 2016, 2014, 2019, 1582,
  17070. 510, 1556, 1553, 452, 448, 1506, 1500, 394, 391, 387, 1443, 1441, 1439, 1436, 1450, 2207, 765, 716, 713, 1709,
  17071. 662, 660, 657, 1673, 1671, 916, 914, 879, 878, 877, 882, 1135, 1134, 1121, 1120, 1118, 1123, 1097, 1096, 1094,
  17072. 1092, 103, 1101, 1099, 1979, 1059, 1058, 1056, 1054, 77, 1051, 74, 1066, 1064, 1061, 1071, 1964, 1963, 1007,
  17073. 1006, 1004, 1002, 999, 41, 996, 37, 1017, 1015, 1012, 1009, 52, 1025, 1022, 1936, 1935, 1933, 1938, 942, 940,
  17074. 938, 935, 932, 5, 2, 955, 953, 950, 947, 18, 943, 15, 965, 962, 958, 1895, 1894, 1892, 1890, 973, 1899, 1897,
  17075. 1379, 325, 1364, 1362, 288, 285, 1334, 1332, 1330, 241, 238, 234, 1287, 1285, 1283, 1280, 1294, 2112, 188, 185,
  17076. 181, 178, 2028, 1219, 1217, 1215, 1212, 200, 1209, 1227, 2074, 2072, 583, 553, 551, 1583, 505, 503, 500, 513,
  17077. 1557, 1555, 444, 442, 439, 436, 2213, 455, 451, 1507, 1505, 1502, 796, 763, 762, 760, 767, 711, 710, 708, 706,
  17078. 2377, 718, 715, 1710, 2544, 917, 915, 2681, 1627, 1597, 1595, 2325, 1769, 1749, 1747, 1499, 1438, 1435, 2204,
  17079. 1390, 1388, 1385, 1395, 2169, 2167, 1704, 1665, 1662, 1625, 1623, 1620, 1770, 1329, 1282, 1279, 2109, 1214, 1207,
  17080. 1222, 2068, 2065, 1149, 1147, 1144, 1141, 146, 1157, 1154, 2013, 2011, 2008, 2015, 1579, 1549, 1546, 1495, 1487,
  17081. 1433, 1431, 1428, 1425, 388, 1440, 2205, 1705, 658, 1667, 1664, 1119, 1095, 1093, 1978, 1057, 1055, 1052, 1062,
  17082. 1962, 1960, 1005, 1003, 1000, 997, 38, 1013, 1010, 1932, 1930, 1927, 1934, 941, 939, 936, 933, 6, 930, 3, 951,
  17083. 948, 944, 1889, 1887, 1884, 1881, 959, 1893, 1891, 35, 1377, 1360, 1358, 1327, 1325, 1322, 1331, 1277, 1275,
  17084. 1272, 1269, 235, 1284, 2110, 1205, 1204, 1201, 1198, 182, 1195, 179, 1213, 2070, 2067, 1580, 501, 1551, 1548,
  17085. 440, 437, 1497, 1494, 1490, 1503, 761, 709, 707, 1706, 913, 912, 2198, 1386, 2164, 2161, 1621, 1766, 2103, 1208,
  17086. 2058, 2054, 1145, 1142, 2005, 2002, 1999, 2009, 1488, 1429, 1426, 2200, 1698, 1659, 1656, 1975, 1053, 1957, 1954,
  17087. 1001, 998, 1924, 1921, 1918, 1928, 937, 934, 931, 1879, 1876, 1873, 1870, 945, 1885, 1882, 1323, 1273, 1270,
  17088. 2105, 1202, 1199, 1196, 1211, 2061, 2057, 1576, 1543, 1540, 1484, 1481, 1478, 1491, 1700
  17089. ]);
  17090. /*
  17091. * Copyright 2007 ZXing authors
  17092. *
  17093. * Licensed under the Apache License, Version 2.0 (the "License");
  17094. * you may not use this file except in compliance with the License.
  17095. * You may obtain a copy of the License at
  17096. *
  17097. * http://www.apache.org/licenses/LICENSE-2.0
  17098. *
  17099. * Unless required by applicable law or agreed to in writing, software
  17100. * distributed under the License is distributed on an "AS IS" BASIS,
  17101. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17102. * See the License for the specific language governing permissions and
  17103. * limitations under the License.
  17104. */
  17105. // import java.util.List;
  17106. /**
  17107. * @author Guenther Grau
  17108. */
  17109. /*public final*/ class PDF417DetectorResult {
  17110. constructor(bits, points) {
  17111. this.bits = bits;
  17112. this.points = points;
  17113. }
  17114. getBits() {
  17115. return this.bits;
  17116. }
  17117. getPoints() {
  17118. return this.points;
  17119. }
  17120. }
  17121. /*
  17122. * Copyright 2009 ZXing authors
  17123. *
  17124. * Licensed under the Apache License, Version 2.0 (the "License");
  17125. * you may not use this file except in compliance with the License.
  17126. * You may obtain a copy of the License at
  17127. *
  17128. * http://www.apache.org/licenses/LICENSE-2.0
  17129. *
  17130. * Unless required by applicable law or agreed to in writing, software
  17131. * distributed under the License is distributed on an "AS IS" BASIS,
  17132. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17133. * See the License for the specific language governing permissions and
  17134. * limitations under the License.
  17135. */
  17136. // import java.util.ArrayList;
  17137. // import java.util.Arrays;
  17138. // import java.util.List;
  17139. // import java.util.Map;
  17140. /**
  17141. * <p>Encapsulates logic that can detect a PDF417 Code in an image, even if the
  17142. * PDF417 Code is rotated or skewed, or partially obscured.</p>
  17143. *
  17144. * @author SITA Lab (kevin.osullivan@sita.aero)
  17145. * @author dswitkin@google.com (Daniel Switkin)
  17146. * @author Guenther Grau
  17147. */
  17148. /*public*/ /*final*/ class Detector$3 {
  17149. /**
  17150. * <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p>
  17151. *
  17152. * @param image barcode image to decode
  17153. * @param hints optional hints to detector
  17154. * @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will
  17155. * be found and returned
  17156. * @return {@link PDF417DetectorResult} encapsulating results of detecting a PDF417 code
  17157. * @throws NotFoundException if no PDF417 Code can be found
  17158. */
  17159. static detectMultiple(image, hints, multiple) {
  17160. // TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even
  17161. // different binarizers
  17162. // boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
  17163. let bitMatrix = image.getBlackMatrix();
  17164. let barcodeCoordinates = Detector$3.detect(multiple, bitMatrix);
  17165. if (!barcodeCoordinates.length) {
  17166. bitMatrix = bitMatrix.clone();
  17167. bitMatrix.rotate180();
  17168. barcodeCoordinates = Detector$3.detect(multiple, bitMatrix);
  17169. }
  17170. return new PDF417DetectorResult(bitMatrix, barcodeCoordinates);
  17171. }
  17172. /**
  17173. * Detects PDF417 codes in an image. Only checks 0 degree rotation
  17174. * @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will
  17175. * be found and returned
  17176. * @param bitMatrix bit matrix to detect barcodes in
  17177. * @return List of ResultPoint arrays containing the coordinates of found barcodes
  17178. */
  17179. static detect(multiple, bitMatrix) {
  17180. const barcodeCoordinates = new Array();
  17181. let row = 0;
  17182. let column = 0;
  17183. let foundBarcodeInRow = false;
  17184. while (row < bitMatrix.getHeight()) {
  17185. const vertices = Detector$3.findVertices(bitMatrix, row, column);
  17186. if (vertices[0] == null && vertices[3] == null) {
  17187. if (!foundBarcodeInRow) {
  17188. // we didn't find any barcode so that's the end of searching
  17189. break;
  17190. }
  17191. // we didn't find a barcode starting at the given column and row. Try again from the first column and slightly
  17192. // below the lowest barcode we found so far.
  17193. foundBarcodeInRow = false;
  17194. column = 0;
  17195. for (const barcodeCoordinate of barcodeCoordinates) {
  17196. if (barcodeCoordinate[1] != null) {
  17197. row = Math.trunc(Math.max(row, barcodeCoordinate[1].getY()));
  17198. }
  17199. if (barcodeCoordinate[3] != null) {
  17200. row = Math.max(row, Math.trunc(barcodeCoordinate[3].getY()));
  17201. }
  17202. }
  17203. row += Detector$3.ROW_STEP;
  17204. continue;
  17205. }
  17206. foundBarcodeInRow = true;
  17207. barcodeCoordinates.push(vertices);
  17208. if (!multiple) {
  17209. break;
  17210. }
  17211. // if we didn't find a right row indicator column, then continue the search for the next barcode after the
  17212. // start pattern of the barcode just found.
  17213. if (vertices[2] != null) {
  17214. column = Math.trunc(vertices[2].getX());
  17215. row = Math.trunc(vertices[2].getY());
  17216. }
  17217. else {
  17218. column = Math.trunc(vertices[4].getX());
  17219. row = Math.trunc(vertices[4].getY());
  17220. }
  17221. }
  17222. return barcodeCoordinates;
  17223. }
  17224. /**
  17225. * Locate the vertices and the codewords area of a black blob using the Start
  17226. * and Stop patterns as locators.
  17227. *
  17228. * @param matrix the scanned barcode image.
  17229. * @return an array containing the vertices:
  17230. * vertices[0] x, y top left barcode
  17231. * vertices[1] x, y bottom left barcode
  17232. * vertices[2] x, y top right barcode
  17233. * vertices[3] x, y bottom right barcode
  17234. * vertices[4] x, y top left codeword area
  17235. * vertices[5] x, y bottom left codeword area
  17236. * vertices[6] x, y top right codeword area
  17237. * vertices[7] x, y bottom right codeword area
  17238. */
  17239. static findVertices(matrix, startRow, startColumn) {
  17240. const height = matrix.getHeight();
  17241. const width = matrix.getWidth();
  17242. // const result = new ResultPoint[8];
  17243. const result = new Array(8);
  17244. Detector$3.copyToResult(result, Detector$3.findRowsWithPattern(matrix, height, width, startRow, startColumn, Detector$3.START_PATTERN), Detector$3.INDEXES_START_PATTERN);
  17245. if (result[4] != null) {
  17246. startColumn = Math.trunc(result[4].getX());
  17247. startRow = Math.trunc(result[4].getY());
  17248. }
  17249. Detector$3.copyToResult(result, Detector$3.findRowsWithPattern(matrix, height, width, startRow, startColumn, Detector$3.STOP_PATTERN), Detector$3.INDEXES_STOP_PATTERN);
  17250. return result;
  17251. }
  17252. static copyToResult(result, tmpResult, destinationIndexes) {
  17253. for (let i = 0; i < destinationIndexes.length; i++) {
  17254. result[destinationIndexes[i]] = tmpResult[i];
  17255. }
  17256. }
  17257. static findRowsWithPattern(matrix, height, width, startRow, startColumn, pattern) {
  17258. // const result = new ResultPoint[4];
  17259. const result = new Array(4);
  17260. let found = false;
  17261. const counters = new Int32Array(pattern.length);
  17262. for (; startRow < height; startRow += Detector$3.ROW_STEP) {
  17263. let loc = Detector$3.findGuardPattern(matrix, startColumn, startRow, width, false, pattern, counters);
  17264. if (loc != null) {
  17265. while (startRow > 0) {
  17266. const previousRowLoc = Detector$3.findGuardPattern(matrix, startColumn, --startRow, width, false, pattern, counters);
  17267. if (previousRowLoc != null) {
  17268. loc = previousRowLoc;
  17269. }
  17270. else {
  17271. startRow++;
  17272. break;
  17273. }
  17274. }
  17275. result[0] = new ResultPoint(loc[0], startRow);
  17276. result[1] = new ResultPoint(loc[1], startRow);
  17277. found = true;
  17278. break;
  17279. }
  17280. }
  17281. let stopRow = startRow + 1;
  17282. // Last row of the current symbol that contains pattern
  17283. if (found) {
  17284. let skippedRowCount = 0;
  17285. let previousRowLoc = Int32Array.from([Math.trunc(result[0].getX()), Math.trunc(result[1].getX())]);
  17286. for (; stopRow < height; stopRow++) {
  17287. const loc = Detector$3.findGuardPattern(matrix, previousRowLoc[0], stopRow, width, false, pattern, counters);
  17288. // a found pattern is only considered to belong to the same barcode if the start and end positions
  17289. // don't differ too much. Pattern drift should be not bigger than two for consecutive rows. With
  17290. // a higher number of skipped rows drift could be larger. To keep it simple for now, we allow a slightly
  17291. // larger drift and don't check for skipped rows.
  17292. if (loc != null &&
  17293. Math.abs(previousRowLoc[0] - loc[0]) < Detector$3.MAX_PATTERN_DRIFT &&
  17294. Math.abs(previousRowLoc[1] - loc[1]) < Detector$3.MAX_PATTERN_DRIFT) {
  17295. previousRowLoc = loc;
  17296. skippedRowCount = 0;
  17297. }
  17298. else {
  17299. if (skippedRowCount > Detector$3.SKIPPED_ROW_COUNT_MAX) {
  17300. break;
  17301. }
  17302. else {
  17303. skippedRowCount++;
  17304. }
  17305. }
  17306. }
  17307. stopRow -= skippedRowCount + 1;
  17308. result[2] = new ResultPoint(previousRowLoc[0], stopRow);
  17309. result[3] = new ResultPoint(previousRowLoc[1], stopRow);
  17310. }
  17311. if (stopRow - startRow < Detector$3.BARCODE_MIN_HEIGHT) {
  17312. Arrays.fill(result, null);
  17313. }
  17314. return result;
  17315. }
  17316. /**
  17317. * @param matrix row of black/white values to search
  17318. * @param column x position to start search
  17319. * @param row y position to start search
  17320. * @param width the number of pixels to search on this row
  17321. * @param pattern pattern of counts of number of black and white pixels that are
  17322. * being searched for as a pattern
  17323. * @param counters array of counters, as long as pattern, to re-use
  17324. * @return start/end horizontal offset of guard pattern, as an array of two ints.
  17325. */
  17326. static findGuardPattern(matrix, column, row, width, whiteFirst, pattern, counters) {
  17327. Arrays.fillWithin(counters, 0, counters.length, 0);
  17328. let patternStart = column;
  17329. let pixelDrift = 0;
  17330. // if there are black pixels left of the current pixel shift to the left, but only for MAX_PIXEL_DRIFT pixels
  17331. while (matrix.get(patternStart, row) && patternStart > 0 && pixelDrift++ < Detector$3.MAX_PIXEL_DRIFT) {
  17332. patternStart--;
  17333. }
  17334. let x = patternStart;
  17335. let counterPosition = 0;
  17336. let patternLength = pattern.length;
  17337. for (let isWhite = whiteFirst; x < width; x++) {
  17338. let pixel = matrix.get(x, row);
  17339. if (pixel !== isWhite) {
  17340. counters[counterPosition]++;
  17341. }
  17342. else {
  17343. if (counterPosition === patternLength - 1) {
  17344. if (Detector$3.patternMatchVariance(counters, pattern, Detector$3.MAX_INDIVIDUAL_VARIANCE) < Detector$3.MAX_AVG_VARIANCE) {
  17345. return new Int32Array([patternStart, x]);
  17346. }
  17347. patternStart += counters[0] + counters[1];
  17348. System.arraycopy(counters, 2, counters, 0, counterPosition - 1);
  17349. counters[counterPosition - 1] = 0;
  17350. counters[counterPosition] = 0;
  17351. counterPosition--;
  17352. }
  17353. else {
  17354. counterPosition++;
  17355. }
  17356. counters[counterPosition] = 1;
  17357. isWhite = !isWhite;
  17358. }
  17359. }
  17360. if (counterPosition === patternLength - 1 &&
  17361. Detector$3.patternMatchVariance(counters, pattern, Detector$3.MAX_INDIVIDUAL_VARIANCE) < Detector$3.MAX_AVG_VARIANCE) {
  17362. return new Int32Array([patternStart, x - 1]);
  17363. }
  17364. return null;
  17365. }
  17366. /**
  17367. * Determines how closely a set of observed counts of runs of black/white
  17368. * values matches a given target pattern. This is reported as the ratio of
  17369. * the total variance from the expected pattern proportions across all
  17370. * pattern elements, to the length of the pattern.
  17371. *
  17372. * @param counters observed counters
  17373. * @param pattern expected pattern
  17374. * @param maxIndividualVariance The most any counter can differ before we give up
  17375. * @return ratio of total variance between counters and pattern compared to total pattern size
  17376. */
  17377. static patternMatchVariance(counters, pattern, maxIndividualVariance) {
  17378. let numCounters = counters.length;
  17379. let total = 0;
  17380. let patternLength = 0;
  17381. for (let i = 0; i < numCounters; i++) {
  17382. total += counters[i];
  17383. patternLength += pattern[i];
  17384. }
  17385. if (total < patternLength) {
  17386. // If we don't even have one pixel per unit of bar width, assume this
  17387. // is too small to reliably match, so fail:
  17388. return /*Float.POSITIVE_INFINITY*/ Infinity;
  17389. }
  17390. // We're going to fake floating-point math in integers. We just need to use more bits.
  17391. // Scale up patternLength so that intermediate values below like scaledCounter will have
  17392. // more "significant digits".
  17393. let unitBarWidth = total / patternLength;
  17394. maxIndividualVariance *= unitBarWidth;
  17395. let totalVariance = 0.0;
  17396. for (let x = 0; x < numCounters; x++) {
  17397. let counter = counters[x];
  17398. let scaledPattern = pattern[x] * unitBarWidth;
  17399. let variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
  17400. if (variance > maxIndividualVariance) {
  17401. return /*Float.POSITIVE_INFINITY*/ Infinity;
  17402. }
  17403. totalVariance += variance;
  17404. }
  17405. return totalVariance / total;
  17406. }
  17407. }
  17408. Detector$3.INDEXES_START_PATTERN = Int32Array.from([0, 4, 1, 5]);
  17409. Detector$3.INDEXES_STOP_PATTERN = Int32Array.from([6, 2, 7, 3]);
  17410. Detector$3.MAX_AVG_VARIANCE = 0.42;
  17411. Detector$3.MAX_INDIVIDUAL_VARIANCE = 0.8;
  17412. // B S B S B S B S Bar/Space pattern
  17413. // 11111111 0 1 0 1 0 1 000
  17414. Detector$3.START_PATTERN = Int32Array.from([8, 1, 1, 1, 1, 1, 1, 3]);
  17415. // 1111111 0 1 000 1 0 1 00 1
  17416. Detector$3.STOP_PATTERN = Int32Array.from([7, 1, 1, 3, 1, 1, 1, 2, 1]);
  17417. Detector$3.MAX_PIXEL_DRIFT = 3;
  17418. Detector$3.MAX_PATTERN_DRIFT = 5;
  17419. // if we set the value too low, then we don't detect the correct height of the bar if the start patterns are damaged.
  17420. // if we set the value too high, then we might detect the start pattern from a neighbor barcode.
  17421. Detector$3.SKIPPED_ROW_COUNT_MAX = 25;
  17422. // A PDF471 barcode should have at least 3 rows, with each row being >= 3 times the module width. Therefore it should be at least
  17423. // 9 pixels tall. To be conservative, we use about half the size to ensure we don't miss it.
  17424. Detector$3.ROW_STEP = 5;
  17425. Detector$3.BARCODE_MIN_HEIGHT = 10;
  17426. /*
  17427. * Copyright 2012 ZXing authors
  17428. *
  17429. * Licensed under the Apache License, Version 2.0 (the "License");
  17430. * you may not use this file except in compliance with the License.
  17431. * You may obtain a copy of the License at
  17432. *
  17433. * http://www.apache.org/licenses/LICENSE-2.0
  17434. *
  17435. * Unless required by applicable law or agreed to in writing, software
  17436. * distributed under the License is distributed on an "AS IS" BASIS,
  17437. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17438. * See the License for the specific language governing permissions and
  17439. * limitations under the License.
  17440. */
  17441. /**
  17442. * @author Sean Owen
  17443. * @see com.google.zxing.common.reedsolomon.GenericGFPoly
  17444. */
  17445. /*final*/ class ModulusPoly {
  17446. constructor(field, coefficients) {
  17447. if (coefficients.length === 0) {
  17448. throw new IllegalArgumentException();
  17449. }
  17450. this.field = field;
  17451. let coefficientsLength = /*int*/ coefficients.length;
  17452. if (coefficientsLength > 1 && coefficients[0] === 0) {
  17453. // Leading term must be non-zero for anything except the constant polynomial "0"
  17454. let firstNonZero = /*int*/ 1;
  17455. while (firstNonZero < coefficientsLength && coefficients[firstNonZero] === 0) {
  17456. firstNonZero++;
  17457. }
  17458. if (firstNonZero === coefficientsLength) {
  17459. this.coefficients = new Int32Array([0]);
  17460. }
  17461. else {
  17462. this.coefficients = new Int32Array(coefficientsLength - firstNonZero);
  17463. System.arraycopy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length);
  17464. }
  17465. }
  17466. else {
  17467. this.coefficients = coefficients;
  17468. }
  17469. }
  17470. getCoefficients() {
  17471. return this.coefficients;
  17472. }
  17473. /**
  17474. * @return degree of this polynomial
  17475. */
  17476. getDegree() {
  17477. return this.coefficients.length - 1;
  17478. }
  17479. /**
  17480. * @return true iff this polynomial is the monomial "0"
  17481. */
  17482. isZero() {
  17483. return this.coefficients[0] === 0;
  17484. }
  17485. /**
  17486. * @return coefficient of x^degree term in this polynomial
  17487. */
  17488. getCoefficient(degree) {
  17489. return this.coefficients[this.coefficients.length - 1 - degree];
  17490. }
  17491. /**
  17492. * @return evaluation of this polynomial at a given point
  17493. */
  17494. evaluateAt(a) {
  17495. if (a === 0) {
  17496. // Just return the x^0 coefficient
  17497. return this.getCoefficient(0);
  17498. }
  17499. if (a === 1) {
  17500. // Just the sum of the coefficients
  17501. let sum = /*int*/ 0;
  17502. for (let coefficient /*int*/ of this.coefficients) {
  17503. sum = this.field.add(sum, coefficient);
  17504. }
  17505. return sum;
  17506. }
  17507. let result = /*int*/ this.coefficients[0];
  17508. let size = /*int*/ this.coefficients.length;
  17509. for (let i /*int*/ = 1; i < size; i++) {
  17510. result = this.field.add(this.field.multiply(a, result), this.coefficients[i]);
  17511. }
  17512. return result;
  17513. }
  17514. add(other) {
  17515. if (!this.field.equals(other.field)) {
  17516. throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');
  17517. }
  17518. if (this.isZero()) {
  17519. return other;
  17520. }
  17521. if (other.isZero()) {
  17522. return this;
  17523. }
  17524. let smallerCoefficients = this.coefficients;
  17525. let largerCoefficients = other.coefficients;
  17526. if (smallerCoefficients.length > largerCoefficients.length) {
  17527. let temp = smallerCoefficients;
  17528. smallerCoefficients = largerCoefficients;
  17529. largerCoefficients = temp;
  17530. }
  17531. let sumDiff = new Int32Array(largerCoefficients.length);
  17532. let lengthDiff = /*int*/ largerCoefficients.length - smallerCoefficients.length;
  17533. // Copy high-order terms only found in higher-degree polynomial's coefficients
  17534. System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
  17535. for (let i /*int*/ = lengthDiff; i < largerCoefficients.length; i++) {
  17536. sumDiff[i] = this.field.add(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
  17537. }
  17538. return new ModulusPoly(this.field, sumDiff);
  17539. }
  17540. subtract(other) {
  17541. if (!this.field.equals(other.field)) {
  17542. throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');
  17543. }
  17544. if (other.isZero()) {
  17545. return this;
  17546. }
  17547. return this.add(other.negative());
  17548. }
  17549. multiply(other) {
  17550. if (other instanceof ModulusPoly) {
  17551. return this.multiplyOther(other);
  17552. }
  17553. return this.multiplyScalar(other);
  17554. }
  17555. multiplyOther(other) {
  17556. if (!this.field.equals(other.field)) {
  17557. throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');
  17558. }
  17559. if (this.isZero() || other.isZero()) {
  17560. // return this.field.getZero();
  17561. return new ModulusPoly(this.field, new Int32Array([0]));
  17562. }
  17563. let aCoefficients = this.coefficients;
  17564. let aLength = /*int*/ aCoefficients.length;
  17565. let bCoefficients = other.coefficients;
  17566. let bLength = /*int*/ bCoefficients.length;
  17567. let product = new Int32Array(aLength + bLength - 1);
  17568. for (let i /*int*/ = 0; i < aLength; i++) {
  17569. let aCoeff = /*int*/ aCoefficients[i];
  17570. for (let j /*int*/ = 0; j < bLength; j++) {
  17571. product[i + j] = this.field.add(product[i + j], this.field.multiply(aCoeff, bCoefficients[j]));
  17572. }
  17573. }
  17574. return new ModulusPoly(this.field, product);
  17575. }
  17576. negative() {
  17577. let size = /*int*/ this.coefficients.length;
  17578. let negativeCoefficients = new Int32Array(size);
  17579. for (let i /*int*/ = 0; i < size; i++) {
  17580. negativeCoefficients[i] = this.field.subtract(0, this.coefficients[i]);
  17581. }
  17582. return new ModulusPoly(this.field, negativeCoefficients);
  17583. }
  17584. multiplyScalar(scalar) {
  17585. if (scalar === 0) {
  17586. return new ModulusPoly(this.field, new Int32Array([0]));
  17587. }
  17588. if (scalar === 1) {
  17589. return this;
  17590. }
  17591. let size = /*int*/ this.coefficients.length;
  17592. let product = new Int32Array(size);
  17593. for (let i /*int*/ = 0; i < size; i++) {
  17594. product[i] = this.field.multiply(this.coefficients[i], scalar);
  17595. }
  17596. return new ModulusPoly(this.field, product);
  17597. }
  17598. multiplyByMonomial(degree, coefficient) {
  17599. if (degree < 0) {
  17600. throw new IllegalArgumentException();
  17601. }
  17602. if (coefficient === 0) {
  17603. return new ModulusPoly(this.field, new Int32Array([0]));
  17604. }
  17605. let size = /*int*/ this.coefficients.length;
  17606. let product = new Int32Array(size + degree);
  17607. for (let i /*int*/ = 0; i < size; i++) {
  17608. product[i] = this.field.multiply(this.coefficients[i], coefficient);
  17609. }
  17610. return new ModulusPoly(this.field, product);
  17611. }
  17612. /*
  17613. ModulusPoly[] divide(other: ModulusPoly) {
  17614. if (!field.equals(other.field)) {
  17615. throw new IllegalArgumentException("ModulusPolys do not have same ModulusGF field");
  17616. }
  17617. if (other.isZero()) {
  17618. throw new IllegalArgumentException("Divide by 0");
  17619. }
  17620. let quotient: ModulusPoly = field.getZero();
  17621. let remainder: ModulusPoly = this;
  17622. let denominatorLeadingTerm: /*int/ number = other.getCoefficient(other.getDegree());
  17623. let inverseDenominatorLeadingTerm: /*int/ number = field.inverse(denominatorLeadingTerm);
  17624. while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) {
  17625. let degreeDifference: /*int/ number = remainder.getDegree() - other.getDegree();
  17626. let scale: /*int/ number = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm);
  17627. let term: ModulusPoly = other.multiplyByMonomial(degreeDifference, scale);
  17628. let iterationQuotient: ModulusPoly = field.buildMonomial(degreeDifference, scale);
  17629. quotient = quotient.add(iterationQuotient);
  17630. remainder = remainder.subtract(term);
  17631. }
  17632. return new ModulusPoly[] { quotient, remainder };
  17633. }
  17634. */
  17635. // @Override
  17636. toString() {
  17637. let result = new StringBuilder( /*8 * this.getDegree()*/); // dynamic string size in JS
  17638. for (let degree /*int*/ = this.getDegree(); degree >= 0; degree--) {
  17639. let coefficient = /*int*/ this.getCoefficient(degree);
  17640. if (coefficient !== 0) {
  17641. if (coefficient < 0) {
  17642. result.append(' - ');
  17643. coefficient = -coefficient;
  17644. }
  17645. else {
  17646. if (result.length() > 0) {
  17647. result.append(' + ');
  17648. }
  17649. }
  17650. if (degree === 0 || coefficient !== 1) {
  17651. result.append(coefficient);
  17652. }
  17653. if (degree !== 0) {
  17654. if (degree === 1) {
  17655. result.append('x');
  17656. }
  17657. else {
  17658. result.append('x^');
  17659. result.append(degree);
  17660. }
  17661. }
  17662. }
  17663. }
  17664. return result.toString();
  17665. }
  17666. }
  17667. class ModulusBase {
  17668. add(a, b) {
  17669. return (a + b) % this.modulus;
  17670. }
  17671. subtract(a, b) {
  17672. return (this.modulus + a - b) % this.modulus;
  17673. }
  17674. exp(a) {
  17675. return this.expTable[a];
  17676. }
  17677. log(a) {
  17678. if (a === 0) {
  17679. throw new IllegalArgumentException();
  17680. }
  17681. return this.logTable[a];
  17682. }
  17683. inverse(a) {
  17684. if (a === 0) {
  17685. throw new ArithmeticException();
  17686. }
  17687. return this.expTable[this.modulus - this.logTable[a] - 1];
  17688. }
  17689. multiply(a, b) {
  17690. if (a === 0 || b === 0) {
  17691. return 0;
  17692. }
  17693. return this.expTable[(this.logTable[a] + this.logTable[b]) % (this.modulus - 1)];
  17694. }
  17695. getSize() {
  17696. return this.modulus;
  17697. }
  17698. equals(o) {
  17699. return o === this;
  17700. }
  17701. }
  17702. /*
  17703. * Copyright 2012 ZXing authors
  17704. *
  17705. * Licensed under the Apache License, Version 2.0 (the "License");
  17706. * you may not use this file except in compliance with the License.
  17707. * You may obtain a copy of the License at
  17708. *
  17709. * http://www.apache.org/licenses/LICENSE-2.0
  17710. *
  17711. * Unless required by applicable law or agreed to in writing, software
  17712. * distributed under the License is distributed on an "AS IS" BASIS,
  17713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17714. * See the License for the specific language governing permissions and
  17715. * limitations under the License.
  17716. */
  17717. /**
  17718. * <p>A field based on powers of a generator integer, modulo some modulus.</p>
  17719. *
  17720. * @author Sean Owen
  17721. * @see com.google.zxing.common.reedsolomon.GenericGF
  17722. */
  17723. /*public final*/ class ModulusGF extends ModulusBase {
  17724. // private /*final*/ modulus: /*int*/ number;
  17725. constructor(modulus, generator) {
  17726. super();
  17727. this.modulus = modulus;
  17728. this.expTable = new Int32Array(modulus);
  17729. this.logTable = new Int32Array(modulus);
  17730. let x = /*int*/ 1;
  17731. for (let i /*int*/ = 0; i < modulus; i++) {
  17732. this.expTable[i] = x;
  17733. x = (x * generator) % modulus;
  17734. }
  17735. for (let i /*int*/ = 0; i < modulus - 1; i++) {
  17736. this.logTable[this.expTable[i]] = i;
  17737. }
  17738. // logTable[0] == 0 but this should never be used
  17739. this.zero = new ModulusPoly(this, new Int32Array([0]));
  17740. this.one = new ModulusPoly(this, new Int32Array([1]));
  17741. }
  17742. getZero() {
  17743. return this.zero;
  17744. }
  17745. getOne() {
  17746. return this.one;
  17747. }
  17748. buildMonomial(degree, coefficient) {
  17749. if (degree < 0) {
  17750. throw new IllegalArgumentException();
  17751. }
  17752. if (coefficient === 0) {
  17753. return this.zero;
  17754. }
  17755. let coefficients = new Int32Array(degree + 1);
  17756. coefficients[0] = coefficient;
  17757. return new ModulusPoly(this, coefficients);
  17758. }
  17759. }
  17760. ModulusGF.PDF417_GF = new ModulusGF(PDF417Common.NUMBER_OF_CODEWORDS, 3);
  17761. /*
  17762. * Copyright 2012 ZXing authors
  17763. *
  17764. * Licensed under the Apache License, Version 2.0 (the "License");
  17765. * you may not use this file except in compliance with the License.
  17766. * You may obtain a copy of the License at
  17767. *
  17768. * http://www.apache.org/licenses/LICENSE-2.0
  17769. *
  17770. * Unless required by applicable law or agreed to in writing, software
  17771. * distributed under the License is distributed on an "AS IS" BASIS,
  17772. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17773. * See the License for the specific language governing permissions and
  17774. * limitations under the License.
  17775. */
  17776. /**
  17777. * <p>PDF417 error correction implementation.</p>
  17778. *
  17779. * <p>This <a href="http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction#Example">example</a>
  17780. * is quite useful in understanding the algorithm.</p>
  17781. *
  17782. * @author Sean Owen
  17783. * @see com.google.zxing.common.reedsolomon.ReedSolomonDecoder
  17784. */
  17785. /*public final*/ class ErrorCorrection {
  17786. constructor() {
  17787. this.field = ModulusGF.PDF417_GF;
  17788. }
  17789. /**
  17790. * @param received received codewords
  17791. * @param numECCodewords number of those codewords used for EC
  17792. * @param erasures location of erasures
  17793. * @return number of errors
  17794. * @throws ChecksumException if errors cannot be corrected, maybe because of too many errors
  17795. */
  17796. decode(received, numECCodewords, erasures) {
  17797. let poly = new ModulusPoly(this.field, received);
  17798. let S = new Int32Array(numECCodewords);
  17799. let error = false;
  17800. for (let i /*int*/ = numECCodewords; i > 0; i--) {
  17801. let evaluation = poly.evaluateAt(this.field.exp(i));
  17802. S[numECCodewords - i] = evaluation;
  17803. if (evaluation !== 0) {
  17804. error = true;
  17805. }
  17806. }
  17807. if (!error) {
  17808. return 0;
  17809. }
  17810. let knownErrors = this.field.getOne();
  17811. if (erasures != null) {
  17812. for (const erasure of erasures) {
  17813. let b = this.field.exp(received.length - 1 - erasure);
  17814. // Add (1 - bx) term:
  17815. let term = new ModulusPoly(this.field, new Int32Array([this.field.subtract(0, b), 1]));
  17816. knownErrors = knownErrors.multiply(term);
  17817. }
  17818. }
  17819. let syndrome = new ModulusPoly(this.field, S);
  17820. // syndrome = syndrome.multiply(knownErrors);
  17821. let sigmaOmega = this.runEuclideanAlgorithm(this.field.buildMonomial(numECCodewords, 1), syndrome, numECCodewords);
  17822. let sigma = sigmaOmega[0];
  17823. let omega = sigmaOmega[1];
  17824. // sigma = sigma.multiply(knownErrors);
  17825. let errorLocations = this.findErrorLocations(sigma);
  17826. let errorMagnitudes = this.findErrorMagnitudes(omega, sigma, errorLocations);
  17827. for (let i /*int*/ = 0; i < errorLocations.length; i++) {
  17828. let position = received.length - 1 - this.field.log(errorLocations[i]);
  17829. if (position < 0) {
  17830. throw ChecksumException.getChecksumInstance();
  17831. }
  17832. received[position] = this.field.subtract(received[position], errorMagnitudes[i]);
  17833. }
  17834. return errorLocations.length;
  17835. }
  17836. /**
  17837. *
  17838. * @param ModulusPoly
  17839. * @param a
  17840. * @param ModulusPoly
  17841. * @param b
  17842. * @param int
  17843. * @param R
  17844. * @throws ChecksumException
  17845. */
  17846. runEuclideanAlgorithm(a, b, R) {
  17847. // Assume a's degree is >= b's
  17848. if (a.getDegree() < b.getDegree()) {
  17849. let temp = a;
  17850. a = b;
  17851. b = temp;
  17852. }
  17853. let rLast = a;
  17854. let r = b;
  17855. let tLast = this.field.getZero();
  17856. let t = this.field.getOne();
  17857. // Run Euclidean algorithm until r's degree is less than R/2
  17858. while (r.getDegree() >= Math.round(R / 2)) {
  17859. let rLastLast = rLast;
  17860. let tLastLast = tLast;
  17861. rLast = r;
  17862. tLast = t;
  17863. // Divide rLastLast by rLast, with quotient in q and remainder in r
  17864. if (rLast.isZero()) {
  17865. // Oops, Euclidean algorithm already terminated?
  17866. throw ChecksumException.getChecksumInstance();
  17867. }
  17868. r = rLastLast;
  17869. let q = this.field.getZero();
  17870. let denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
  17871. let dltInverse = this.field.inverse(denominatorLeadingTerm);
  17872. while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
  17873. let degreeDiff = r.getDegree() - rLast.getDegree();
  17874. let scale = this.field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
  17875. q = q.add(this.field.buildMonomial(degreeDiff, scale));
  17876. r = r.subtract(rLast.multiplyByMonomial(degreeDiff, scale));
  17877. }
  17878. t = q.multiply(tLast).subtract(tLastLast).negative();
  17879. }
  17880. let sigmaTildeAtZero = t.getCoefficient(0);
  17881. if (sigmaTildeAtZero === 0) {
  17882. throw ChecksumException.getChecksumInstance();
  17883. }
  17884. let inverse = this.field.inverse(sigmaTildeAtZero);
  17885. let sigma = t.multiply(inverse);
  17886. let omega = r.multiply(inverse);
  17887. return [sigma, omega];
  17888. }
  17889. /**
  17890. *
  17891. * @param errorLocator
  17892. * @throws ChecksumException
  17893. */
  17894. findErrorLocations(errorLocator) {
  17895. // This is a direct application of Chien's search
  17896. let numErrors = errorLocator.getDegree();
  17897. let result = new Int32Array(numErrors);
  17898. let e = 0;
  17899. for (let i /*int*/ = 1; i < this.field.getSize() && e < numErrors; i++) {
  17900. if (errorLocator.evaluateAt(i) === 0) {
  17901. result[e] = this.field.inverse(i);
  17902. e++;
  17903. }
  17904. }
  17905. if (e !== numErrors) {
  17906. throw ChecksumException.getChecksumInstance();
  17907. }
  17908. return result;
  17909. }
  17910. findErrorMagnitudes(errorEvaluator, errorLocator, errorLocations) {
  17911. let errorLocatorDegree = errorLocator.getDegree();
  17912. let formalDerivativeCoefficients = new Int32Array(errorLocatorDegree);
  17913. for (let i /*int*/ = 1; i <= errorLocatorDegree; i++) {
  17914. formalDerivativeCoefficients[errorLocatorDegree - i] =
  17915. this.field.multiply(i, errorLocator.getCoefficient(i));
  17916. }
  17917. let formalDerivative = new ModulusPoly(this.field, formalDerivativeCoefficients);
  17918. // This is directly applying Forney's Formula
  17919. let s = errorLocations.length;
  17920. let result = new Int32Array(s);
  17921. for (let i /*int*/ = 0; i < s; i++) {
  17922. let xiInverse = this.field.inverse(errorLocations[i]);
  17923. let numerator = this.field.subtract(0, errorEvaluator.evaluateAt(xiInverse));
  17924. let denominator = this.field.inverse(formalDerivative.evaluateAt(xiInverse));
  17925. result[i] = this.field.multiply(numerator, denominator);
  17926. }
  17927. return result;
  17928. }
  17929. }
  17930. /*
  17931. * Copyright 2013 ZXing authors
  17932. *
  17933. * Licensed under the Apache License, Version 2.0 (the "License");
  17934. * you may not use this file except in compliance with the License.
  17935. * You may obtain a copy of the License at
  17936. *
  17937. * http://www.apache.org/licenses/LICENSE-2.0
  17938. *
  17939. * Unless required by applicable law or agreed to in writing, software
  17940. * distributed under the License is distributed on an "AS IS" BASIS,
  17941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17942. * See the License for the specific language governing permissions and
  17943. * limitations under the License.
  17944. */
  17945. /**
  17946. * @author Guenther Grau
  17947. */
  17948. /*final*/ class BoundingBox {
  17949. constructor(image, topLeft, bottomLeft, topRight, bottomRight) {
  17950. if (image instanceof BoundingBox) {
  17951. this.constructor_2(image);
  17952. }
  17953. else {
  17954. this.constructor_1(image, topLeft, bottomLeft, topRight, bottomRight);
  17955. }
  17956. }
  17957. /**
  17958. *
  17959. * @param image
  17960. * @param topLeft
  17961. * @param bottomLeft
  17962. * @param topRight
  17963. * @param bottomRight
  17964. *
  17965. * @throws NotFoundException
  17966. */
  17967. constructor_1(image, topLeft, bottomLeft, topRight, bottomRight) {
  17968. const leftUnspecified = topLeft == null || bottomLeft == null;
  17969. const rightUnspecified = topRight == null || bottomRight == null;
  17970. if (leftUnspecified && rightUnspecified) {
  17971. throw new NotFoundException();
  17972. }
  17973. if (leftUnspecified) {
  17974. topLeft = new ResultPoint(0, topRight.getY());
  17975. bottomLeft = new ResultPoint(0, bottomRight.getY());
  17976. }
  17977. else if (rightUnspecified) {
  17978. topRight = new ResultPoint(image.getWidth() - 1, topLeft.getY());
  17979. bottomRight = new ResultPoint(image.getWidth() - 1, bottomLeft.getY());
  17980. }
  17981. this.image = image;
  17982. this.topLeft = topLeft;
  17983. this.bottomLeft = bottomLeft;
  17984. this.topRight = topRight;
  17985. this.bottomRight = bottomRight;
  17986. this.minX = Math.trunc(Math.min(topLeft.getX(), bottomLeft.getX()));
  17987. this.maxX = Math.trunc(Math.max(topRight.getX(), bottomRight.getX()));
  17988. this.minY = Math.trunc(Math.min(topLeft.getY(), topRight.getY()));
  17989. this.maxY = Math.trunc(Math.max(bottomLeft.getY(), bottomRight.getY()));
  17990. }
  17991. constructor_2(boundingBox) {
  17992. this.image = boundingBox.image;
  17993. this.topLeft = boundingBox.getTopLeft();
  17994. this.bottomLeft = boundingBox.getBottomLeft();
  17995. this.topRight = boundingBox.getTopRight();
  17996. this.bottomRight = boundingBox.getBottomRight();
  17997. this.minX = boundingBox.getMinX();
  17998. this.maxX = boundingBox.getMaxX();
  17999. this.minY = boundingBox.getMinY();
  18000. this.maxY = boundingBox.getMaxY();
  18001. }
  18002. /**
  18003. * @throws NotFoundException
  18004. */
  18005. static merge(leftBox, rightBox) {
  18006. if (leftBox == null) {
  18007. return rightBox;
  18008. }
  18009. if (rightBox == null) {
  18010. return leftBox;
  18011. }
  18012. return new BoundingBox(leftBox.image, leftBox.topLeft, leftBox.bottomLeft, rightBox.topRight, rightBox.bottomRight);
  18013. }
  18014. /**
  18015. * @throws NotFoundException
  18016. */
  18017. addMissingRows(missingStartRows, missingEndRows, isLeft) {
  18018. let newTopLeft = this.topLeft;
  18019. let newBottomLeft = this.bottomLeft;
  18020. let newTopRight = this.topRight;
  18021. let newBottomRight = this.bottomRight;
  18022. if (missingStartRows > 0) {
  18023. let top = isLeft ? this.topLeft : this.topRight;
  18024. let newMinY = Math.trunc(top.getY() - missingStartRows);
  18025. if (newMinY < 0) {
  18026. newMinY = 0;
  18027. }
  18028. let newTop = new ResultPoint(top.getX(), newMinY);
  18029. if (isLeft) {
  18030. newTopLeft = newTop;
  18031. }
  18032. else {
  18033. newTopRight = newTop;
  18034. }
  18035. }
  18036. if (missingEndRows > 0) {
  18037. let bottom = isLeft ? this.bottomLeft : this.bottomRight;
  18038. let newMaxY = Math.trunc(bottom.getY() + missingEndRows);
  18039. if (newMaxY >= this.image.getHeight()) {
  18040. newMaxY = this.image.getHeight() - 1;
  18041. }
  18042. let newBottom = new ResultPoint(bottom.getX(), newMaxY);
  18043. if (isLeft) {
  18044. newBottomLeft = newBottom;
  18045. }
  18046. else {
  18047. newBottomRight = newBottom;
  18048. }
  18049. }
  18050. return new BoundingBox(this.image, newTopLeft, newBottomLeft, newTopRight, newBottomRight);
  18051. }
  18052. getMinX() {
  18053. return this.minX;
  18054. }
  18055. getMaxX() {
  18056. return this.maxX;
  18057. }
  18058. getMinY() {
  18059. return this.minY;
  18060. }
  18061. getMaxY() {
  18062. return this.maxY;
  18063. }
  18064. getTopLeft() {
  18065. return this.topLeft;
  18066. }
  18067. getTopRight() {
  18068. return this.topRight;
  18069. }
  18070. getBottomLeft() {
  18071. return this.bottomLeft;
  18072. }
  18073. getBottomRight() {
  18074. return this.bottomRight;
  18075. }
  18076. }
  18077. /*
  18078. * Copyright 2013 ZXing authors
  18079. *
  18080. * Licensed under the Apache License, Version 2.0 (the "License");
  18081. * you may not use this file except in compliance with the License.
  18082. * You may obtain a copy of the License at
  18083. *
  18084. * http://www.apache.org/licenses/LICENSE-2.0
  18085. *
  18086. * Unless required by applicable law or agreed to in writing, software
  18087. * distributed under the License is distributed on an "AS IS" BASIS,
  18088. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18089. * See the License for the specific language governing permissions and
  18090. * limitations under the License.
  18091. */
  18092. // package com.google.zxing.pdf417.decoder;
  18093. /**
  18094. * @author Guenther Grau
  18095. */
  18096. /*final*/ class BarcodeMetadata {
  18097. constructor(columnCount, rowCountUpperPart, rowCountLowerPart, errorCorrectionLevel) {
  18098. this.columnCount = columnCount;
  18099. this.errorCorrectionLevel = errorCorrectionLevel;
  18100. this.rowCountUpperPart = rowCountUpperPart;
  18101. this.rowCountLowerPart = rowCountLowerPart;
  18102. this.rowCount = rowCountUpperPart + rowCountLowerPart;
  18103. }
  18104. getColumnCount() {
  18105. return this.columnCount;
  18106. }
  18107. getErrorCorrectionLevel() {
  18108. return this.errorCorrectionLevel;
  18109. }
  18110. getRowCount() {
  18111. return this.rowCount;
  18112. }
  18113. getRowCountUpperPart() {
  18114. return this.rowCountUpperPart;
  18115. }
  18116. getRowCountLowerPart() {
  18117. return this.rowCountLowerPart;
  18118. }
  18119. }
  18120. /**
  18121. * Java Formatter class polyfill that works in the JS way.
  18122. */
  18123. class Formatter {
  18124. constructor() {
  18125. this.buffer = '';
  18126. }
  18127. /**
  18128. *
  18129. * @see https://stackoverflow.com/a/13439711/4367683
  18130. *
  18131. * @param str
  18132. * @param arr
  18133. */
  18134. static form(str, arr) {
  18135. let i = -1;
  18136. function callback(exp, p0, p1, p2, p3, p4) {
  18137. if (exp === '%%')
  18138. return '%';
  18139. if (arr[++i] === undefined)
  18140. return undefined;
  18141. exp = p2 ? parseInt(p2.substr(1)) : undefined;
  18142. let base = p3 ? parseInt(p3.substr(1)) : undefined;
  18143. let val;
  18144. switch (p4) {
  18145. case 's':
  18146. val = arr[i];
  18147. break;
  18148. case 'c':
  18149. val = arr[i][0];
  18150. break;
  18151. case 'f':
  18152. val = parseFloat(arr[i]).toFixed(exp);
  18153. break;
  18154. case 'p':
  18155. val = parseFloat(arr[i]).toPrecision(exp);
  18156. break;
  18157. case 'e':
  18158. val = parseFloat(arr[i]).toExponential(exp);
  18159. break;
  18160. case 'x':
  18161. val = parseInt(arr[i]).toString(base ? base : 16);
  18162. break;
  18163. case 'd':
  18164. val = parseFloat(parseInt(arr[i], base ? base : 10).toPrecision(exp)).toFixed(0);
  18165. break;
  18166. }
  18167. val = typeof val === 'object' ? JSON.stringify(val) : (+val).toString(base);
  18168. let size = parseInt(p1); /* padding size */
  18169. let ch = p1 && (p1[0] + '') === '0' ? '0' : ' '; /* isnull? */
  18170. while (val.length < size)
  18171. val = p0 !== undefined ? val + ch : ch + val; /* isminus? */
  18172. return val;
  18173. }
  18174. let regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;
  18175. return str.replace(regex, callback);
  18176. }
  18177. /**
  18178. *
  18179. * @param append The new string to append.
  18180. * @param args Argumets values to be formated.
  18181. */
  18182. format(append, ...args) {
  18183. this.buffer += Formatter.form(append, args);
  18184. }
  18185. /**
  18186. * Returns the Formatter string value.
  18187. */
  18188. toString() {
  18189. return this.buffer;
  18190. }
  18191. }
  18192. /*
  18193. * Copyright 2013 ZXing authors
  18194. *
  18195. * Licensed under the Apache License, Version 2.0 (the "License");
  18196. * you may not use this file except in compliance with the License.
  18197. * You may obtain a copy of the License at
  18198. *
  18199. * http://www.apache.org/licenses/LICENSE-2.0
  18200. *
  18201. * Unless required by applicable law or agreed to in writing, software
  18202. * distributed under the License is distributed on an "AS IS" BASIS,
  18203. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18204. * See the License for the specific language governing permissions and
  18205. * limitations under the License.
  18206. */
  18207. /**
  18208. * @author Guenther Grau
  18209. */
  18210. class DetectionResultColumn {
  18211. constructor(boundingBox) {
  18212. this.boundingBox = new BoundingBox(boundingBox);
  18213. // this.codewords = new Codeword[boundingBox.getMaxY() - boundingBox.getMinY() + 1];
  18214. this.codewords = new Array(boundingBox.getMaxY() - boundingBox.getMinY() + 1);
  18215. }
  18216. /*final*/ getCodewordNearby(imageRow) {
  18217. let codeword = this.getCodeword(imageRow);
  18218. if (codeword != null) {
  18219. return codeword;
  18220. }
  18221. for (let i = 1; i < DetectionResultColumn.MAX_NEARBY_DISTANCE; i++) {
  18222. let nearImageRow = this.imageRowToCodewordIndex(imageRow) - i;
  18223. if (nearImageRow >= 0) {
  18224. codeword = this.codewords[nearImageRow];
  18225. if (codeword != null) {
  18226. return codeword;
  18227. }
  18228. }
  18229. nearImageRow = this.imageRowToCodewordIndex(imageRow) + i;
  18230. if (nearImageRow < this.codewords.length) {
  18231. codeword = this.codewords[nearImageRow];
  18232. if (codeword != null) {
  18233. return codeword;
  18234. }
  18235. }
  18236. }
  18237. return null;
  18238. }
  18239. /*final int*/ imageRowToCodewordIndex(imageRow) {
  18240. return imageRow - this.boundingBox.getMinY();
  18241. }
  18242. /*final void*/ setCodeword(imageRow, codeword) {
  18243. this.codewords[this.imageRowToCodewordIndex(imageRow)] = codeword;
  18244. }
  18245. /*final*/ getCodeword(imageRow) {
  18246. return this.codewords[this.imageRowToCodewordIndex(imageRow)];
  18247. }
  18248. /*final*/ getBoundingBox() {
  18249. return this.boundingBox;
  18250. }
  18251. /*final*/ getCodewords() {
  18252. return this.codewords;
  18253. }
  18254. // @Override
  18255. toString() {
  18256. const formatter = new Formatter();
  18257. let row = 0;
  18258. for (const codeword of this.codewords) {
  18259. if (codeword == null) {
  18260. formatter.format('%3d: | %n', row++);
  18261. continue;
  18262. }
  18263. formatter.format('%3d: %3d|%3d%n', row++, codeword.getRowNumber(), codeword.getValue());
  18264. }
  18265. return formatter.toString();
  18266. }
  18267. }
  18268. DetectionResultColumn.MAX_NEARBY_DISTANCE = 5;
  18269. /*
  18270. * Copyright 2013 ZXing authors
  18271. *
  18272. * Licensed under the Apache License, Version 2.0 (the "License");
  18273. * you may not use this file except in compliance with the License.
  18274. * You may obtain a copy of the License at
  18275. *
  18276. * http://www.apache.org/licenses/LICENSE-2.0
  18277. *
  18278. * Unless required by applicable law or agreed to in writing, software
  18279. * distributed under the License is distributed on an "AS IS" BASIS,
  18280. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18281. * See the License for the specific language governing permissions and
  18282. * limitations under the License.
  18283. */
  18284. // import java.util.ArrayList;
  18285. // import java.util.Collection;
  18286. // import java.util.HashMap;
  18287. // import java.util.Map;
  18288. // import java.util.Map.Entry;
  18289. /**
  18290. * @author Guenther Grau
  18291. */
  18292. /*final*/ class BarcodeValue {
  18293. constructor() {
  18294. this.values = new Map();
  18295. }
  18296. /**
  18297. * Add an occurrence of a value
  18298. */
  18299. setValue(value) {
  18300. value = Math.trunc(value);
  18301. let confidence = this.values.get(value);
  18302. if (confidence == null) {
  18303. confidence = 0;
  18304. }
  18305. confidence++;
  18306. this.values.set(value, confidence);
  18307. }
  18308. /**
  18309. * Determines the maximum occurrence of a set value and returns all values which were set with this occurrence.
  18310. * @return an array of int, containing the values with the highest occurrence, or null, if no value was set
  18311. */
  18312. getValue() {
  18313. let maxConfidence = -1;
  18314. let result = new Array();
  18315. for (const [key, value] of this.values.entries()) {
  18316. const entry = {
  18317. getKey: () => key,
  18318. getValue: () => value,
  18319. };
  18320. if (entry.getValue() > maxConfidence) {
  18321. maxConfidence = entry.getValue();
  18322. result = [];
  18323. result.push(entry.getKey());
  18324. }
  18325. else if (entry.getValue() === maxConfidence) {
  18326. result.push(entry.getKey());
  18327. }
  18328. }
  18329. return PDF417Common.toIntArray(result);
  18330. }
  18331. getConfidence(value) {
  18332. return this.values.get(value);
  18333. }
  18334. }
  18335. /*
  18336. * Copyright 2013 ZXing authors
  18337. *
  18338. * Licensed under the Apache License, Version 2.0 (the "License");
  18339. * you may not use this file except in compliance with the License.
  18340. * You may obtain a copy of the License at
  18341. *
  18342. * http://www.apache.org/licenses/LICENSE-2.0
  18343. *
  18344. * Unless required by applicable law or agreed to in writing, software
  18345. * distributed under the License is distributed on an "AS IS" BASIS,
  18346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18347. * See the License for the specific language governing permissions and
  18348. * limitations under the License.
  18349. */
  18350. /**
  18351. * @author Guenther Grau
  18352. */
  18353. /*final*/ class DetectionResultRowIndicatorColumn extends DetectionResultColumn {
  18354. constructor(boundingBox, isLeft) {
  18355. super(boundingBox);
  18356. this._isLeft = isLeft;
  18357. }
  18358. setRowNumbers() {
  18359. for (let codeword /*Codeword*/ of this.getCodewords()) {
  18360. if (codeword != null) {
  18361. codeword.setRowNumberAsRowIndicatorColumn();
  18362. }
  18363. }
  18364. }
  18365. // TODO implement properly
  18366. // TODO maybe we should add missing codewords to store the correct row number to make
  18367. // finding row numbers for other columns easier
  18368. // use row height count to make detection of invalid row numbers more reliable
  18369. adjustCompleteIndicatorColumnRowNumbers(barcodeMetadata) {
  18370. let codewords = this.getCodewords();
  18371. this.setRowNumbers();
  18372. this.removeIncorrectCodewords(codewords, barcodeMetadata);
  18373. let boundingBox = this.getBoundingBox();
  18374. let top = this._isLeft ? boundingBox.getTopLeft() : boundingBox.getTopRight();
  18375. let bottom = this._isLeft ? boundingBox.getBottomLeft() : boundingBox.getBottomRight();
  18376. let firstRow = this.imageRowToCodewordIndex(Math.trunc(top.getY()));
  18377. let lastRow = this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));
  18378. // We need to be careful using the average row height. Barcode could be skewed so that we have smaller and
  18379. // taller rows
  18380. // float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();
  18381. let barcodeRow = -1;
  18382. let maxRowHeight = 1;
  18383. let currentRowHeight = 0;
  18384. for (let codewordsRow /*int*/ = firstRow; codewordsRow < lastRow; codewordsRow++) {
  18385. if (codewords[codewordsRow] == null) {
  18386. continue;
  18387. }
  18388. let codeword = codewords[codewordsRow];
  18389. // float expectedRowNumber = (codewordsRow - firstRow) / averageRowHeight;
  18390. // if (Math.abs(codeword.getRowNumber() - expectedRowNumber) > 2) {
  18391. // SimpleLog.log(LEVEL.WARNING,
  18392. // "Removing codeword, rowNumberSkew too high, codeword[" + codewordsRow + "]: Expected Row: " +
  18393. // expectedRowNumber + ", RealRow: " + codeword.getRowNumber() + ", value: " + codeword.getValue());
  18394. // codewords[codewordsRow] = null;
  18395. // }
  18396. let rowDifference = codeword.getRowNumber() - barcodeRow;
  18397. // TODO improve handling with case where first row indicator doesn't start with 0
  18398. if (rowDifference === 0) {
  18399. currentRowHeight++;
  18400. }
  18401. else if (rowDifference === 1) {
  18402. maxRowHeight = Math.max(maxRowHeight, currentRowHeight);
  18403. currentRowHeight = 1;
  18404. barcodeRow = codeword.getRowNumber();
  18405. }
  18406. else if (rowDifference < 0 ||
  18407. codeword.getRowNumber() >= barcodeMetadata.getRowCount() ||
  18408. rowDifference > codewordsRow) {
  18409. codewords[codewordsRow] = null;
  18410. }
  18411. else {
  18412. let checkedRows;
  18413. if (maxRowHeight > 2) {
  18414. checkedRows = (maxRowHeight - 2) * rowDifference;
  18415. }
  18416. else {
  18417. checkedRows = rowDifference;
  18418. }
  18419. let closePreviousCodewordFound = checkedRows >= codewordsRow;
  18420. for (let i /*int*/ = 1; i <= checkedRows && !closePreviousCodewordFound; i++) {
  18421. // there must be (height * rowDifference) number of codewords missing. For now we assume height = 1.
  18422. // This should hopefully get rid of most problems already.
  18423. closePreviousCodewordFound = codewords[codewordsRow - i] != null;
  18424. }
  18425. if (closePreviousCodewordFound) {
  18426. codewords[codewordsRow] = null;
  18427. }
  18428. else {
  18429. barcodeRow = codeword.getRowNumber();
  18430. currentRowHeight = 1;
  18431. }
  18432. }
  18433. }
  18434. // return (int) (averageRowHeight + 0.5);
  18435. }
  18436. getRowHeights() {
  18437. let barcodeMetadata = this.getBarcodeMetadata();
  18438. if (barcodeMetadata == null) {
  18439. return null;
  18440. }
  18441. this.adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata);
  18442. let result = new Int32Array(barcodeMetadata.getRowCount());
  18443. for (let codeword /*Codeword*/ of this.getCodewords()) {
  18444. if (codeword != null) {
  18445. let rowNumber = codeword.getRowNumber();
  18446. if (rowNumber >= result.length) {
  18447. // We have more rows than the barcode metadata allows for, ignore them.
  18448. continue;
  18449. }
  18450. result[rowNumber]++;
  18451. } // else throw exception?
  18452. }
  18453. return result;
  18454. }
  18455. // TODO maybe we should add missing codewords to store the correct row number to make
  18456. // finding row numbers for other columns easier
  18457. // use row height count to make detection of invalid row numbers more reliable
  18458. adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata) {
  18459. let boundingBox = this.getBoundingBox();
  18460. let top = this._isLeft ? boundingBox.getTopLeft() : boundingBox.getTopRight();
  18461. let bottom = this._isLeft ? boundingBox.getBottomLeft() : boundingBox.getBottomRight();
  18462. let firstRow = this.imageRowToCodewordIndex(Math.trunc(top.getY()));
  18463. let lastRow = this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));
  18464. // float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();
  18465. let codewords = this.getCodewords();
  18466. let barcodeRow = -1;
  18467. for (let codewordsRow /*int*/ = firstRow; codewordsRow < lastRow; codewordsRow++) {
  18468. if (codewords[codewordsRow] == null) {
  18469. continue;
  18470. }
  18471. let codeword = codewords[codewordsRow];
  18472. codeword.setRowNumberAsRowIndicatorColumn();
  18473. let rowDifference = codeword.getRowNumber() - barcodeRow;
  18474. // TODO improve handling with case where first row indicator doesn't start with 0
  18475. if (rowDifference === 0) ;
  18476. else if (rowDifference === 1) {
  18477. barcodeRow = codeword.getRowNumber();
  18478. }
  18479. else if (codeword.getRowNumber() >= barcodeMetadata.getRowCount()) {
  18480. codewords[codewordsRow] = null;
  18481. }
  18482. else {
  18483. barcodeRow = codeword.getRowNumber();
  18484. }
  18485. }
  18486. // return (int) (averageRowHeight + 0.5);
  18487. }
  18488. getBarcodeMetadata() {
  18489. let codewords = this.getCodewords();
  18490. let barcodeColumnCount = new BarcodeValue();
  18491. let barcodeRowCountUpperPart = new BarcodeValue();
  18492. let barcodeRowCountLowerPart = new BarcodeValue();
  18493. let barcodeECLevel = new BarcodeValue();
  18494. for (let codeword /*Codeword*/ of codewords) {
  18495. if (codeword == null) {
  18496. continue;
  18497. }
  18498. codeword.setRowNumberAsRowIndicatorColumn();
  18499. let rowIndicatorValue = codeword.getValue() % 30;
  18500. let codewordRowNumber = codeword.getRowNumber();
  18501. if (!this._isLeft) {
  18502. codewordRowNumber += 2;
  18503. }
  18504. switch (codewordRowNumber % 3) {
  18505. case 0:
  18506. barcodeRowCountUpperPart.setValue(rowIndicatorValue * 3 + 1);
  18507. break;
  18508. case 1:
  18509. barcodeECLevel.setValue(rowIndicatorValue / 3);
  18510. barcodeRowCountLowerPart.setValue(rowIndicatorValue % 3);
  18511. break;
  18512. case 2:
  18513. barcodeColumnCount.setValue(rowIndicatorValue + 1);
  18514. break;
  18515. }
  18516. }
  18517. // Maybe we should check if we have ambiguous values?
  18518. if ((barcodeColumnCount.getValue().length === 0) ||
  18519. (barcodeRowCountUpperPart.getValue().length === 0) ||
  18520. (barcodeRowCountLowerPart.getValue().length === 0) ||
  18521. (barcodeECLevel.getValue().length === 0) ||
  18522. barcodeColumnCount.getValue()[0] < 1 ||
  18523. barcodeRowCountUpperPart.getValue()[0] + barcodeRowCountLowerPart.getValue()[0] < PDF417Common.MIN_ROWS_IN_BARCODE ||
  18524. barcodeRowCountUpperPart.getValue()[0] + barcodeRowCountLowerPart.getValue()[0] > PDF417Common.MAX_ROWS_IN_BARCODE) {
  18525. return null;
  18526. }
  18527. let barcodeMetadata = new BarcodeMetadata(barcodeColumnCount.getValue()[0], barcodeRowCountUpperPart.getValue()[0], barcodeRowCountLowerPart.getValue()[0], barcodeECLevel.getValue()[0]);
  18528. this.removeIncorrectCodewords(codewords, barcodeMetadata);
  18529. return barcodeMetadata;
  18530. }
  18531. removeIncorrectCodewords(codewords, barcodeMetadata) {
  18532. // Remove codewords which do not match the metadata
  18533. // TODO Maybe we should keep the incorrect codewords for the start and end positions?
  18534. for (let codewordRow /*int*/ = 0; codewordRow < codewords.length; codewordRow++) {
  18535. let codeword = codewords[codewordRow];
  18536. if (codewords[codewordRow] == null) {
  18537. continue;
  18538. }
  18539. let rowIndicatorValue = codeword.getValue() % 30;
  18540. let codewordRowNumber = codeword.getRowNumber();
  18541. if (codewordRowNumber > barcodeMetadata.getRowCount()) {
  18542. codewords[codewordRow] = null;
  18543. continue;
  18544. }
  18545. if (!this._isLeft) {
  18546. codewordRowNumber += 2;
  18547. }
  18548. switch (codewordRowNumber % 3) {
  18549. case 0:
  18550. if (rowIndicatorValue * 3 + 1 !== barcodeMetadata.getRowCountUpperPart()) {
  18551. codewords[codewordRow] = null;
  18552. }
  18553. break;
  18554. case 1:
  18555. if (Math.trunc(rowIndicatorValue / 3) !== barcodeMetadata.getErrorCorrectionLevel() ||
  18556. rowIndicatorValue % 3 !== barcodeMetadata.getRowCountLowerPart()) {
  18557. codewords[codewordRow] = null;
  18558. }
  18559. break;
  18560. case 2:
  18561. if (rowIndicatorValue + 1 !== barcodeMetadata.getColumnCount()) {
  18562. codewords[codewordRow] = null;
  18563. }
  18564. break;
  18565. }
  18566. }
  18567. }
  18568. isLeft() {
  18569. return this._isLeft;
  18570. }
  18571. // @Override
  18572. toString() {
  18573. return 'IsLeft: ' + this._isLeft + '\n' + super.toString();
  18574. }
  18575. }
  18576. /*
  18577. * Copyright 2013 ZXing authors
  18578. *
  18579. * Licensed under the Apache License, Version 2.0 (the "License");
  18580. * you may not use this file except in compliance with the License.
  18581. * You may obtain a copy of the License at
  18582. *
  18583. * http://www.apache.org/licenses/LICENSE-2.0
  18584. *
  18585. * Unless required by applicable law or agreed to in writing, software
  18586. * distributed under the License is distributed on an "AS IS" BASIS,
  18587. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18588. * See the License for the specific language governing permissions and
  18589. * limitations under the License.
  18590. */
  18591. /**
  18592. * @author Guenther Grau
  18593. */
  18594. /*final*/ class DetectionResult {
  18595. constructor(barcodeMetadata, boundingBox) {
  18596. /*final*/ this.ADJUST_ROW_NUMBER_SKIP = 2;
  18597. this.barcodeMetadata = barcodeMetadata;
  18598. this.barcodeColumnCount = barcodeMetadata.getColumnCount();
  18599. this.boundingBox = boundingBox;
  18600. // this.detectionResultColumns = new DetectionResultColumn[this.barcodeColumnCount + 2];
  18601. this.detectionResultColumns = new Array(this.barcodeColumnCount + 2);
  18602. }
  18603. getDetectionResultColumns() {
  18604. this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]);
  18605. this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount + 1]);
  18606. let unadjustedCodewordCount = PDF417Common.MAX_CODEWORDS_IN_BARCODE;
  18607. let previousUnadjustedCount;
  18608. do {
  18609. previousUnadjustedCount = unadjustedCodewordCount;
  18610. unadjustedCodewordCount = this.adjustRowNumbersAndGetCount();
  18611. } while (unadjustedCodewordCount > 0 && unadjustedCodewordCount < previousUnadjustedCount);
  18612. return this.detectionResultColumns;
  18613. }
  18614. adjustIndicatorColumnRowNumbers(detectionResultColumn) {
  18615. if (detectionResultColumn != null) {
  18616. detectionResultColumn
  18617. .adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata);
  18618. }
  18619. }
  18620. // TODO ensure that no detected codewords with unknown row number are left
  18621. // we should be able to estimate the row height and use it as a hint for the row number
  18622. // we should also fill the rows top to bottom and bottom to top
  18623. /**
  18624. * @return number of codewords which don't have a valid row number. Note that the count is not accurate as codewords
  18625. * will be counted several times. It just serves as an indicator to see when we can stop adjusting row numbers
  18626. */
  18627. adjustRowNumbersAndGetCount() {
  18628. let unadjustedCount = this.adjustRowNumbersByRow();
  18629. if (unadjustedCount === 0) {
  18630. return 0;
  18631. }
  18632. for (let barcodeColumn /*int*/ = 1; barcodeColumn < this.barcodeColumnCount + 1; barcodeColumn++) {
  18633. let codewords = this.detectionResultColumns[barcodeColumn].getCodewords();
  18634. for (let codewordsRow /*int*/ = 0; codewordsRow < codewords.length; codewordsRow++) {
  18635. if (codewords[codewordsRow] == null) {
  18636. continue;
  18637. }
  18638. if (!codewords[codewordsRow].hasValidRowNumber()) {
  18639. this.adjustRowNumbers(barcodeColumn, codewordsRow, codewords);
  18640. }
  18641. }
  18642. }
  18643. return unadjustedCount;
  18644. }
  18645. adjustRowNumbersByRow() {
  18646. this.adjustRowNumbersFromBothRI();
  18647. // TODO we should only do full row adjustments if row numbers of left and right row indicator column match.
  18648. // Maybe it's even better to calculated the height (rows: d) and divide it by the number of barcode
  18649. // rows. This, together with the LRI and RRI row numbers should allow us to get a good estimate where a row
  18650. // number starts and ends.
  18651. let unadjustedCount = this.adjustRowNumbersFromLRI();
  18652. return unadjustedCount + this.adjustRowNumbersFromRRI();
  18653. }
  18654. adjustRowNumbersFromBothRI() {
  18655. if (this.detectionResultColumns[0] == null || this.detectionResultColumns[this.barcodeColumnCount + 1] == null) {
  18656. return;
  18657. }
  18658. let LRIcodewords = this.detectionResultColumns[0].getCodewords();
  18659. let RRIcodewords = this.detectionResultColumns[this.barcodeColumnCount + 1].getCodewords();
  18660. for (let codewordsRow /*int*/ = 0; codewordsRow < LRIcodewords.length; codewordsRow++) {
  18661. if (LRIcodewords[codewordsRow] != null &&
  18662. RRIcodewords[codewordsRow] != null &&
  18663. LRIcodewords[codewordsRow].getRowNumber() === RRIcodewords[codewordsRow].getRowNumber()) {
  18664. for (let barcodeColumn /*int*/ = 1; barcodeColumn <= this.barcodeColumnCount; barcodeColumn++) {
  18665. let codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];
  18666. if (codeword == null) {
  18667. continue;
  18668. }
  18669. codeword.setRowNumber(LRIcodewords[codewordsRow].getRowNumber());
  18670. if (!codeword.hasValidRowNumber()) {
  18671. this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow] = null;
  18672. }
  18673. }
  18674. }
  18675. }
  18676. }
  18677. adjustRowNumbersFromRRI() {
  18678. if (this.detectionResultColumns[this.barcodeColumnCount + 1] == null) {
  18679. return 0;
  18680. }
  18681. let unadjustedCount = 0;
  18682. let codewords = this.detectionResultColumns[this.barcodeColumnCount + 1].getCodewords();
  18683. for (let codewordsRow /*int*/ = 0; codewordsRow < codewords.length; codewordsRow++) {
  18684. if (codewords[codewordsRow] == null) {
  18685. continue;
  18686. }
  18687. let rowIndicatorRowNumber = codewords[codewordsRow].getRowNumber();
  18688. let invalidRowCounts = 0;
  18689. for (let barcodeColumn /*int*/ = this.barcodeColumnCount + 1; barcodeColumn > 0 && invalidRowCounts < this.ADJUST_ROW_NUMBER_SKIP; barcodeColumn--) {
  18690. let codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];
  18691. if (codeword != null) {
  18692. invalidRowCounts = DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);
  18693. if (!codeword.hasValidRowNumber()) {
  18694. unadjustedCount++;
  18695. }
  18696. }
  18697. }
  18698. }
  18699. return unadjustedCount;
  18700. }
  18701. adjustRowNumbersFromLRI() {
  18702. if (this.detectionResultColumns[0] == null) {
  18703. return 0;
  18704. }
  18705. let unadjustedCount = 0;
  18706. let codewords = this.detectionResultColumns[0].getCodewords();
  18707. for (let codewordsRow /*int*/ = 0; codewordsRow < codewords.length; codewordsRow++) {
  18708. if (codewords[codewordsRow] == null) {
  18709. continue;
  18710. }
  18711. let rowIndicatorRowNumber = codewords[codewordsRow].getRowNumber();
  18712. let invalidRowCounts = 0;
  18713. for (let barcodeColumn /*int*/ = 1; barcodeColumn < this.barcodeColumnCount + 1 && invalidRowCounts < this.ADJUST_ROW_NUMBER_SKIP; barcodeColumn++) {
  18714. let codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];
  18715. if (codeword != null) {
  18716. invalidRowCounts = DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);
  18717. if (!codeword.hasValidRowNumber()) {
  18718. unadjustedCount++;
  18719. }
  18720. }
  18721. }
  18722. }
  18723. return unadjustedCount;
  18724. }
  18725. static adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword) {
  18726. if (codeword == null) {
  18727. return invalidRowCounts;
  18728. }
  18729. if (!codeword.hasValidRowNumber()) {
  18730. if (codeword.isValidRowNumber(rowIndicatorRowNumber)) {
  18731. codeword.setRowNumber(rowIndicatorRowNumber);
  18732. invalidRowCounts = 0;
  18733. }
  18734. else {
  18735. ++invalidRowCounts;
  18736. }
  18737. }
  18738. return invalidRowCounts;
  18739. }
  18740. adjustRowNumbers(barcodeColumn, codewordsRow, codewords) {
  18741. if (this.detectionResultColumns[barcodeColumn - 1] == null) {
  18742. return;
  18743. }
  18744. let codeword = codewords[codewordsRow];
  18745. let previousColumnCodewords = this.detectionResultColumns[barcodeColumn - 1].getCodewords();
  18746. let nextColumnCodewords = previousColumnCodewords;
  18747. if (this.detectionResultColumns[barcodeColumn + 1] != null) {
  18748. nextColumnCodewords = this.detectionResultColumns[barcodeColumn + 1].getCodewords();
  18749. }
  18750. // let otherCodewords: Codeword[] = new Codeword[14];
  18751. let otherCodewords = new Array(14);
  18752. otherCodewords[2] = previousColumnCodewords[codewordsRow];
  18753. otherCodewords[3] = nextColumnCodewords[codewordsRow];
  18754. if (codewordsRow > 0) {
  18755. otherCodewords[0] = codewords[codewordsRow - 1];
  18756. otherCodewords[4] = previousColumnCodewords[codewordsRow - 1];
  18757. otherCodewords[5] = nextColumnCodewords[codewordsRow - 1];
  18758. }
  18759. if (codewordsRow > 1) {
  18760. otherCodewords[8] = codewords[codewordsRow - 2];
  18761. otherCodewords[10] = previousColumnCodewords[codewordsRow - 2];
  18762. otherCodewords[11] = nextColumnCodewords[codewordsRow - 2];
  18763. }
  18764. if (codewordsRow < codewords.length - 1) {
  18765. otherCodewords[1] = codewords[codewordsRow + 1];
  18766. otherCodewords[6] = previousColumnCodewords[codewordsRow + 1];
  18767. otherCodewords[7] = nextColumnCodewords[codewordsRow + 1];
  18768. }
  18769. if (codewordsRow < codewords.length - 2) {
  18770. otherCodewords[9] = codewords[codewordsRow + 2];
  18771. otherCodewords[12] = previousColumnCodewords[codewordsRow + 2];
  18772. otherCodewords[13] = nextColumnCodewords[codewordsRow + 2];
  18773. }
  18774. for (let otherCodeword of otherCodewords) {
  18775. if (DetectionResult.adjustRowNumber(codeword, otherCodeword)) {
  18776. return;
  18777. }
  18778. }
  18779. }
  18780. /**
  18781. * @return true, if row number was adjusted, false otherwise
  18782. */
  18783. static adjustRowNumber(codeword, otherCodeword) {
  18784. if (otherCodeword == null) {
  18785. return false;
  18786. }
  18787. if (otherCodeword.hasValidRowNumber() && otherCodeword.getBucket() === codeword.getBucket()) {
  18788. codeword.setRowNumber(otherCodeword.getRowNumber());
  18789. return true;
  18790. }
  18791. return false;
  18792. }
  18793. getBarcodeColumnCount() {
  18794. return this.barcodeColumnCount;
  18795. }
  18796. getBarcodeRowCount() {
  18797. return this.barcodeMetadata.getRowCount();
  18798. }
  18799. getBarcodeECLevel() {
  18800. return this.barcodeMetadata.getErrorCorrectionLevel();
  18801. }
  18802. setBoundingBox(boundingBox) {
  18803. this.boundingBox = boundingBox;
  18804. }
  18805. getBoundingBox() {
  18806. return this.boundingBox;
  18807. }
  18808. setDetectionResultColumn(barcodeColumn, detectionResultColumn) {
  18809. this.detectionResultColumns[barcodeColumn] = detectionResultColumn;
  18810. }
  18811. getDetectionResultColumn(barcodeColumn) {
  18812. return this.detectionResultColumns[barcodeColumn];
  18813. }
  18814. // @Override
  18815. toString() {
  18816. let rowIndicatorColumn = this.detectionResultColumns[0];
  18817. if (rowIndicatorColumn == null) {
  18818. rowIndicatorColumn = this.detectionResultColumns[this.barcodeColumnCount + 1];
  18819. }
  18820. // try (
  18821. let formatter = new Formatter();
  18822. // ) {
  18823. for (let codewordsRow /*int*/ = 0; codewordsRow < rowIndicatorColumn.getCodewords().length; codewordsRow++) {
  18824. formatter.format('CW %3d:', codewordsRow);
  18825. for (let barcodeColumn /*int*/ = 0; barcodeColumn < this.barcodeColumnCount + 2; barcodeColumn++) {
  18826. if (this.detectionResultColumns[barcodeColumn] == null) {
  18827. formatter.format(' | ');
  18828. continue;
  18829. }
  18830. let codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];
  18831. if (codeword == null) {
  18832. formatter.format(' | ');
  18833. continue;
  18834. }
  18835. formatter.format(' %3d|%3d', codeword.getRowNumber(), codeword.getValue());
  18836. }
  18837. formatter.format('%n');
  18838. }
  18839. return formatter.toString();
  18840. // }
  18841. }
  18842. }
  18843. /*
  18844. * Copyright 2013 ZXing authors
  18845. *
  18846. * Licensed under the Apache License, Version 2.0 (the "License");
  18847. * you may not use this file except in compliance with the License.
  18848. * You may obtain a copy of the License at
  18849. *
  18850. * http://www.apache.org/licenses/LICENSE-2.0
  18851. *
  18852. * Unless required by applicable law or agreed to in writing, software
  18853. * distributed under the License is distributed on an "AS IS" BASIS,
  18854. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18855. * See the License for the specific language governing permissions and
  18856. * limitations under the License.
  18857. */
  18858. // package com.google.zxing.pdf417.decoder;
  18859. /**
  18860. * @author Guenther Grau
  18861. */
  18862. /*final*/ class Codeword {
  18863. constructor(startX, endX, bucket, value) {
  18864. this.rowNumber = Codeword.BARCODE_ROW_UNKNOWN;
  18865. this.startX = Math.trunc(startX);
  18866. this.endX = Math.trunc(endX);
  18867. this.bucket = Math.trunc(bucket);
  18868. this.value = Math.trunc(value);
  18869. }
  18870. hasValidRowNumber() {
  18871. return this.isValidRowNumber(this.rowNumber);
  18872. }
  18873. isValidRowNumber(rowNumber) {
  18874. return rowNumber !== Codeword.BARCODE_ROW_UNKNOWN && this.bucket === (rowNumber % 3) * 3;
  18875. }
  18876. setRowNumberAsRowIndicatorColumn() {
  18877. this.rowNumber = Math.trunc((Math.trunc(this.value / 30)) * 3 + Math.trunc(this.bucket / 3));
  18878. }
  18879. getWidth() {
  18880. return this.endX - this.startX;
  18881. }
  18882. getStartX() {
  18883. return this.startX;
  18884. }
  18885. getEndX() {
  18886. return this.endX;
  18887. }
  18888. getBucket() {
  18889. return this.bucket;
  18890. }
  18891. getValue() {
  18892. return this.value;
  18893. }
  18894. getRowNumber() {
  18895. return this.rowNumber;
  18896. }
  18897. setRowNumber(rowNumber) {
  18898. this.rowNumber = rowNumber;
  18899. }
  18900. // @Override
  18901. toString() {
  18902. return this.rowNumber + '|' + this.value;
  18903. }
  18904. }
  18905. Codeword.BARCODE_ROW_UNKNOWN = -1;
  18906. /*
  18907. * Copyright 2013 ZXing authors
  18908. *
  18909. * Licensed under the Apache License, Version 2.0 (the "License");
  18910. * you may not use this file except in compliance with the License.
  18911. * You may obtain a copy of the License at
  18912. *
  18913. * http://www.apache.org/licenses/LICENSE-2.0
  18914. *
  18915. * Unless required by applicable law or agreed to in writing, software
  18916. * distributed under the License is distributed on an "AS IS" BASIS,
  18917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18918. * See the License for the specific language governing permissions and
  18919. * limitations under the License.
  18920. */
  18921. /**
  18922. * @author Guenther Grau
  18923. * @author creatale GmbH (christoph.schulz@creatale.de)
  18924. */
  18925. /*final*/ class PDF417CodewordDecoder {
  18926. /* @note
  18927. * this action have to be performed before first use of class
  18928. * - static constructor
  18929. * working with 32bit float (based from Java logic)
  18930. */
  18931. static initialize() {
  18932. // Pre-computes the symbol ratio table.
  18933. for ( /*int*/let i = 0; i < PDF417Common.SYMBOL_TABLE.length; i++) {
  18934. let currentSymbol = PDF417Common.SYMBOL_TABLE[i];
  18935. let currentBit = currentSymbol & 0x1;
  18936. for ( /*int*/let j = 0; j < PDF417Common.BARS_IN_MODULE; j++) {
  18937. let size = 0.0;
  18938. while ((currentSymbol & 0x1) === currentBit) {
  18939. size += 1.0;
  18940. currentSymbol >>= 1;
  18941. }
  18942. currentBit = currentSymbol & 0x1;
  18943. if (!PDF417CodewordDecoder.RATIOS_TABLE[i]) {
  18944. PDF417CodewordDecoder.RATIOS_TABLE[i] = new Array(PDF417Common.BARS_IN_MODULE);
  18945. }
  18946. PDF417CodewordDecoder.RATIOS_TABLE[i][PDF417Common.BARS_IN_MODULE - j - 1] = Math.fround(size / PDF417Common.MODULES_IN_CODEWORD);
  18947. }
  18948. }
  18949. this.bSymbolTableReady = true;
  18950. }
  18951. static getDecodedValue(moduleBitCount) {
  18952. let decodedValue = PDF417CodewordDecoder.getDecodedCodewordValue(PDF417CodewordDecoder.sampleBitCounts(moduleBitCount));
  18953. if (decodedValue !== -1) {
  18954. return decodedValue;
  18955. }
  18956. return PDF417CodewordDecoder.getClosestDecodedValue(moduleBitCount);
  18957. }
  18958. static sampleBitCounts(moduleBitCount) {
  18959. let bitCountSum = MathUtils.sum(moduleBitCount);
  18960. let result = new Int32Array(PDF417Common.BARS_IN_MODULE);
  18961. let bitCountIndex = 0;
  18962. let sumPreviousBits = 0;
  18963. for ( /*int*/let i = 0; i < PDF417Common.MODULES_IN_CODEWORD; i++) {
  18964. let sampleIndex = bitCountSum / (2 * PDF417Common.MODULES_IN_CODEWORD) +
  18965. (i * bitCountSum) / PDF417Common.MODULES_IN_CODEWORD;
  18966. if (sumPreviousBits + moduleBitCount[bitCountIndex] <= sampleIndex) {
  18967. sumPreviousBits += moduleBitCount[bitCountIndex];
  18968. bitCountIndex++;
  18969. }
  18970. result[bitCountIndex]++;
  18971. }
  18972. return result;
  18973. }
  18974. static getDecodedCodewordValue(moduleBitCount) {
  18975. let decodedValue = PDF417CodewordDecoder.getBitValue(moduleBitCount);
  18976. return PDF417Common.getCodeword(decodedValue) === -1 ? -1 : decodedValue;
  18977. }
  18978. static getBitValue(moduleBitCount) {
  18979. let result = /*long*/ 0;
  18980. for (let /*int*/ i = 0; i < moduleBitCount.length; i++) {
  18981. for ( /*int*/let bit = 0; bit < moduleBitCount[i]; bit++) {
  18982. result = (result << 1) | (i % 2 === 0 ? 1 : 0);
  18983. }
  18984. }
  18985. return Math.trunc(result);
  18986. }
  18987. // working with 32bit float (as in Java)
  18988. static getClosestDecodedValue(moduleBitCount) {
  18989. let bitCountSum = MathUtils.sum(moduleBitCount);
  18990. let bitCountRatios = new Array(PDF417Common.BARS_IN_MODULE);
  18991. if (bitCountSum > 1) {
  18992. for (let /*int*/ i = 0; i < bitCountRatios.length; i++) {
  18993. bitCountRatios[i] = Math.fround(moduleBitCount[i] / bitCountSum);
  18994. }
  18995. }
  18996. let bestMatchError = Float.MAX_VALUE;
  18997. let bestMatch = -1;
  18998. if (!this.bSymbolTableReady) {
  18999. PDF417CodewordDecoder.initialize();
  19000. }
  19001. for ( /*int*/let j = 0; j < PDF417CodewordDecoder.RATIOS_TABLE.length; j++) {
  19002. let error = 0.0;
  19003. let ratioTableRow = PDF417CodewordDecoder.RATIOS_TABLE[j];
  19004. for ( /*int*/let k = 0; k < PDF417Common.BARS_IN_MODULE; k++) {
  19005. let diff = Math.fround(ratioTableRow[k] - bitCountRatios[k]);
  19006. error += Math.fround(diff * diff);
  19007. if (error >= bestMatchError) {
  19008. break;
  19009. }
  19010. }
  19011. if (error < bestMatchError) {
  19012. bestMatchError = error;
  19013. bestMatch = PDF417Common.SYMBOL_TABLE[j];
  19014. }
  19015. }
  19016. return bestMatch;
  19017. }
  19018. }
  19019. // flag that the table is ready for use
  19020. PDF417CodewordDecoder.bSymbolTableReady = false;
  19021. PDF417CodewordDecoder.RATIOS_TABLE = new Array(PDF417Common.SYMBOL_TABLE.length).map(x => x = new Array(PDF417Common.BARS_IN_MODULE));
  19022. /*
  19023. * Copyright 2013 ZXing authors
  19024. *
  19025. * Licensed under the Apache License, Version 2.0 (the "License");
  19026. * you may not use this file except in compliance with the License.
  19027. * You may obtain a copy of the License at
  19028. *
  19029. * http://www.apache.org/licenses/LICENSE-2.0
  19030. *
  19031. * Unless required by applicable law or agreed to in writing, software
  19032. * distributed under the License is distributed on an "AS IS" BASIS,
  19033. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19034. * See the License for the specific language governing permissions and
  19035. * limitations under the License.
  19036. */
  19037. // package com.google.zxing.pdf417;
  19038. /**
  19039. * @author Guenther Grau
  19040. */
  19041. /*public final*/ class PDF417ResultMetadata {
  19042. constructor() {
  19043. this.segmentCount = -1;
  19044. this.fileSize = -1;
  19045. this.timestamp = -1;
  19046. this.checksum = -1;
  19047. }
  19048. /**
  19049. * The Segment ID represents the segment of the whole file distributed over different symbols.
  19050. *
  19051. * @return File segment index
  19052. */
  19053. getSegmentIndex() {
  19054. return this.segmentIndex;
  19055. }
  19056. setSegmentIndex(segmentIndex) {
  19057. this.segmentIndex = segmentIndex;
  19058. }
  19059. /**
  19060. * Is the same for each related PDF417 symbol
  19061. *
  19062. * @return File ID
  19063. */
  19064. getFileId() {
  19065. return this.fileId;
  19066. }
  19067. setFileId(fileId) {
  19068. this.fileId = fileId;
  19069. }
  19070. /**
  19071. * @return always null
  19072. * @deprecated use dedicated already parsed fields
  19073. */
  19074. // @Deprecated
  19075. getOptionalData() {
  19076. return this.optionalData;
  19077. }
  19078. /**
  19079. * @param optionalData old optional data format as int array
  19080. * @deprecated parse and use new fields
  19081. */
  19082. // @Deprecated
  19083. setOptionalData(optionalData) {
  19084. this.optionalData = optionalData;
  19085. }
  19086. /**
  19087. * @return true if it is the last segment
  19088. */
  19089. isLastSegment() {
  19090. return this.lastSegment;
  19091. }
  19092. setLastSegment(lastSegment) {
  19093. this.lastSegment = lastSegment;
  19094. }
  19095. /**
  19096. * @return count of segments, -1 if not set
  19097. */
  19098. getSegmentCount() {
  19099. return this.segmentCount;
  19100. }
  19101. setSegmentCount(segmentCount /*int*/) {
  19102. this.segmentCount = segmentCount;
  19103. }
  19104. getSender() {
  19105. return this.sender || null;
  19106. }
  19107. setSender(sender) {
  19108. this.sender = sender;
  19109. }
  19110. getAddressee() {
  19111. return this.addressee || null;
  19112. }
  19113. setAddressee(addressee) {
  19114. this.addressee = addressee;
  19115. }
  19116. /**
  19117. * Filename of the encoded file
  19118. *
  19119. * @return filename
  19120. */
  19121. getFileName() {
  19122. return this.fileName;
  19123. }
  19124. setFileName(fileName) {
  19125. this.fileName = fileName;
  19126. }
  19127. /**
  19128. * filesize in bytes of the encoded file
  19129. *
  19130. * @return filesize in bytes, -1 if not set
  19131. */
  19132. getFileSize() {
  19133. return this.fileSize;
  19134. }
  19135. setFileSize(fileSize /*long*/) {
  19136. this.fileSize = fileSize;
  19137. }
  19138. /**
  19139. * 16-bit CRC checksum using CCITT-16
  19140. *
  19141. * @return crc checksum, -1 if not set
  19142. */
  19143. getChecksum() {
  19144. return this.checksum;
  19145. }
  19146. setChecksum(checksum /*int*/) {
  19147. this.checksum = checksum;
  19148. }
  19149. /**
  19150. * unix epock timestamp, elapsed seconds since 1970-01-01
  19151. *
  19152. * @return elapsed seconds, -1 if not set
  19153. */
  19154. getTimestamp() {
  19155. return this.timestamp;
  19156. }
  19157. setTimestamp(timestamp /*long*/) {
  19158. this.timestamp = timestamp;
  19159. }
  19160. }
  19161. /**
  19162. * Ponyfill for Java's Long class.
  19163. */
  19164. class Long {
  19165. /**
  19166. * Parses a string to a number, since JS has no really Int64.
  19167. *
  19168. * @param num Numeric string.
  19169. * @param radix Destination radix.
  19170. */
  19171. static parseLong(num, radix = undefined) {
  19172. return parseInt(num, radix);
  19173. }
  19174. }
  19175. /**
  19176. * Custom Error class of type Exception.
  19177. */
  19178. class NullPointerException extends Exception {
  19179. }
  19180. NullPointerException.kind = 'NullPointerException';
  19181. /*
  19182. * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.
  19183. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  19184. *
  19185. * This code is free software; you can redistribute it and/or modify it
  19186. * under the terms of the GNU General Public License version 2 only, as
  19187. * published by the Free Software Foundation. Oracle designates this
  19188. * particular file as subject to the "Classpath" exception as provided
  19189. * by Oracle in the LICENSE file that accompanied this code.
  19190. *
  19191. * This code is distributed in the hope that it will be useful, but WITHOUT
  19192. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  19193. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  19194. * version 2 for more details (a copy is included in the LICENSE file that
  19195. * accompanied this code).
  19196. *
  19197. * You should have received a copy of the GNU General Public License version
  19198. * 2 along with this work; if not, write to the Free Software Foundation,
  19199. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19200. *
  19201. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19202. * or visit www.oracle.com if you need additional information or have any
  19203. * questions.
  19204. */
  19205. // package java.io;
  19206. /**
  19207. * This abstract class is the superclass of all classes representing
  19208. * an output stream of bytes. An output stream accepts output bytes
  19209. * and sends them to some sink.
  19210. * <p>
  19211. * Applications that need to define a subclass of
  19212. * <code>OutputStream</code> must always provide at least a method
  19213. * that writes one byte of output.
  19214. *
  19215. * @author Arthur van Hoff
  19216. * @see java.io.BufferedOutputStream
  19217. * @see java.io.ByteArrayOutputStream
  19218. * @see java.io.DataOutputStream
  19219. * @see java.io.FilterOutputStream
  19220. * @see java.io.InputStream
  19221. * @see java.io.OutputStream#write(int)
  19222. * @since JDK1.0
  19223. */
  19224. /*public*/ class OutputStream /*implements Closeable, Flushable*/ {
  19225. /**
  19226. * Writes <code>b.length</code> bytes from the specified byte array
  19227. * to this output stream. The general contract for <code>write(b)</code>
  19228. * is that it should have exactly the same effect as the call
  19229. * <code>write(b, 0, b.length)</code>.
  19230. *
  19231. * @param b the data.
  19232. * @exception IOException if an I/O error occurs.
  19233. * @see java.io.OutputStream#write(byte[], int, int)
  19234. */
  19235. writeBytes(b) {
  19236. this.writeBytesOffset(b, 0, b.length);
  19237. }
  19238. /**
  19239. * Writes <code>len</code> bytes from the specified byte array
  19240. * starting at offset <code>off</code> to this output stream.
  19241. * The general contract for <code>write(b, off, len)</code> is that
  19242. * some of the bytes in the array <code>b</code> are written to the
  19243. * output stream in order; element <code>b[off]</code> is the first
  19244. * byte written and <code>b[off+len-1]</code> is the last byte written
  19245. * by this operation.
  19246. * <p>
  19247. * The <code>write</code> method of <code>OutputStream</code> calls
  19248. * the write method of one argument on each of the bytes to be
  19249. * written out. Subclasses are encouraged to override this method and
  19250. * provide a more efficient implementation.
  19251. * <p>
  19252. * If <code>b</code> is <code>null</code>, a
  19253. * <code>NullPointerException</code> is thrown.
  19254. * <p>
  19255. * If <code>off</code> is negative, or <code>len</code> is negative, or
  19256. * <code>off+len</code> is greater than the length of the array
  19257. * <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
  19258. *
  19259. * @param b the data.
  19260. * @param off the start offset in the data.
  19261. * @param len the number of bytes to write.
  19262. * @exception IOException if an I/O error occurs. In particular,
  19263. * an <code>IOException</code> is thrown if the output
  19264. * stream is closed.
  19265. */
  19266. writeBytesOffset(b, off, len) {
  19267. if (b == null) {
  19268. throw new NullPointerException();
  19269. }
  19270. else if ((off < 0) || (off > b.length) || (len < 0) ||
  19271. ((off + len) > b.length) || ((off + len) < 0)) {
  19272. throw new IndexOutOfBoundsException();
  19273. }
  19274. else if (len === 0) {
  19275. return;
  19276. }
  19277. for (let i = 0; i < len; i++) {
  19278. this.write(b[off + i]);
  19279. }
  19280. }
  19281. /**
  19282. * Flushes this output stream and forces any buffered output bytes
  19283. * to be written out. The general contract of <code>flush</code> is
  19284. * that calling it is an indication that, if any bytes previously
  19285. * written have been buffered by the implementation of the output
  19286. * stream, such bytes should immediately be written to their
  19287. * intended destination.
  19288. * <p>
  19289. * If the intended destination of this stream is an abstraction provided by
  19290. * the underlying operating system, for example a file, then flushing the
  19291. * stream guarantees only that bytes previously written to the stream are
  19292. * passed to the operating system for writing; it does not guarantee that
  19293. * they are actually written to a physical device such as a disk drive.
  19294. * <p>
  19295. * The <code>flush</code> method of <code>OutputStream</code> does nothing.
  19296. *
  19297. * @exception IOException if an I/O error occurs.
  19298. */
  19299. flush() {
  19300. }
  19301. /**
  19302. * Closes this output stream and releases any system resources
  19303. * associated with this stream. The general contract of <code>close</code>
  19304. * is that it closes the output stream. A closed stream cannot perform
  19305. * output operations and cannot be reopened.
  19306. * <p>
  19307. * The <code>close</code> method of <code>OutputStream</code> does nothing.
  19308. *
  19309. * @exception IOException if an I/O error occurs.
  19310. */
  19311. close() {
  19312. }
  19313. }
  19314. /**
  19315. * Custom Error class of type Exception.
  19316. */
  19317. class OutOfMemoryError extends Exception {
  19318. }
  19319. /*
  19320. * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
  19321. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  19322. *
  19323. * This code is free software; you can redistribute it and/or modify it
  19324. * under the terms of the GNU General Public License version 2 only, as
  19325. * published by the Free Software Foundation. Oracle designates this
  19326. * particular file as subject to the "Classpath" exception as provided
  19327. * by Oracle in the LICENSE file that accompanied this code.
  19328. *
  19329. * This code is distributed in the hope that it will be useful, but WITHOUT
  19330. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  19331. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  19332. * version 2 for more details (a copy is included in the LICENSE file that
  19333. * accompanied this code).
  19334. *
  19335. * You should have received a copy of the GNU General Public License version
  19336. * 2 along with this work; if not, write to the Free Software Foundation,
  19337. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19338. *
  19339. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19340. * or visit www.oracle.com if you need additional information or have any
  19341. * questions.
  19342. */
  19343. /**
  19344. * This class implements an output stream in which the data is
  19345. * written into a byte array. The buffer automatically grows as data
  19346. * is written to it.
  19347. * The data can be retrieved using <code>toByteArray()</code> and
  19348. * <code>toString()</code>.
  19349. * <p>
  19350. * Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
  19351. * this class can be called after the stream has been closed without
  19352. * generating an <tt>IOException</tt>.
  19353. *
  19354. * @author Arthur van Hoff
  19355. * @since JDK1.0
  19356. */
  19357. /*public*/ class ByteArrayOutputStream extends OutputStream {
  19358. /**
  19359. * Creates a new byte array output stream. The buffer capacity is
  19360. * initially 32 bytes, though its size increases if necessary.
  19361. */
  19362. // public constructor() {
  19363. // this(32);
  19364. // }
  19365. /**
  19366. * Creates a new byte array output stream, with a buffer capacity of
  19367. * the specified size, in bytes.
  19368. *
  19369. * @param size the initial size.
  19370. * @exception IllegalArgumentException if size is negative.
  19371. */
  19372. constructor(size = 32) {
  19373. super();
  19374. /**
  19375. * The number of valid bytes in the buffer.
  19376. */
  19377. this.count = 0;
  19378. if (size < 0) {
  19379. throw new IllegalArgumentException('Negative initial size: '
  19380. + size);
  19381. }
  19382. this.buf = new Uint8Array(size);
  19383. }
  19384. /**
  19385. * Increases the capacity if necessary to ensure that it can hold
  19386. * at least the number of elements specified by the minimum
  19387. * capacity argument.
  19388. *
  19389. * @param minCapacity the desired minimum capacity
  19390. * @throws OutOfMemoryError if {@code minCapacity < 0}. This is
  19391. * interpreted as a request for the unsatisfiably large capacity
  19392. * {@code (long) Integer.MAX_VALUE + (minCapacity - Integer.MAX_VALUE)}.
  19393. */
  19394. ensureCapacity(minCapacity) {
  19395. // overflow-conscious code
  19396. if (minCapacity - this.buf.length > 0)
  19397. this.grow(minCapacity);
  19398. }
  19399. /**
  19400. * Increases the capacity to ensure that it can hold at least the
  19401. * number of elements specified by the minimum capacity argument.
  19402. *
  19403. * @param minCapacity the desired minimum capacity
  19404. */
  19405. grow(minCapacity) {
  19406. // overflow-conscious code
  19407. let oldCapacity = this.buf.length;
  19408. let newCapacity = oldCapacity << 1;
  19409. if (newCapacity - minCapacity < 0)
  19410. newCapacity = minCapacity;
  19411. if (newCapacity < 0) {
  19412. if (minCapacity < 0) // overflow
  19413. throw new OutOfMemoryError();
  19414. newCapacity = Integer.MAX_VALUE;
  19415. }
  19416. this.buf = Arrays.copyOfUint8Array(this.buf, newCapacity);
  19417. }
  19418. /**
  19419. * Writes the specified byte to this byte array output stream.
  19420. *
  19421. * @param b the byte to be written.
  19422. */
  19423. write(b) {
  19424. this.ensureCapacity(this.count + 1);
  19425. this.buf[this.count] = /*(byte)*/ b;
  19426. this.count += 1;
  19427. }
  19428. /**
  19429. * Writes <code>len</code> bytes from the specified byte array
  19430. * starting at offset <code>off</code> to this byte array output stream.
  19431. *
  19432. * @param b the data.
  19433. * @param off the start offset in the data.
  19434. * @param len the number of bytes to write.
  19435. */
  19436. writeBytesOffset(b, off, len) {
  19437. if ((off < 0) || (off > b.length) || (len < 0) ||
  19438. ((off + len) - b.length > 0)) {
  19439. throw new IndexOutOfBoundsException();
  19440. }
  19441. this.ensureCapacity(this.count + len);
  19442. System.arraycopy(b, off, this.buf, this.count, len);
  19443. this.count += len;
  19444. }
  19445. /**
  19446. * Writes the complete contents of this byte array output stream to
  19447. * the specified output stream argument, as if by calling the output
  19448. * stream's write method using <code>out.write(buf, 0, count)</code>.
  19449. *
  19450. * @param out the output stream to which to write the data.
  19451. * @exception IOException if an I/O error occurs.
  19452. */
  19453. writeTo(out) {
  19454. out.writeBytesOffset(this.buf, 0, this.count);
  19455. }
  19456. /**
  19457. * Resets the <code>count</code> field of this byte array output
  19458. * stream to zero, so that all currently accumulated output in the
  19459. * output stream is discarded. The output stream can be used again,
  19460. * reusing the already allocated buffer space.
  19461. *
  19462. * @see java.io.ByteArrayInputStream#count
  19463. */
  19464. reset() {
  19465. this.count = 0;
  19466. }
  19467. /**
  19468. * Creates a newly allocated byte array. Its size is the current
  19469. * size of this output stream and the valid contents of the buffer
  19470. * have been copied into it.
  19471. *
  19472. * @return the current contents of this output stream, as a byte array.
  19473. * @see java.io.ByteArrayOutputStream#size()
  19474. */
  19475. toByteArray() {
  19476. return Arrays.copyOfUint8Array(this.buf, this.count);
  19477. }
  19478. /**
  19479. * Returns the current size of the buffer.
  19480. *
  19481. * @return the value of the <code>count</code> field, which is the number
  19482. * of valid bytes in this output stream.
  19483. * @see java.io.ByteArrayOutputStream#count
  19484. */
  19485. size() {
  19486. return this.count;
  19487. }
  19488. toString(param) {
  19489. if (!param) {
  19490. return this.toString_void();
  19491. }
  19492. if (typeof param === 'string') {
  19493. return this.toString_string(param);
  19494. }
  19495. return this.toString_number(param);
  19496. }
  19497. /**
  19498. * Converts the buffer's contents into a string decoding bytes using the
  19499. * platform's default character set. The length of the new <tt>String</tt>
  19500. * is a function of the character set, and hence may not be equal to the
  19501. * size of the buffer.
  19502. *
  19503. * <p> This method always replaces malformed-input and unmappable-character
  19504. * sequences with the default replacement string for the platform's
  19505. * default character set. The {@linkplain java.nio.charset.CharsetDecoder}
  19506. * class should be used when more control over the decoding process is
  19507. * required.
  19508. *
  19509. * @return String decoded from the buffer's contents.
  19510. * @since JDK1.1
  19511. */
  19512. toString_void() {
  19513. return new String(this.buf /*, 0, this.count*/).toString();
  19514. }
  19515. /**
  19516. * Converts the buffer's contents into a string by decoding the bytes using
  19517. * the specified {@link java.nio.charset.Charset charsetName}. The length of
  19518. * the new <tt>String</tt> is a function of the charset, and hence may not be
  19519. * equal to the length of the byte array.
  19520. *
  19521. * <p> This method always replaces malformed-input and unmappable-character
  19522. * sequences with this charset's default replacement string. The {@link
  19523. * java.nio.charset.CharsetDecoder} class should be used when more control
  19524. * over the decoding process is required.
  19525. *
  19526. * @param charsetName the name of a supported
  19527. * {@linkplain java.nio.charset.Charset </code>charset<code>}
  19528. * @return String decoded from the buffer's contents.
  19529. * @exception UnsupportedEncodingException
  19530. * If the named charset is not supported
  19531. * @since JDK1.1
  19532. */
  19533. toString_string(charsetName) {
  19534. return new String(this.buf /*, 0, this.count, charsetName*/).toString();
  19535. }
  19536. /**
  19537. * Creates a newly allocated string. Its size is the current size of
  19538. * the output stream and the valid contents of the buffer have been
  19539. * copied into it. Each character <i>c</i> in the resulting string is
  19540. * constructed from the corresponding element <i>b</i> in the byte
  19541. * array such that:
  19542. * <blockquote><pre>
  19543. * c == (char)(((hibyte &amp; 0xff) &lt;&lt; 8) | (b &amp; 0xff))
  19544. * </pre></blockquote>
  19545. *
  19546. * @deprecated This method does not properly convert bytes into characters.
  19547. * As of JDK&nbsp;1.1, the preferred way to do this is via the
  19548. * <code>toString(String enc)</code> method, which takes an encoding-name
  19549. * argument, or the <code>toString()</code> method, which uses the
  19550. * platform's default character encoding.
  19551. *
  19552. * @param hibyte the high byte of each resulting Unicode character.
  19553. * @return the current contents of the output stream, as a string.
  19554. * @see java.io.ByteArrayOutputStream#size()
  19555. * @see java.io.ByteArrayOutputStream#toString(String)
  19556. * @see java.io.ByteArrayOutputStream#toString()
  19557. */
  19558. // @Deprecated
  19559. toString_number(hibyte) {
  19560. return new String(this.buf /*, hibyte, 0, this.count*/).toString();
  19561. }
  19562. /**
  19563. * Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
  19564. * this class can be called after the stream has been closed without
  19565. * generating an <tt>IOException</tt>.
  19566. * <p>
  19567. *
  19568. * @throws IOException
  19569. */
  19570. close() {
  19571. }
  19572. }
  19573. /*
  19574. * Copyright 2009 ZXing authors
  19575. *
  19576. * Licensed under the Apache License, Version 2.0 (the "License");
  19577. * you may not use this file except in compliance with the License.
  19578. * You may obtain a copy of the License at
  19579. *
  19580. * http://www.apache.org/licenses/LICENSE-2.0
  19581. *
  19582. * Unless required by applicable law or agreed to in writing, software
  19583. * distributed under the License is distributed on an "AS IS" BASIS,
  19584. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19585. * See the License for the specific language governing permissions and
  19586. * limitations under the License.
  19587. */
  19588. /*private*/ var Mode$2;
  19589. (function (Mode) {
  19590. Mode[Mode["ALPHA"] = 0] = "ALPHA";
  19591. Mode[Mode["LOWER"] = 1] = "LOWER";
  19592. Mode[Mode["MIXED"] = 2] = "MIXED";
  19593. Mode[Mode["PUNCT"] = 3] = "PUNCT";
  19594. Mode[Mode["ALPHA_SHIFT"] = 4] = "ALPHA_SHIFT";
  19595. Mode[Mode["PUNCT_SHIFT"] = 5] = "PUNCT_SHIFT";
  19596. })(Mode$2 || (Mode$2 = {}));
  19597. /**
  19598. * Indirectly access the global BigInt constructor, it
  19599. * allows browsers that doesn't support BigInt to run
  19600. * the library without breaking due to "undefined BigInt"
  19601. * errors.
  19602. */
  19603. function getBigIntConstructor() {
  19604. if (typeof window !== 'undefined') {
  19605. return window['BigInt'] || null;
  19606. }
  19607. if (typeof global !== 'undefined') {
  19608. return global['BigInt'] || null;
  19609. }
  19610. if (typeof self !== 'undefined') {
  19611. return self['BigInt'] || null;
  19612. }
  19613. throw new Error('Can\'t search globals for BigInt!');
  19614. }
  19615. /**
  19616. * Used to store the BigInt constructor.
  19617. */
  19618. let BigInteger;
  19619. /**
  19620. * This function creates a bigint value. It allows browsers
  19621. * that doesn't support BigInt to run the rest of the library
  19622. * by not directly accessing the BigInt constructor.
  19623. */
  19624. function createBigInt(num) {
  19625. if (typeof BigInteger === 'undefined') {
  19626. BigInteger = getBigIntConstructor();
  19627. }
  19628. if (BigInteger === null) {
  19629. throw new Error('BigInt is not supported!');
  19630. }
  19631. return BigInteger(num);
  19632. }
  19633. function getEXP900() {
  19634. // in Java - array with length = 16
  19635. let EXP900 = [];
  19636. EXP900[0] = createBigInt(1);
  19637. let nineHundred = createBigInt(900);
  19638. EXP900[1] = nineHundred;
  19639. // in Java - array with length = 16
  19640. for (let i /*int*/ = 2; i < 16; i++) {
  19641. EXP900[i] = EXP900[i - 1] * nineHundred;
  19642. }
  19643. return EXP900;
  19644. }
  19645. /**
  19646. * <p>This class contains the methods for decoding the PDF417 codewords.</p>
  19647. *
  19648. * @author SITA Lab (kevin.osullivan@sita.aero)
  19649. * @author Guenther Grau
  19650. */
  19651. /*final*/ class DecodedBitStreamParser$2 {
  19652. // private DecodedBitStreamParser() {
  19653. // }
  19654. /**
  19655. *
  19656. * @param codewords
  19657. * @param ecLevel
  19658. *
  19659. * @throws FormatException
  19660. */
  19661. static decode(codewords, ecLevel) {
  19662. // pass encoding to result (will be used for decode symbols in byte mode)
  19663. let result = new StringBuilder('');
  19664. // let encoding: Charset = StandardCharsets.ISO_8859_1;
  19665. let encoding = CharacterSetECI.ISO8859_1;
  19666. /**
  19667. * @note the next command is specific from this TypeScript library
  19668. * because TS can't properly cast some values to char and
  19669. * convert it to string later correctly due to encoding
  19670. * differences from Java version. As reported here:
  19671. * https://github.com/zxing-js/library/pull/264/files#r382831593
  19672. */
  19673. result.enableDecoding(encoding);
  19674. // Get compaction mode
  19675. let codeIndex = 1;
  19676. let code = codewords[codeIndex++];
  19677. let resultMetadata = new PDF417ResultMetadata();
  19678. while (codeIndex < codewords[0]) {
  19679. switch (code) {
  19680. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  19681. codeIndex = DecodedBitStreamParser$2.textCompaction(codewords, codeIndex, result);
  19682. break;
  19683. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:
  19684. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:
  19685. codeIndex = DecodedBitStreamParser$2.byteCompaction(code, codewords, encoding, codeIndex, result);
  19686. break;
  19687. case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
  19688. result.append(/*(char)*/ codewords[codeIndex++]);
  19689. break;
  19690. case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:
  19691. codeIndex = DecodedBitStreamParser$2.numericCompaction(codewords, codeIndex, result);
  19692. break;
  19693. case DecodedBitStreamParser$2.ECI_CHARSET:
  19694. let charsetECI = CharacterSetECI.getCharacterSetECIByValue(codewords[codeIndex++]);
  19695. // encoding = Charset.forName(charsetECI.getName());
  19696. break;
  19697. case DecodedBitStreamParser$2.ECI_GENERAL_PURPOSE:
  19698. // Can't do anything with generic ECI; skip its 2 characters
  19699. codeIndex += 2;
  19700. break;
  19701. case DecodedBitStreamParser$2.ECI_USER_DEFINED:
  19702. // Can't do anything with user ECI; skip its 1 character
  19703. codeIndex++;
  19704. break;
  19705. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:
  19706. codeIndex = DecodedBitStreamParser$2.decodeMacroBlock(codewords, codeIndex, resultMetadata);
  19707. break;
  19708. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
  19709. case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:
  19710. // Should not see these outside a macro block
  19711. throw new FormatException();
  19712. default:
  19713. // Default to text compaction. During testing numerous barcodes
  19714. // appeared to be missing the starting mode. In these cases defaulting
  19715. // to text compaction seems to work.
  19716. codeIndex--;
  19717. codeIndex = DecodedBitStreamParser$2.textCompaction(codewords, codeIndex, result);
  19718. break;
  19719. }
  19720. if (codeIndex < codewords.length) {
  19721. code = codewords[codeIndex++];
  19722. }
  19723. else {
  19724. throw FormatException.getFormatInstance();
  19725. }
  19726. }
  19727. if (result.length() === 0) {
  19728. throw FormatException.getFormatInstance();
  19729. }
  19730. let decoderResult = new DecoderResult(null, result.toString(), null, ecLevel);
  19731. decoderResult.setOther(resultMetadata);
  19732. return decoderResult;
  19733. }
  19734. /**
  19735. *
  19736. * @param int
  19737. * @param param1
  19738. * @param codewords
  19739. * @param int
  19740. * @param codeIndex
  19741. * @param PDF417ResultMetadata
  19742. * @param resultMetadata
  19743. *
  19744. * @throws FormatException
  19745. */
  19746. // @SuppressWarnings("deprecation")
  19747. static decodeMacroBlock(codewords, codeIndex, resultMetadata) {
  19748. if (codeIndex + DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0]) {
  19749. // we must have at least two bytes left for the segment index
  19750. throw FormatException.getFormatInstance();
  19751. }
  19752. let segmentIndexArray = new Int32Array(DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS);
  19753. for (let i /*int*/ = 0; i < DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++) {
  19754. segmentIndexArray[i] = codewords[codeIndex];
  19755. }
  19756. resultMetadata.setSegmentIndex(Integer.parseInt(DecodedBitStreamParser$2.decodeBase900toBase10(segmentIndexArray, DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS)));
  19757. let fileId = new StringBuilder();
  19758. codeIndex = DecodedBitStreamParser$2.textCompaction(codewords, codeIndex, fileId);
  19759. resultMetadata.setFileId(fileId.toString());
  19760. let optionalFieldsStart = -1;
  19761. if (codewords[codeIndex] === DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD) {
  19762. optionalFieldsStart = codeIndex + 1;
  19763. }
  19764. while (codeIndex < codewords[0]) {
  19765. switch (codewords[codeIndex]) {
  19766. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
  19767. codeIndex++;
  19768. switch (codewords[codeIndex]) {
  19769. case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:
  19770. let fileName = new StringBuilder();
  19771. codeIndex = DecodedBitStreamParser$2.textCompaction(codewords, codeIndex + 1, fileName);
  19772. resultMetadata.setFileName(fileName.toString());
  19773. break;
  19774. case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SENDER:
  19775. let sender = new StringBuilder();
  19776. codeIndex = DecodedBitStreamParser$2.textCompaction(codewords, codeIndex + 1, sender);
  19777. resultMetadata.setSender(sender.toString());
  19778. break;
  19779. case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:
  19780. let addressee = new StringBuilder();
  19781. codeIndex = DecodedBitStreamParser$2.textCompaction(codewords, codeIndex + 1, addressee);
  19782. resultMetadata.setAddressee(addressee.toString());
  19783. break;
  19784. case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:
  19785. let segmentCount = new StringBuilder();
  19786. codeIndex = DecodedBitStreamParser$2.numericCompaction(codewords, codeIndex + 1, segmentCount);
  19787. resultMetadata.setSegmentCount(Integer.parseInt(segmentCount.toString()));
  19788. break;
  19789. case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:
  19790. let timestamp = new StringBuilder();
  19791. codeIndex = DecodedBitStreamParser$2.numericCompaction(codewords, codeIndex + 1, timestamp);
  19792. resultMetadata.setTimestamp(Long.parseLong(timestamp.toString()));
  19793. break;
  19794. case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:
  19795. let checksum = new StringBuilder();
  19796. codeIndex = DecodedBitStreamParser$2.numericCompaction(codewords, codeIndex + 1, checksum);
  19797. resultMetadata.setChecksum(Integer.parseInt(checksum.toString()));
  19798. break;
  19799. case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:
  19800. let fileSize = new StringBuilder();
  19801. codeIndex = DecodedBitStreamParser$2.numericCompaction(codewords, codeIndex + 1, fileSize);
  19802. resultMetadata.setFileSize(Long.parseLong(fileSize.toString()));
  19803. break;
  19804. default:
  19805. throw FormatException.getFormatInstance();
  19806. }
  19807. break;
  19808. case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:
  19809. codeIndex++;
  19810. resultMetadata.setLastSegment(true);
  19811. break;
  19812. default:
  19813. throw FormatException.getFormatInstance();
  19814. }
  19815. }
  19816. // copy optional fields to additional options
  19817. if (optionalFieldsStart !== -1) {
  19818. let optionalFieldsLength = codeIndex - optionalFieldsStart;
  19819. if (resultMetadata.isLastSegment()) {
  19820. // do not include terminator
  19821. optionalFieldsLength--;
  19822. }
  19823. resultMetadata.setOptionalData(Arrays.copyOfRange(codewords, optionalFieldsStart, optionalFieldsStart + optionalFieldsLength));
  19824. }
  19825. return codeIndex;
  19826. }
  19827. /**
  19828. * Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be
  19829. * encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as
  19830. * well as selected control characters.
  19831. *
  19832. * @param codewords The array of codewords (data + error)
  19833. * @param codeIndex The current index into the codeword array.
  19834. * @param result The decoded data is appended to the result.
  19835. * @return The next index into the codeword array.
  19836. */
  19837. static textCompaction(codewords, codeIndex, result) {
  19838. // 2 character per codeword
  19839. let textCompactionData = new Int32Array((codewords[0] - codeIndex) * 2);
  19840. // Used to hold the byte compaction value if there is a mode shift
  19841. let byteCompactionData = new Int32Array((codewords[0] - codeIndex) * 2);
  19842. let index = 0;
  19843. let end = false;
  19844. while ((codeIndex < codewords[0]) && !end) {
  19845. let code = codewords[codeIndex++];
  19846. if (code < DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH) {
  19847. textCompactionData[index] = code / 30;
  19848. textCompactionData[index + 1] = code % 30;
  19849. index += 2;
  19850. }
  19851. else {
  19852. switch (code) {
  19853. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  19854. // reinitialize text compaction mode to alpha sub mode
  19855. textCompactionData[index++] = DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH;
  19856. break;
  19857. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:
  19858. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:
  19859. case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:
  19860. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:
  19861. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
  19862. case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:
  19863. codeIndex--;
  19864. end = true;
  19865. break;
  19866. case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
  19867. // The Mode Shift codeword 913 shall cause a temporary
  19868. // switch from Text Compaction mode to Byte Compaction mode.
  19869. // This switch shall be in effect for only the next codeword,
  19870. // after which the mode shall revert to the prevailing sub-mode
  19871. // of the Text Compaction mode. Codeword 913 is only available
  19872. // in Text Compaction mode; its use is described in 5.4.2.4.
  19873. textCompactionData[index] = DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE;
  19874. code = codewords[codeIndex++];
  19875. byteCompactionData[index] = code;
  19876. index++;
  19877. break;
  19878. }
  19879. }
  19880. }
  19881. DecodedBitStreamParser$2.decodeTextCompaction(textCompactionData, byteCompactionData, index, result);
  19882. return codeIndex;
  19883. }
  19884. /**
  19885. * The Text Compaction mode includes all the printable ASCII characters
  19886. * (i.e. values from 32 to 126) and three ASCII control characters: HT or tab
  19887. * (9: e), LF or line feed (10: e), and CR or carriage
  19888. * return (13: e). The Text Compaction mode also includes various latch
  19889. * and shift characters which are used exclusively within the mode. The Text
  19890. * Compaction mode encodes up to 2 characters per codeword. The compaction rules
  19891. * for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode
  19892. * switches are defined in 5.4.2.3.
  19893. *
  19894. * @param textCompactionData The text compaction data.
  19895. * @param byteCompactionData The byte compaction data if there
  19896. * was a mode shift.
  19897. * @param length The size of the text compaction and byte compaction data.
  19898. * @param result The decoded data is appended to the result.
  19899. */
  19900. static decodeTextCompaction(textCompactionData, byteCompactionData, length, result) {
  19901. // Beginning from an initial state of the Alpha sub-mode
  19902. // The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text
  19903. // Compaction mode Alpha sub-mode (alphabetic: uppercase). A latch codeword from another mode to the Text
  19904. // Compaction mode shall always switch to the Text Compaction Alpha sub-mode.
  19905. let subMode = Mode$2.ALPHA;
  19906. let priorToShiftMode = Mode$2.ALPHA;
  19907. let i = 0;
  19908. while (i < length) {
  19909. let subModeCh = textCompactionData[i];
  19910. let ch = /*char*/ '';
  19911. switch (subMode) {
  19912. case Mode$2.ALPHA:
  19913. // Alpha (alphabetic: uppercase)
  19914. if (subModeCh < 26) {
  19915. // Upper case Alpha Character
  19916. // Note: 65 = 'A' ASCII -> there is byte code of symbol
  19917. ch = /*(char)('A' + subModeCh) */ String.fromCharCode(65 + subModeCh);
  19918. }
  19919. else {
  19920. switch (subModeCh) {
  19921. case 26:
  19922. ch = ' ';
  19923. break;
  19924. case DecodedBitStreamParser$2.LL:
  19925. subMode = Mode$2.LOWER;
  19926. break;
  19927. case DecodedBitStreamParser$2.ML:
  19928. subMode = Mode$2.MIXED;
  19929. break;
  19930. case DecodedBitStreamParser$2.PS:
  19931. // Shift to punctuation
  19932. priorToShiftMode = subMode;
  19933. subMode = Mode$2.PUNCT_SHIFT;
  19934. break;
  19935. case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
  19936. result.append(/*(char)*/ byteCompactionData[i]);
  19937. break;
  19938. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  19939. subMode = Mode$2.ALPHA;
  19940. break;
  19941. }
  19942. }
  19943. break;
  19944. case Mode$2.LOWER:
  19945. // Lower (alphabetic: lowercase)
  19946. if (subModeCh < 26) {
  19947. ch = /*(char)('a' + subModeCh)*/ String.fromCharCode(97 + subModeCh);
  19948. }
  19949. else {
  19950. switch (subModeCh) {
  19951. case 26:
  19952. ch = ' ';
  19953. break;
  19954. case DecodedBitStreamParser$2.AS:
  19955. // Shift to alpha
  19956. priorToShiftMode = subMode;
  19957. subMode = Mode$2.ALPHA_SHIFT;
  19958. break;
  19959. case DecodedBitStreamParser$2.ML:
  19960. subMode = Mode$2.MIXED;
  19961. break;
  19962. case DecodedBitStreamParser$2.PS:
  19963. // Shift to punctuation
  19964. priorToShiftMode = subMode;
  19965. subMode = Mode$2.PUNCT_SHIFT;
  19966. break;
  19967. case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
  19968. // TODO Does this need to use the current character encoding? See other occurrences below
  19969. result.append(/*(char)*/ byteCompactionData[i]);
  19970. break;
  19971. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  19972. subMode = Mode$2.ALPHA;
  19973. break;
  19974. }
  19975. }
  19976. break;
  19977. case Mode$2.MIXED:
  19978. // Mixed (punctuation: e)
  19979. if (subModeCh < DecodedBitStreamParser$2.PL) {
  19980. ch = DecodedBitStreamParser$2.MIXED_CHARS[subModeCh];
  19981. }
  19982. else {
  19983. switch (subModeCh) {
  19984. case DecodedBitStreamParser$2.PL:
  19985. subMode = Mode$2.PUNCT;
  19986. break;
  19987. case 26:
  19988. ch = ' ';
  19989. break;
  19990. case DecodedBitStreamParser$2.LL:
  19991. subMode = Mode$2.LOWER;
  19992. break;
  19993. case DecodedBitStreamParser$2.AL:
  19994. subMode = Mode$2.ALPHA;
  19995. break;
  19996. case DecodedBitStreamParser$2.PS:
  19997. // Shift to punctuation
  19998. priorToShiftMode = subMode;
  19999. subMode = Mode$2.PUNCT_SHIFT;
  20000. break;
  20001. case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
  20002. result.append(/*(char)*/ byteCompactionData[i]);
  20003. break;
  20004. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  20005. subMode = Mode$2.ALPHA;
  20006. break;
  20007. }
  20008. }
  20009. break;
  20010. case Mode$2.PUNCT:
  20011. // Punctuation
  20012. if (subModeCh < DecodedBitStreamParser$2.PAL) {
  20013. ch = DecodedBitStreamParser$2.PUNCT_CHARS[subModeCh];
  20014. }
  20015. else {
  20016. switch (subModeCh) {
  20017. case DecodedBitStreamParser$2.PAL:
  20018. subMode = Mode$2.ALPHA;
  20019. break;
  20020. case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
  20021. result.append(/*(char)*/ byteCompactionData[i]);
  20022. break;
  20023. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  20024. subMode = Mode$2.ALPHA;
  20025. break;
  20026. }
  20027. }
  20028. break;
  20029. case Mode$2.ALPHA_SHIFT:
  20030. // Restore sub-mode
  20031. subMode = priorToShiftMode;
  20032. if (subModeCh < 26) {
  20033. ch = /*(char)('A' + subModeCh)*/ String.fromCharCode(65 + subModeCh);
  20034. }
  20035. else {
  20036. switch (subModeCh) {
  20037. case 26:
  20038. ch = ' ';
  20039. break;
  20040. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  20041. subMode = Mode$2.ALPHA;
  20042. break;
  20043. }
  20044. }
  20045. break;
  20046. case Mode$2.PUNCT_SHIFT:
  20047. // Restore sub-mode
  20048. subMode = priorToShiftMode;
  20049. if (subModeCh < DecodedBitStreamParser$2.PAL) {
  20050. ch = DecodedBitStreamParser$2.PUNCT_CHARS[subModeCh];
  20051. }
  20052. else {
  20053. switch (subModeCh) {
  20054. case DecodedBitStreamParser$2.PAL:
  20055. subMode = Mode$2.ALPHA;
  20056. break;
  20057. case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:
  20058. // PS before Shift-to-Byte is used as a padding character,
  20059. // see 5.4.2.4 of the specification
  20060. result.append(/*(char)*/ byteCompactionData[i]);
  20061. break;
  20062. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  20063. subMode = Mode$2.ALPHA;
  20064. break;
  20065. }
  20066. }
  20067. break;
  20068. }
  20069. // if (ch !== 0) {
  20070. if (ch !== '') {
  20071. // Append decoded character to result
  20072. result.append(ch);
  20073. }
  20074. i++;
  20075. }
  20076. }
  20077. /**
  20078. * Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded.
  20079. * This includes all ASCII characters value 0 to 127 inclusive and provides for international
  20080. * character set support.
  20081. *
  20082. * @param mode The byte compaction mode i.e. 901 or 924
  20083. * @param codewords The array of codewords (data + error)
  20084. * @param encoding Currently active character encoding
  20085. * @param codeIndex The current index into the codeword array.
  20086. * @param result The decoded data is appended to the result.
  20087. * @return The next index into the codeword array.
  20088. */
  20089. static /*int*/ byteCompaction(mode, codewords, encoding, codeIndex, result) {
  20090. let decodedBytes = new ByteArrayOutputStream();
  20091. let count = 0;
  20092. let value = /*long*/ 0;
  20093. let end = false;
  20094. switch (mode) {
  20095. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:
  20096. // Total number of Byte Compaction characters to be encoded
  20097. // is not a multiple of 6
  20098. let byteCompactedCodewords = new Int32Array(6);
  20099. let nextCode = codewords[codeIndex++];
  20100. while ((codeIndex < codewords[0]) && !end) {
  20101. byteCompactedCodewords[count++] = nextCode;
  20102. // Base 900
  20103. value = 900 * value + nextCode;
  20104. nextCode = codewords[codeIndex++];
  20105. // perhaps it should be ok to check only nextCode >= TEXT_COMPACTION_MODE_LATCH
  20106. switch (nextCode) {
  20107. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  20108. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:
  20109. case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:
  20110. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:
  20111. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:
  20112. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
  20113. case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:
  20114. codeIndex--;
  20115. end = true;
  20116. break;
  20117. default:
  20118. if ((count % 5 === 0) && (count > 0)) {
  20119. // Decode every 5 codewords
  20120. // Convert to Base 256
  20121. for (let j /*int*/ = 0; j < 6; ++j) {
  20122. /* @note
  20123. * JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.
  20124. * So the next bitwise operation could not be done with simple numbers
  20125. */
  20126. decodedBytes.write(/*(byte)*/ Number(createBigInt(value) >> createBigInt(8 * (5 - j))));
  20127. }
  20128. value = 0;
  20129. count = 0;
  20130. }
  20131. break;
  20132. }
  20133. }
  20134. // if the end of all codewords is reached the last codeword needs to be added
  20135. if (codeIndex === codewords[0] && nextCode < DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH) {
  20136. byteCompactedCodewords[count++] = nextCode;
  20137. }
  20138. // If Byte Compaction mode is invoked with codeword 901,
  20139. // the last group of codewords is interpreted directly
  20140. // as one byte per codeword, without compaction.
  20141. for (let i /*int*/ = 0; i < count; i++) {
  20142. decodedBytes.write(/*(byte)*/ byteCompactedCodewords[i]);
  20143. }
  20144. break;
  20145. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:
  20146. // Total number of Byte Compaction characters to be encoded
  20147. // is an integer multiple of 6
  20148. while (codeIndex < codewords[0] && !end) {
  20149. let code = codewords[codeIndex++];
  20150. if (code < DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH) {
  20151. count++;
  20152. // Base 900
  20153. value = 900 * value + code;
  20154. }
  20155. else {
  20156. switch (code) {
  20157. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  20158. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:
  20159. case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:
  20160. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:
  20161. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:
  20162. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
  20163. case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:
  20164. codeIndex--;
  20165. end = true;
  20166. break;
  20167. }
  20168. }
  20169. if ((count % 5 === 0) && (count > 0)) {
  20170. // Decode every 5 codewords
  20171. // Convert to Base 256
  20172. /* @note
  20173. * JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.
  20174. * So the next bitwise operation could not be done with simple numbers
  20175. */
  20176. for (let j /*int*/ = 0; j < 6; ++j) {
  20177. decodedBytes.write(/*(byte)*/ Number(createBigInt(value) >> createBigInt(8 * (5 - j))));
  20178. }
  20179. value = 0;
  20180. count = 0;
  20181. }
  20182. }
  20183. break;
  20184. }
  20185. result.append(StringEncoding.decode(decodedBytes.toByteArray(), encoding));
  20186. return codeIndex;
  20187. }
  20188. /**
  20189. * Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings.
  20190. *
  20191. * @param codewords The array of codewords (data + error)
  20192. * @param codeIndex The current index into the codeword array.
  20193. * @param result The decoded data is appended to the result.
  20194. * @return The next index into the codeword array.
  20195. *
  20196. * @throws FormatException
  20197. */
  20198. static numericCompaction(codewords, codeIndex /*int*/, result) {
  20199. let count = 0;
  20200. let end = false;
  20201. let numericCodewords = new Int32Array(DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS);
  20202. while (codeIndex < codewords[0] && !end) {
  20203. let code = codewords[codeIndex++];
  20204. if (codeIndex === codewords[0]) {
  20205. end = true;
  20206. }
  20207. if (code < DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH) {
  20208. numericCodewords[count] = code;
  20209. count++;
  20210. }
  20211. else {
  20212. switch (code) {
  20213. case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:
  20214. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:
  20215. case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:
  20216. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:
  20217. case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:
  20218. case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:
  20219. codeIndex--;
  20220. end = true;
  20221. break;
  20222. }
  20223. }
  20224. if ((count % DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS === 0 || code === DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH || end) && count > 0) {
  20225. // Re-invoking Numeric Compaction mode (by using codeword 902
  20226. // while in Numeric Compaction mode) serves to terminate the
  20227. // current Numeric Compaction mode grouping as described in 5.4.4.2,
  20228. // and then to start a new one grouping.
  20229. result.append(DecodedBitStreamParser$2.decodeBase900toBase10(numericCodewords, count));
  20230. count = 0;
  20231. }
  20232. }
  20233. return codeIndex;
  20234. }
  20235. /**
  20236. * Convert a list of Numeric Compacted codewords from Base 900 to Base 10.
  20237. *
  20238. * @param codewords The array of codewords
  20239. * @param count The number of codewords
  20240. * @return The decoded string representing the Numeric data.
  20241. *
  20242. * EXAMPLE
  20243. * Encode the fifteen digit numeric string 000213298174000
  20244. * Prefix the numeric string with a 1 and set the initial value of
  20245. * t = 1 000 213 298 174 000
  20246. * Calculate codeword 0
  20247. * d0 = 1 000 213 298 174 000 mod 900 = 200
  20248. *
  20249. * t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082
  20250. * Calculate codeword 1
  20251. * d1 = 1 111 348 109 082 mod 900 = 282
  20252. *
  20253. * t = 1 111 348 109 082 div 900 = 1 234 831 232
  20254. * Calculate codeword 2
  20255. * d2 = 1 234 831 232 mod 900 = 632
  20256. *
  20257. * t = 1 234 831 232 div 900 = 1 372 034
  20258. * Calculate codeword 3
  20259. * d3 = 1 372 034 mod 900 = 434
  20260. *
  20261. * t = 1 372 034 div 900 = 1 524
  20262. * Calculate codeword 4
  20263. * d4 = 1 524 mod 900 = 624
  20264. *
  20265. * t = 1 524 div 900 = 1
  20266. * Calculate codeword 5
  20267. * d5 = 1 mod 900 = 1
  20268. * t = 1 div 900 = 0
  20269. * Codeword sequence is: 1, 624, 434, 632, 282, 200
  20270. *
  20271. * Decode the above codewords involves
  20272. * 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 +
  20273. * 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000
  20274. *
  20275. * Remove leading 1 => Result is 000213298174000
  20276. *
  20277. * @throws FormatException
  20278. */
  20279. static decodeBase900toBase10(codewords, count) {
  20280. let result = createBigInt(0);
  20281. for (let i /*int*/ = 0; i < count; i++) {
  20282. result += DecodedBitStreamParser$2.EXP900[count - i - 1] * createBigInt(codewords[i]);
  20283. }
  20284. let resultString = result.toString();
  20285. if (resultString.charAt(0) !== '1') {
  20286. throw new FormatException();
  20287. }
  20288. return resultString.substring(1);
  20289. }
  20290. }
  20291. DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH = 900;
  20292. DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH = 901;
  20293. DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH = 902;
  20294. DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6 = 924;
  20295. DecodedBitStreamParser$2.ECI_USER_DEFINED = 925;
  20296. DecodedBitStreamParser$2.ECI_GENERAL_PURPOSE = 926;
  20297. DecodedBitStreamParser$2.ECI_CHARSET = 927;
  20298. DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK = 928;
  20299. DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD = 923;
  20300. DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR = 922;
  20301. DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE = 913;
  20302. DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS = 15;
  20303. DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME = 0;
  20304. DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT = 1;
  20305. DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP = 2;
  20306. DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SENDER = 3;
  20307. DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE = 4;
  20308. DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE = 5;
  20309. DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM = 6;
  20310. DecodedBitStreamParser$2.PL = 25;
  20311. DecodedBitStreamParser$2.LL = 27;
  20312. DecodedBitStreamParser$2.AS = 27;
  20313. DecodedBitStreamParser$2.ML = 28;
  20314. DecodedBitStreamParser$2.AL = 28;
  20315. DecodedBitStreamParser$2.PS = 29;
  20316. DecodedBitStreamParser$2.PAL = 29;
  20317. DecodedBitStreamParser$2.PUNCT_CHARS = ';<>@[\\]_`~!\r\t,:\n-.$/"|*()?{}\'';
  20318. DecodedBitStreamParser$2.MIXED_CHARS = '0123456789&\r\t,:#-.$/+%*=^';
  20319. /**
  20320. * Table containing values for the exponent of 900.
  20321. * This is used in the numeric compaction decode algorithm.
  20322. */
  20323. DecodedBitStreamParser$2.EXP900 = getBigIntConstructor() ? getEXP900() : [];
  20324. DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS = 2;
  20325. /*
  20326. * Copyright 2013 ZXing authors
  20327. *
  20328. * Licensed under the Apache License, Version 2.0 (the "License");
  20329. * you may not use this file except in compliance with the License.
  20330. * You may obtain a copy of the License at
  20331. *
  20332. * http://www.apache.org/licenses/LICENSE-2.0
  20333. *
  20334. * Unless required by applicable law or agreed to in writing, software
  20335. * distributed under the License is distributed on an "AS IS" BASIS,
  20336. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20337. * See the License for the specific language governing permissions and
  20338. * limitations under the License.
  20339. */
  20340. // import java.util.ArrayList;
  20341. // import java.util.Collection;
  20342. // import java.util.Formatter;
  20343. // import java.util.List;
  20344. /**
  20345. * @author Guenther Grau
  20346. */
  20347. /*public final*/ class PDF417ScanningDecoder {
  20348. constructor() { }
  20349. /**
  20350. * @TODO don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern
  20351. *
  20352. * columns. That way width can be deducted from the pattern column.
  20353. * This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider
  20354. * than it should be. This can happen if the scanner used a bad blackpoint.
  20355. *
  20356. * @param BitMatrix
  20357. * @param image
  20358. * @param ResultPoint
  20359. * @param imageTopLeft
  20360. * @param ResultPoint
  20361. * @param imageBottomLeft
  20362. * @param ResultPoint
  20363. * @param imageTopRight
  20364. * @param ResultPoint
  20365. * @param imageBottomRight
  20366. * @param int
  20367. * @param minCodewordWidth
  20368. * @param int
  20369. * @param maxCodewordWidth
  20370. *
  20371. * @throws NotFoundException
  20372. * @throws FormatException
  20373. * @throws ChecksumException
  20374. */
  20375. static decode(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight, minCodewordWidth, maxCodewordWidth) {
  20376. let boundingBox = new BoundingBox(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight);
  20377. let leftRowIndicatorColumn = null;
  20378. let rightRowIndicatorColumn = null;
  20379. let detectionResult;
  20380. for (let firstPass /*boolean*/ = true;; firstPass = false) {
  20381. if (imageTopLeft != null) {
  20382. leftRowIndicatorColumn = PDF417ScanningDecoder.getRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth);
  20383. }
  20384. if (imageTopRight != null) {
  20385. rightRowIndicatorColumn = PDF417ScanningDecoder.getRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth);
  20386. }
  20387. detectionResult = PDF417ScanningDecoder.merge(leftRowIndicatorColumn, rightRowIndicatorColumn);
  20388. if (detectionResult == null) {
  20389. throw NotFoundException.getNotFoundInstance();
  20390. }
  20391. let resultBox = detectionResult.getBoundingBox();
  20392. if (firstPass && resultBox != null &&
  20393. (resultBox.getMinY() < boundingBox.getMinY() || resultBox.getMaxY() > boundingBox.getMaxY())) {
  20394. boundingBox = resultBox;
  20395. }
  20396. else {
  20397. break;
  20398. }
  20399. }
  20400. detectionResult.setBoundingBox(boundingBox);
  20401. let maxBarcodeColumn = detectionResult.getBarcodeColumnCount() + 1;
  20402. detectionResult.setDetectionResultColumn(0, leftRowIndicatorColumn);
  20403. detectionResult.setDetectionResultColumn(maxBarcodeColumn, rightRowIndicatorColumn);
  20404. let leftToRight = leftRowIndicatorColumn != null;
  20405. for (let barcodeColumnCount /*int*/ = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++) {
  20406. let barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount;
  20407. if (detectionResult.getDetectionResultColumn(barcodeColumn) !== /* null */ undefined) {
  20408. // This will be the case for the opposite row indicator column, which doesn't need to be decoded again.
  20409. continue;
  20410. }
  20411. let detectionResultColumn;
  20412. if (barcodeColumn === 0 || barcodeColumn === maxBarcodeColumn) {
  20413. detectionResultColumn = new DetectionResultRowIndicatorColumn(boundingBox, barcodeColumn === 0);
  20414. }
  20415. else {
  20416. detectionResultColumn = new DetectionResultColumn(boundingBox);
  20417. }
  20418. detectionResult.setDetectionResultColumn(barcodeColumn, detectionResultColumn);
  20419. let startColumn = -1;
  20420. let previousStartColumn = startColumn;
  20421. // TODO start at a row for which we know the start position, then detect upwards and downwards from there.
  20422. for (let imageRow /*int*/ = boundingBox.getMinY(); imageRow <= boundingBox.getMaxY(); imageRow++) {
  20423. startColumn = PDF417ScanningDecoder.getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight);
  20424. if (startColumn < 0 || startColumn > boundingBox.getMaxX()) {
  20425. if (previousStartColumn === -1) {
  20426. continue;
  20427. }
  20428. startColumn = previousStartColumn;
  20429. }
  20430. let codeword = PDF417ScanningDecoder.detectCodeword(image, boundingBox.getMinX(), boundingBox.getMaxX(), leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth);
  20431. if (codeword != null) {
  20432. detectionResultColumn.setCodeword(imageRow, codeword);
  20433. previousStartColumn = startColumn;
  20434. minCodewordWidth = Math.min(minCodewordWidth, codeword.getWidth());
  20435. maxCodewordWidth = Math.max(maxCodewordWidth, codeword.getWidth());
  20436. }
  20437. }
  20438. }
  20439. return PDF417ScanningDecoder.createDecoderResult(detectionResult);
  20440. }
  20441. /**
  20442. *
  20443. * @param leftRowIndicatorColumn
  20444. * @param rightRowIndicatorColumn
  20445. *
  20446. * @throws NotFoundException
  20447. */
  20448. static merge(leftRowIndicatorColumn, rightRowIndicatorColumn) {
  20449. if (leftRowIndicatorColumn == null && rightRowIndicatorColumn == null) {
  20450. return null;
  20451. }
  20452. let barcodeMetadata = PDF417ScanningDecoder.getBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn);
  20453. if (barcodeMetadata == null) {
  20454. return null;
  20455. }
  20456. let boundingBox = BoundingBox.merge(PDF417ScanningDecoder.adjustBoundingBox(leftRowIndicatorColumn), PDF417ScanningDecoder.adjustBoundingBox(rightRowIndicatorColumn));
  20457. return new DetectionResult(barcodeMetadata, boundingBox);
  20458. }
  20459. /**
  20460. *
  20461. * @param rowIndicatorColumn
  20462. *
  20463. * @throws NotFoundException
  20464. */
  20465. static adjustBoundingBox(rowIndicatorColumn) {
  20466. if (rowIndicatorColumn == null) {
  20467. return null;
  20468. }
  20469. let rowHeights = rowIndicatorColumn.getRowHeights();
  20470. if (rowHeights == null) {
  20471. return null;
  20472. }
  20473. let maxRowHeight = PDF417ScanningDecoder.getMax(rowHeights);
  20474. let missingStartRows = 0;
  20475. for (let rowHeight /*int*/ of rowHeights) {
  20476. missingStartRows += maxRowHeight - rowHeight;
  20477. if (rowHeight > 0) {
  20478. break;
  20479. }
  20480. }
  20481. let codewords = rowIndicatorColumn.getCodewords();
  20482. for (let row /*int*/ = 0; missingStartRows > 0 && codewords[row] == null; row++) {
  20483. missingStartRows--;
  20484. }
  20485. let missingEndRows = 0;
  20486. for (let row /*int*/ = rowHeights.length - 1; row >= 0; row--) {
  20487. missingEndRows += maxRowHeight - rowHeights[row];
  20488. if (rowHeights[row] > 0) {
  20489. break;
  20490. }
  20491. }
  20492. for (let row /*int*/ = codewords.length - 1; missingEndRows > 0 && codewords[row] == null; row--) {
  20493. missingEndRows--;
  20494. }
  20495. return rowIndicatorColumn.getBoundingBox().addMissingRows(missingStartRows, missingEndRows, rowIndicatorColumn.isLeft());
  20496. }
  20497. static getMax(values) {
  20498. let maxValue = -1;
  20499. for (let value /*int*/ of values) {
  20500. maxValue = Math.max(maxValue, value);
  20501. }
  20502. return maxValue;
  20503. }
  20504. static getBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn) {
  20505. let leftBarcodeMetadata;
  20506. if (leftRowIndicatorColumn == null ||
  20507. (leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()) == null) {
  20508. return rightRowIndicatorColumn == null ? null : rightRowIndicatorColumn.getBarcodeMetadata();
  20509. }
  20510. let rightBarcodeMetadata;
  20511. if (rightRowIndicatorColumn == null ||
  20512. (rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()) == null) {
  20513. return leftBarcodeMetadata;
  20514. }
  20515. if (leftBarcodeMetadata.getColumnCount() !== rightBarcodeMetadata.getColumnCount() &&
  20516. leftBarcodeMetadata.getErrorCorrectionLevel() !== rightBarcodeMetadata.getErrorCorrectionLevel() &&
  20517. leftBarcodeMetadata.getRowCount() !== rightBarcodeMetadata.getRowCount()) {
  20518. return null;
  20519. }
  20520. return leftBarcodeMetadata;
  20521. }
  20522. static getRowIndicatorColumn(image, boundingBox, startPoint, leftToRight, minCodewordWidth, maxCodewordWidth) {
  20523. let rowIndicatorColumn = new DetectionResultRowIndicatorColumn(boundingBox, leftToRight);
  20524. for (let i /*int*/ = 0; i < 2; i++) {
  20525. let increment = i === 0 ? 1 : -1;
  20526. let startColumn = Math.trunc(Math.trunc(startPoint.getX()));
  20527. for (let imageRow /*int*/ = Math.trunc(Math.trunc(startPoint.getY())); imageRow <= boundingBox.getMaxY() &&
  20528. imageRow >= boundingBox.getMinY(); imageRow += increment) {
  20529. let codeword = PDF417ScanningDecoder.detectCodeword(image, 0, image.getWidth(), leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth);
  20530. if (codeword != null) {
  20531. rowIndicatorColumn.setCodeword(imageRow, codeword);
  20532. if (leftToRight) {
  20533. startColumn = codeword.getStartX();
  20534. }
  20535. else {
  20536. startColumn = codeword.getEndX();
  20537. }
  20538. }
  20539. }
  20540. }
  20541. return rowIndicatorColumn;
  20542. }
  20543. /**
  20544. *
  20545. * @param detectionResult
  20546. * @param BarcodeValue
  20547. * @param param2
  20548. * @param param3
  20549. * @param barcodeMatrix
  20550. *
  20551. * @throws NotFoundException
  20552. */
  20553. static adjustCodewordCount(detectionResult, barcodeMatrix) {
  20554. let barcodeMatrix01 = barcodeMatrix[0][1];
  20555. let numberOfCodewords = barcodeMatrix01.getValue();
  20556. let calculatedNumberOfCodewords = detectionResult.getBarcodeColumnCount() *
  20557. detectionResult.getBarcodeRowCount() -
  20558. PDF417ScanningDecoder.getNumberOfECCodeWords(detectionResult.getBarcodeECLevel());
  20559. if (numberOfCodewords.length === 0) {
  20560. if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > PDF417Common.MAX_CODEWORDS_IN_BARCODE) {
  20561. throw NotFoundException.getNotFoundInstance();
  20562. }
  20563. barcodeMatrix01.setValue(calculatedNumberOfCodewords);
  20564. }
  20565. else if (numberOfCodewords[0] !== calculatedNumberOfCodewords) {
  20566. // The calculated one is more reliable as it is derived from the row indicator columns
  20567. barcodeMatrix01.setValue(calculatedNumberOfCodewords);
  20568. }
  20569. }
  20570. /**
  20571. *
  20572. * @param detectionResult
  20573. *
  20574. * @throws FormatException
  20575. * @throws ChecksumException
  20576. * @throws NotFoundException
  20577. */
  20578. static createDecoderResult(detectionResult) {
  20579. let barcodeMatrix = PDF417ScanningDecoder.createBarcodeMatrix(detectionResult);
  20580. PDF417ScanningDecoder.adjustCodewordCount(detectionResult, barcodeMatrix);
  20581. let erasures /*Collection<Integer>*/ = new Array();
  20582. let codewords = new Int32Array(detectionResult.getBarcodeRowCount() * detectionResult.getBarcodeColumnCount());
  20583. let ambiguousIndexValuesList = /*List<int[]>*/ [];
  20584. let ambiguousIndexesList = /*Collection<Integer>*/ new Array();
  20585. for (let row /*int*/ = 0; row < detectionResult.getBarcodeRowCount(); row++) {
  20586. for (let column /*int*/ = 0; column < detectionResult.getBarcodeColumnCount(); column++) {
  20587. let values = barcodeMatrix[row][column + 1].getValue();
  20588. let codewordIndex = row * detectionResult.getBarcodeColumnCount() + column;
  20589. if (values.length === 0) {
  20590. erasures.push(codewordIndex);
  20591. }
  20592. else if (values.length === 1) {
  20593. codewords[codewordIndex] = values[0];
  20594. }
  20595. else {
  20596. ambiguousIndexesList.push(codewordIndex);
  20597. ambiguousIndexValuesList.push(values);
  20598. }
  20599. }
  20600. }
  20601. let ambiguousIndexValues = new Array(ambiguousIndexValuesList.length);
  20602. for (let i /*int*/ = 0; i < ambiguousIndexValues.length; i++) {
  20603. ambiguousIndexValues[i] = ambiguousIndexValuesList[i];
  20604. }
  20605. return PDF417ScanningDecoder.createDecoderResultFromAmbiguousValues(detectionResult.getBarcodeECLevel(), codewords, PDF417Common.toIntArray(erasures), PDF417Common.toIntArray(ambiguousIndexesList), ambiguousIndexValues);
  20606. }
  20607. /**
  20608. * This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The
  20609. * current error correction implementation doesn't deal with erasures very well, so it's better to provide a value
  20610. * for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of
  20611. * the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the
  20612. * ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes,
  20613. * so decoding the normal barcodes is not affected by this.
  20614. *
  20615. * @param erasureArray contains the indexes of erasures
  20616. * @param ambiguousIndexes array with the indexes that have more than one most likely value
  20617. * @param ambiguousIndexValues two dimensional array that contains the ambiguous values. The first dimension must
  20618. * be the same length as the ambiguousIndexes array
  20619. *
  20620. * @throws FormatException
  20621. * @throws ChecksumException
  20622. */
  20623. static createDecoderResultFromAmbiguousValues(ecLevel, codewords, erasureArray, ambiguousIndexes, ambiguousIndexValues) {
  20624. let ambiguousIndexCount = new Int32Array(ambiguousIndexes.length);
  20625. let tries = 100;
  20626. while (tries-- > 0) {
  20627. for (let i /*int*/ = 0; i < ambiguousIndexCount.length; i++) {
  20628. codewords[ambiguousIndexes[i]] = ambiguousIndexValues[i][ambiguousIndexCount[i]];
  20629. }
  20630. try {
  20631. return PDF417ScanningDecoder.decodeCodewords(codewords, ecLevel, erasureArray);
  20632. }
  20633. catch (err) {
  20634. let ignored = err instanceof ChecksumException;
  20635. if (!ignored) {
  20636. throw err;
  20637. }
  20638. }
  20639. if (ambiguousIndexCount.length === 0) {
  20640. throw ChecksumException.getChecksumInstance();
  20641. }
  20642. for (let i /*int*/ = 0; i < ambiguousIndexCount.length; i++) {
  20643. if (ambiguousIndexCount[i] < ambiguousIndexValues[i].length - 1) {
  20644. ambiguousIndexCount[i]++;
  20645. break;
  20646. }
  20647. else {
  20648. ambiguousIndexCount[i] = 0;
  20649. if (i === ambiguousIndexCount.length - 1) {
  20650. throw ChecksumException.getChecksumInstance();
  20651. }
  20652. }
  20653. }
  20654. }
  20655. throw ChecksumException.getChecksumInstance();
  20656. }
  20657. static createBarcodeMatrix(detectionResult) {
  20658. // let barcodeMatrix: BarcodeValue[][] =
  20659. // new BarcodeValue[detectionResult.getBarcodeRowCount()][detectionResult.getBarcodeColumnCount() + 2];
  20660. let barcodeMatrix = Array.from({ length: detectionResult.getBarcodeRowCount() }, () => new Array(detectionResult.getBarcodeColumnCount() + 2));
  20661. for (let row /*int*/ = 0; row < barcodeMatrix.length; row++) {
  20662. for (let column /*int*/ = 0; column < barcodeMatrix[row].length; column++) {
  20663. barcodeMatrix[row][column] = new BarcodeValue();
  20664. }
  20665. }
  20666. let column = 0;
  20667. for (let detectionResultColumn /*DetectionResultColumn*/ of detectionResult.getDetectionResultColumns()) {
  20668. if (detectionResultColumn != null) {
  20669. for (let codeword /*Codeword*/ of detectionResultColumn.getCodewords()) {
  20670. if (codeword != null) {
  20671. let rowNumber = codeword.getRowNumber();
  20672. if (rowNumber >= 0) {
  20673. if (rowNumber >= barcodeMatrix.length) {
  20674. // We have more rows than the barcode metadata allows for, ignore them.
  20675. continue;
  20676. }
  20677. barcodeMatrix[rowNumber][column].setValue(codeword.getValue());
  20678. }
  20679. }
  20680. }
  20681. }
  20682. column++;
  20683. }
  20684. return barcodeMatrix;
  20685. }
  20686. static isValidBarcodeColumn(detectionResult, barcodeColumn) {
  20687. return barcodeColumn >= 0 && barcodeColumn <= detectionResult.getBarcodeColumnCount() + 1;
  20688. }
  20689. static getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight) {
  20690. let offset = leftToRight ? 1 : -1;
  20691. let codeword = null;
  20692. if (PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult, barcodeColumn - offset)) {
  20693. codeword = detectionResult.getDetectionResultColumn(barcodeColumn - offset).getCodeword(imageRow);
  20694. }
  20695. if (codeword != null) {
  20696. return leftToRight ? codeword.getEndX() : codeword.getStartX();
  20697. }
  20698. codeword = detectionResult.getDetectionResultColumn(barcodeColumn).getCodewordNearby(imageRow);
  20699. if (codeword != null) {
  20700. return leftToRight ? codeword.getStartX() : codeword.getEndX();
  20701. }
  20702. if (PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult, barcodeColumn - offset)) {
  20703. codeword = detectionResult.getDetectionResultColumn(barcodeColumn - offset).getCodewordNearby(imageRow);
  20704. }
  20705. if (codeword != null) {
  20706. return leftToRight ? codeword.getEndX() : codeword.getStartX();
  20707. }
  20708. let skippedColumns = 0;
  20709. while (PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult, barcodeColumn - offset)) {
  20710. barcodeColumn -= offset;
  20711. for (let previousRowCodeword /*Codeword*/ of detectionResult.getDetectionResultColumn(barcodeColumn).getCodewords()) {
  20712. if (previousRowCodeword != null) {
  20713. return (leftToRight ? previousRowCodeword.getEndX() : previousRowCodeword.getStartX()) +
  20714. offset *
  20715. skippedColumns *
  20716. (previousRowCodeword.getEndX() - previousRowCodeword.getStartX());
  20717. }
  20718. }
  20719. skippedColumns++;
  20720. }
  20721. return leftToRight ? detectionResult.getBoundingBox().getMinX() : detectionResult.getBoundingBox().getMaxX();
  20722. }
  20723. static detectCodeword(image, minColumn, maxColumn, leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth) {
  20724. startColumn = PDF417ScanningDecoder.adjustCodewordStartColumn(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
  20725. // we usually know fairly exact now how long a codeword is. We should provide minimum and maximum expected length
  20726. // and try to adjust the read pixels, e.g. remove single pixel errors or try to cut off exceeding pixels.
  20727. // min and maxCodewordWidth should not be used as they are calculated for the whole barcode an can be inaccurate
  20728. // for the current position
  20729. let moduleBitCount = PDF417ScanningDecoder.getModuleBitCount(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
  20730. if (moduleBitCount == null) {
  20731. return null;
  20732. }
  20733. let endColumn;
  20734. let codewordBitCount = MathUtils.sum(moduleBitCount);
  20735. if (leftToRight) {
  20736. endColumn = startColumn + codewordBitCount;
  20737. }
  20738. else {
  20739. for (let i /*int*/ = 0; i < moduleBitCount.length / 2; i++) {
  20740. let tmpCount = moduleBitCount[i];
  20741. moduleBitCount[i] = moduleBitCount[moduleBitCount.length - 1 - i];
  20742. moduleBitCount[moduleBitCount.length - 1 - i] = tmpCount;
  20743. }
  20744. endColumn = startColumn;
  20745. startColumn = endColumn - codewordBitCount;
  20746. }
  20747. // TODO implement check for width and correction of black and white bars
  20748. // use start (and maybe stop pattern) to determine if black bars are wider than white bars. If so, adjust.
  20749. // should probably done only for codewords with a lot more than 17 bits.
  20750. // The following fixes 10-1.png, which has wide black bars and small white bars
  20751. // for (let i /*int*/ = 0; i < moduleBitCount.length; i++) {
  20752. // if (i % 2 === 0) {
  20753. // moduleBitCount[i]--;
  20754. // } else {
  20755. // moduleBitCount[i]++;
  20756. // }
  20757. // }
  20758. // We could also use the width of surrounding codewords for more accurate results, but this seems
  20759. // sufficient for now
  20760. if (!PDF417ScanningDecoder.checkCodewordSkew(codewordBitCount, minCodewordWidth, maxCodewordWidth)) {
  20761. // We could try to use the startX and endX position of the codeword in the same column in the previous row,
  20762. // create the bit count from it and normalize it to 8. This would help with single pixel errors.
  20763. return null;
  20764. }
  20765. let decodedValue = PDF417CodewordDecoder.getDecodedValue(moduleBitCount);
  20766. let codeword = PDF417Common.getCodeword(decodedValue);
  20767. if (codeword === -1) {
  20768. return null;
  20769. }
  20770. return new Codeword(startColumn, endColumn, PDF417ScanningDecoder.getCodewordBucketNumber(decodedValue), codeword);
  20771. }
  20772. static getModuleBitCount(image, minColumn, maxColumn, leftToRight, startColumn, imageRow) {
  20773. let imageColumn = startColumn;
  20774. let moduleBitCount = new Int32Array(8);
  20775. let moduleNumber = 0;
  20776. let increment = leftToRight ? 1 : -1;
  20777. let previousPixelValue = leftToRight;
  20778. while ((leftToRight ? imageColumn < maxColumn : imageColumn >= minColumn) &&
  20779. moduleNumber < moduleBitCount.length) {
  20780. if (image.get(imageColumn, imageRow) === previousPixelValue) {
  20781. moduleBitCount[moduleNumber]++;
  20782. imageColumn += increment;
  20783. }
  20784. else {
  20785. moduleNumber++;
  20786. previousPixelValue = !previousPixelValue;
  20787. }
  20788. }
  20789. if (moduleNumber === moduleBitCount.length ||
  20790. ((imageColumn === (leftToRight ? maxColumn : minColumn)) &&
  20791. moduleNumber === moduleBitCount.length - 1)) {
  20792. return moduleBitCount;
  20793. }
  20794. return null;
  20795. }
  20796. static getNumberOfECCodeWords(barcodeECLevel) {
  20797. return 2 << barcodeECLevel;
  20798. }
  20799. static adjustCodewordStartColumn(image, minColumn, maxColumn, leftToRight, codewordStartColumn, imageRow) {
  20800. let correctedStartColumn = codewordStartColumn;
  20801. let increment = leftToRight ? -1 : 1;
  20802. // there should be no black pixels before the start column. If there are, then we need to start earlier.
  20803. for (let i /*int*/ = 0; i < 2; i++) {
  20804. while ((leftToRight ? correctedStartColumn >= minColumn : correctedStartColumn < maxColumn) &&
  20805. leftToRight === image.get(correctedStartColumn, imageRow)) {
  20806. if (Math.abs(codewordStartColumn - correctedStartColumn) > PDF417ScanningDecoder.CODEWORD_SKEW_SIZE) {
  20807. return codewordStartColumn;
  20808. }
  20809. correctedStartColumn += increment;
  20810. }
  20811. increment = -increment;
  20812. leftToRight = !leftToRight;
  20813. }
  20814. return correctedStartColumn;
  20815. }
  20816. static checkCodewordSkew(codewordSize, minCodewordWidth, maxCodewordWidth) {
  20817. return minCodewordWidth - PDF417ScanningDecoder.CODEWORD_SKEW_SIZE <= codewordSize &&
  20818. codewordSize <= maxCodewordWidth + PDF417ScanningDecoder.CODEWORD_SKEW_SIZE;
  20819. }
  20820. /**
  20821. * @throws FormatException,
  20822. * @throws ChecksumException
  20823. */
  20824. static decodeCodewords(codewords, ecLevel, erasures) {
  20825. if (codewords.length === 0) {
  20826. throw FormatException.getFormatInstance();
  20827. }
  20828. let numECCodewords = 1 << (ecLevel + 1);
  20829. let correctedErrorsCount = PDF417ScanningDecoder.correctErrors(codewords, erasures, numECCodewords);
  20830. PDF417ScanningDecoder.verifyCodewordCount(codewords, numECCodewords);
  20831. // Decode the codewords
  20832. let decoderResult = DecodedBitStreamParser$2.decode(codewords, '' + ecLevel);
  20833. decoderResult.setErrorsCorrected(correctedErrorsCount);
  20834. decoderResult.setErasures(erasures.length);
  20835. return decoderResult;
  20836. }
  20837. /**
  20838. * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
  20839. * correct the errors in-place.</p>
  20840. *
  20841. * @param codewords data and error correction codewords
  20842. * @param erasures positions of any known erasures
  20843. * @param numECCodewords number of error correction codewords that are available in codewords
  20844. * @throws ChecksumException if error correction fails
  20845. */
  20846. static correctErrors(codewords, erasures, numECCodewords) {
  20847. if (erasures != null &&
  20848. erasures.length > numECCodewords / 2 + PDF417ScanningDecoder.MAX_ERRORS ||
  20849. numECCodewords < 0 ||
  20850. numECCodewords > PDF417ScanningDecoder.MAX_EC_CODEWORDS) {
  20851. // Too many errors or EC Codewords is corrupted
  20852. throw ChecksumException.getChecksumInstance();
  20853. }
  20854. return PDF417ScanningDecoder.errorCorrection.decode(codewords, numECCodewords, erasures);
  20855. }
  20856. /**
  20857. * Verify that all is OK with the codeword array.
  20858. * @throws FormatException
  20859. */
  20860. static verifyCodewordCount(codewords, numECCodewords) {
  20861. if (codewords.length < 4) {
  20862. // Codeword array size should be at least 4 allowing for
  20863. // Count CW, At least one Data CW, Error Correction CW, Error Correction CW
  20864. throw FormatException.getFormatInstance();
  20865. }
  20866. // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
  20867. // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
  20868. // codewords, but excluding the number of error correction codewords.
  20869. let numberOfCodewords = codewords[0];
  20870. if (numberOfCodewords > codewords.length) {
  20871. throw FormatException.getFormatInstance();
  20872. }
  20873. if (numberOfCodewords === 0) {
  20874. // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
  20875. if (numECCodewords < codewords.length) {
  20876. codewords[0] = codewords.length - numECCodewords;
  20877. }
  20878. else {
  20879. throw FormatException.getFormatInstance();
  20880. }
  20881. }
  20882. }
  20883. static getBitCountForCodeword(codeword) {
  20884. let result = new Int32Array(8);
  20885. let previousValue = 0;
  20886. let i = result.length - 1;
  20887. while (true) {
  20888. if ((codeword & 0x1) !== previousValue) {
  20889. previousValue = codeword & 0x1;
  20890. i--;
  20891. if (i < 0) {
  20892. break;
  20893. }
  20894. }
  20895. result[i]++;
  20896. codeword >>= 1;
  20897. }
  20898. return result;
  20899. }
  20900. static getCodewordBucketNumber(codeword) {
  20901. if (codeword instanceof Int32Array) {
  20902. return this.getCodewordBucketNumber_Int32Array(codeword);
  20903. }
  20904. return this.getCodewordBucketNumber_number(codeword);
  20905. }
  20906. static getCodewordBucketNumber_number(codeword) {
  20907. return PDF417ScanningDecoder.getCodewordBucketNumber(PDF417ScanningDecoder.getBitCountForCodeword(codeword));
  20908. }
  20909. static getCodewordBucketNumber_Int32Array(moduleBitCount) {
  20910. return (moduleBitCount[0] - moduleBitCount[2] + moduleBitCount[4] - moduleBitCount[6] + 9) % 9;
  20911. }
  20912. static toString(barcodeMatrix) {
  20913. let formatter = new Formatter();
  20914. // try (let formatter = new Formatter()) {
  20915. for (let row /*int*/ = 0; row < barcodeMatrix.length; row++) {
  20916. formatter.format('Row %2d: ', row);
  20917. for (let column /*int*/ = 0; column < barcodeMatrix[row].length; column++) {
  20918. let barcodeValue = barcodeMatrix[row][column];
  20919. if (barcodeValue.getValue().length === 0) {
  20920. formatter.format(' ', null);
  20921. }
  20922. else {
  20923. formatter.format('%4d(%2d)', barcodeValue.getValue()[0], barcodeValue.getConfidence(barcodeValue.getValue()[0]));
  20924. }
  20925. }
  20926. formatter.format('%n');
  20927. }
  20928. return formatter.toString();
  20929. // }
  20930. }
  20931. }
  20932. /*final*/ PDF417ScanningDecoder.CODEWORD_SKEW_SIZE = 2;
  20933. /*final*/ PDF417ScanningDecoder.MAX_ERRORS = 3;
  20934. /*final*/ PDF417ScanningDecoder.MAX_EC_CODEWORDS = 512;
  20935. /*final*/ PDF417ScanningDecoder.errorCorrection = new ErrorCorrection();
  20936. /*
  20937. * Copyright 2009 ZXing authors
  20938. *
  20939. * Licensed under the Apache License, Version 2.0 (the "License");
  20940. * you may not use this file except in compliance with the License.
  20941. * You may obtain a copy of the License at
  20942. *
  20943. * http://www.apache.org/licenses/LICENSE-2.0
  20944. *
  20945. * Unless required by applicable law or agreed to in writing, software
  20946. * distributed under the License is distributed on an "AS IS" BASIS,
  20947. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20948. * See the License for the specific language governing permissions and
  20949. * limitations under the License.
  20950. */
  20951. // import java.util.ArrayList;
  20952. // import java.util.List;
  20953. // import java.util.Map;
  20954. /**
  20955. * This implementation can detect and decode PDF417 codes in an image.
  20956. *
  20957. * @author Guenther Grau
  20958. */
  20959. /*public final*/ class PDF417Reader {
  20960. // private static /*final Result[]*/ EMPTY_RESULT_ARRAY: Result[] = new Result([0]);
  20961. /**
  20962. * Locates and decodes a PDF417 code in an image.
  20963. *
  20964. * @return a String representing the content encoded by the PDF417 code
  20965. * @throws NotFoundException if a PDF417 code cannot be found,
  20966. * @throws FormatException if a PDF417 cannot be decoded
  20967. * @throws ChecksumException
  20968. */
  20969. // @Override
  20970. decode(image, hints = null) {
  20971. let result = PDF417Reader.decode(image, hints, false);
  20972. if (result == null || result.length === 0 || result[0] == null) {
  20973. throw NotFoundException.getNotFoundInstance();
  20974. }
  20975. return result[0];
  20976. }
  20977. /**
  20978. *
  20979. * @param BinaryBitmap
  20980. * @param image
  20981. * @throws NotFoundException
  20982. */
  20983. // @Override
  20984. decodeMultiple(image, hints = null) {
  20985. try {
  20986. return PDF417Reader.decode(image, hints, true);
  20987. }
  20988. catch (ignored) {
  20989. if (ignored instanceof FormatException || ignored instanceof ChecksumException) {
  20990. throw NotFoundException.getNotFoundInstance();
  20991. }
  20992. throw ignored;
  20993. }
  20994. }
  20995. /**
  20996. *
  20997. * @param image
  20998. * @param hints
  20999. * @param multiple
  21000. *
  21001. * @throws NotFoundException
  21002. * @throws FormatExceptionß
  21003. * @throws ChecksumException
  21004. */
  21005. static decode(image, hints, multiple) {
  21006. const results = new Array();
  21007. const detectorResult = Detector$3.detectMultiple(image, hints, multiple);
  21008. for (const points of detectorResult.getPoints()) {
  21009. const decoderResult = PDF417ScanningDecoder.decode(detectorResult.getBits(), points[4], points[5], points[6], points[7], PDF417Reader.getMinCodewordWidth(points), PDF417Reader.getMaxCodewordWidth(points));
  21010. const result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), undefined, points, BarcodeFormat$1.PDF_417);
  21011. result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL, decoderResult.getECLevel());
  21012. const pdf417ResultMetadata = decoderResult.getOther();
  21013. if (pdf417ResultMetadata != null) {
  21014. result.putMetadata(ResultMetadataType$1.PDF417_EXTRA_METADATA, pdf417ResultMetadata);
  21015. }
  21016. results.push(result);
  21017. }
  21018. return results.map(x => x);
  21019. }
  21020. static getMaxWidth(p1, p2) {
  21021. if (p1 == null || p2 == null) {
  21022. return 0;
  21023. }
  21024. return Math.trunc(Math.abs(p1.getX() - p2.getX()));
  21025. }
  21026. static getMinWidth(p1, p2) {
  21027. if (p1 == null || p2 == null) {
  21028. return Integer.MAX_VALUE;
  21029. }
  21030. return Math.trunc(Math.abs(p1.getX() - p2.getX()));
  21031. }
  21032. static getMaxCodewordWidth(p) {
  21033. return Math.floor(Math.max(Math.max(PDF417Reader.getMaxWidth(p[0], p[4]), PDF417Reader.getMaxWidth(p[6], p[2]) * PDF417Common.MODULES_IN_CODEWORD /
  21034. PDF417Common.MODULES_IN_STOP_PATTERN), Math.max(PDF417Reader.getMaxWidth(p[1], p[5]), PDF417Reader.getMaxWidth(p[7], p[3]) * PDF417Common.MODULES_IN_CODEWORD /
  21035. PDF417Common.MODULES_IN_STOP_PATTERN)));
  21036. }
  21037. static getMinCodewordWidth(p) {
  21038. return Math.floor(Math.min(Math.min(PDF417Reader.getMinWidth(p[0], p[4]), PDF417Reader.getMinWidth(p[6], p[2]) * PDF417Common.MODULES_IN_CODEWORD /
  21039. PDF417Common.MODULES_IN_STOP_PATTERN), Math.min(PDF417Reader.getMinWidth(p[1], p[5]), PDF417Reader.getMinWidth(p[7], p[3]) * PDF417Common.MODULES_IN_CODEWORD /
  21040. PDF417Common.MODULES_IN_STOP_PATTERN)));
  21041. }
  21042. // @Override
  21043. reset() {
  21044. // nothing needs to be reset
  21045. }
  21046. }
  21047. /**
  21048. * Custom Error class of type Exception.
  21049. */
  21050. class ReaderException extends Exception {
  21051. }
  21052. ReaderException.kind = 'ReaderException';
  21053. /*
  21054. * Copyright 2009 ZXing authors
  21055. *
  21056. * Licensed under the Apache License, Version 2.0 (the "License");
  21057. * you may not use this file except in compliance with the License.
  21058. * You may obtain a copy of the License at
  21059. *
  21060. * http://www.apache.org/licenses/LICENSE-2.0
  21061. *
  21062. * Unless required by applicable law or agreed to in writing, software
  21063. * distributed under the License is distributed on an "AS IS" BASIS,
  21064. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21065. * See the License for the specific language governing permissions and
  21066. * limitations under the License.
  21067. */
  21068. /*namespace com.google.zxing {*/
  21069. /**
  21070. * MultiFormatReader is a convenience class and the main entry point into the library for most uses.
  21071. * By default it attempts to decode all barcode formats that the library supports. Optionally, you
  21072. * can provide a hints object to request different behavior, for example only decoding QR codes.
  21073. *
  21074. * @author Sean Owen
  21075. * @author dswitkin@google.com (Daniel Switkin)
  21076. */
  21077. class MultiFormatReader {
  21078. /**
  21079. * This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it
  21080. * passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly.
  21081. * Use setHints() followed by decodeWithState() for continuous scan applications.
  21082. *
  21083. * @param image The pixel data to decode
  21084. * @return The contents of the image
  21085. *
  21086. * @throws NotFoundException Any errors which occurred
  21087. */
  21088. /*@Override*/
  21089. // public decode(image: BinaryBitmap): Result {
  21090. // setHints(null)
  21091. // return decodeInternal(image)
  21092. // }
  21093. /**
  21094. * Decode an image using the hints provided. Does not honor existing state.
  21095. *
  21096. * @param image The pixel data to decode
  21097. * @param hints The hints to use, clearing the previous state.
  21098. * @return The contents of the image
  21099. *
  21100. * @throws NotFoundException Any errors which occurred
  21101. */
  21102. /*@Override*/
  21103. decode(image, hints) {
  21104. this.setHints(hints);
  21105. return this.decodeInternal(image);
  21106. }
  21107. /**
  21108. * Decode an image using the state set up by calling setHints() previously. Continuous scan
  21109. * clients will get a <b>large</b> speed increase by using this instead of decode().
  21110. *
  21111. * @param image The pixel data to decode
  21112. * @return The contents of the image
  21113. *
  21114. * @throws NotFoundException Any errors which occurred
  21115. */
  21116. decodeWithState(image) {
  21117. // Make sure to set up the default state so we don't crash
  21118. if (this.readers === null || this.readers === undefined) {
  21119. this.setHints(null);
  21120. }
  21121. return this.decodeInternal(image);
  21122. }
  21123. /**
  21124. * This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls
  21125. * to decodeWithState(image) can reuse the same set of readers without reallocating memory. This
  21126. * is important for performance in continuous scan clients.
  21127. *
  21128. * @param hints The set of hints to use for subsequent calls to decode(image)
  21129. */
  21130. setHints(hints) {
  21131. this.hints = hints;
  21132. const tryHarder = hints !== null && hints !== undefined && undefined !== hints.get(DecodeHintType$1.TRY_HARDER);
  21133. /*@SuppressWarnings("unchecked")*/
  21134. const formats = hints === null || hints === undefined ? null : hints.get(DecodeHintType$1.POSSIBLE_FORMATS);
  21135. const readers = new Array();
  21136. if (formats !== null && formats !== undefined) {
  21137. const addOneDReader = formats.some(f => f === BarcodeFormat$1.UPC_A ||
  21138. f === BarcodeFormat$1.UPC_E ||
  21139. f === BarcodeFormat$1.EAN_13 ||
  21140. f === BarcodeFormat$1.EAN_8 ||
  21141. f === BarcodeFormat$1.CODABAR ||
  21142. f === BarcodeFormat$1.CODE_39 ||
  21143. f === BarcodeFormat$1.CODE_93 ||
  21144. f === BarcodeFormat$1.CODE_128 ||
  21145. f === BarcodeFormat$1.ITF ||
  21146. f === BarcodeFormat$1.RSS_14 ||
  21147. f === BarcodeFormat$1.RSS_EXPANDED);
  21148. // Put 1D readers upfront in "normal" mode
  21149. // TYPESCRIPTPORT: TODO: uncomment below as they are ported
  21150. if (addOneDReader && !tryHarder) {
  21151. readers.push(new MultiFormatOneDReader(hints));
  21152. }
  21153. if (formats.includes(BarcodeFormat$1.QR_CODE)) {
  21154. readers.push(new QRCodeReader());
  21155. }
  21156. if (formats.includes(BarcodeFormat$1.DATA_MATRIX)) {
  21157. readers.push(new DataMatrixReader());
  21158. }
  21159. if (formats.includes(BarcodeFormat$1.AZTEC)) {
  21160. readers.push(new AztecReader());
  21161. }
  21162. if (formats.includes(BarcodeFormat$1.PDF_417)) {
  21163. readers.push(new PDF417Reader());
  21164. }
  21165. // if (formats.includes(BarcodeFormat.MAXICODE)) {
  21166. // readers.push(new MaxiCodeReader())
  21167. // }
  21168. // At end in "try harder" mode
  21169. if (addOneDReader && tryHarder) {
  21170. readers.push(new MultiFormatOneDReader(hints));
  21171. }
  21172. }
  21173. if (readers.length === 0) {
  21174. if (!tryHarder) {
  21175. readers.push(new MultiFormatOneDReader(hints));
  21176. }
  21177. readers.push(new QRCodeReader());
  21178. readers.push(new DataMatrixReader());
  21179. readers.push(new AztecReader());
  21180. readers.push(new PDF417Reader());
  21181. // readers.push(new MaxiCodeReader())
  21182. if (tryHarder) {
  21183. readers.push(new MultiFormatOneDReader(hints));
  21184. }
  21185. }
  21186. this.readers = readers; // .toArray(new Reader[readers.size()])
  21187. }
  21188. /*@Override*/
  21189. reset() {
  21190. if (this.readers !== null) {
  21191. for (const reader of this.readers) {
  21192. reader.reset();
  21193. }
  21194. }
  21195. }
  21196. /**
  21197. * @throws NotFoundException
  21198. */
  21199. decodeInternal(image) {
  21200. if (this.readers === null) {
  21201. throw new ReaderException('No readers where selected, nothing can be read.');
  21202. }
  21203. for (const reader of this.readers) {
  21204. // Trying to decode with ${reader} reader.
  21205. try {
  21206. return reader.decode(image, this.hints);
  21207. }
  21208. catch (ex) {
  21209. if (ex instanceof ReaderException) {
  21210. continue;
  21211. }
  21212. // Bad Exception.
  21213. }
  21214. }
  21215. throw new NotFoundException('No MultiFormat Readers were able to detect the code.');
  21216. }
  21217. }
  21218. class BrowserMultiFormatReader extends BrowserCodeReader {
  21219. constructor(hints = null, timeBetweenScansMillis = 500) {
  21220. const reader = new MultiFormatReader();
  21221. reader.setHints(hints);
  21222. super(reader, timeBetweenScansMillis);
  21223. }
  21224. /**
  21225. * Overwrite decodeBitmap to call decodeWithState, which will pay
  21226. * attention to the hints set in the constructor function
  21227. */
  21228. decodeBitmap(binaryBitmap) {
  21229. return this.reader.decodeWithState(binaryBitmap);
  21230. }
  21231. }
  21232. /**
  21233. * @deprecated Moving to @zxing/browser
  21234. *
  21235. * QR Code reader to use from browser.
  21236. */
  21237. class BrowserPDF417Reader extends BrowserCodeReader {
  21238. /**
  21239. * Creates an instance of BrowserPDF417Reader.
  21240. * @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
  21241. */
  21242. constructor(timeBetweenScansMillis = 500) {
  21243. super(new PDF417Reader(), timeBetweenScansMillis);
  21244. }
  21245. }
  21246. /**
  21247. * @deprecated Moving to @zxing/browser
  21248. *
  21249. * QR Code reader to use from browser.
  21250. */
  21251. class BrowserQRCodeReader extends BrowserCodeReader {
  21252. /**
  21253. * Creates an instance of BrowserQRCodeReader.
  21254. * @param {number} [timeBetweenScansMillis=500] the time delay between subsequent decode tries
  21255. */
  21256. constructor(timeBetweenScansMillis = 500) {
  21257. super(new QRCodeReader(), timeBetweenScansMillis);
  21258. }
  21259. }
  21260. /*
  21261. * Copyright 2009 ZXing authors
  21262. *
  21263. * Licensed under the Apache License, Version 2.0 (the "License");
  21264. * you may not use this file except in compliance with the License.
  21265. * You may obtain a copy of the License at
  21266. *
  21267. * http://www.apache.org/licenses/LICENSE-2.0
  21268. *
  21269. * Unless required by applicable law or agreed to in writing, software
  21270. * distributed under the License is distributed on an "AS IS" BASIS,
  21271. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21272. * See the License for the specific language governing permissions and
  21273. * limitations under the License.
  21274. */
  21275. /*namespace com.google.zxing {*/
  21276. /**
  21277. * These are a set of hints that you may pass to Writers to specify their behavior.
  21278. *
  21279. * @author dswitkin@google.com (Daniel Switkin)
  21280. */
  21281. var EncodeHintType;
  21282. (function (EncodeHintType) {
  21283. /**
  21284. * Specifies what degree of error correction to use, for example in QR Codes.
  21285. * Type depends on the encoder. For example for QR codes it's type
  21286. * {@link com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ErrorCorrectionLevel}.
  21287. * For Aztec it is of type {@link Integer}, representing the minimal percentage of error correction words.
  21288. * For PDF417 it is of type {@link Integer}, valid values being 0 to 8.
  21289. * In all cases, it can also be a {@link String} representation of the desired value as well.
  21290. * Note: an Aztec symbol should have a minimum of 25% EC words.
  21291. */
  21292. EncodeHintType[EncodeHintType["ERROR_CORRECTION"] = 0] = "ERROR_CORRECTION";
  21293. /**
  21294. * Specifies what character encoding to use where applicable (type {@link String})
  21295. */
  21296. EncodeHintType[EncodeHintType["CHARACTER_SET"] = 1] = "CHARACTER_SET";
  21297. /**
  21298. * Specifies the matrix shape for Data Matrix (type {@link com.google.zxing.datamatrix.encoder.SymbolShapeHint})
  21299. */
  21300. EncodeHintType[EncodeHintType["DATA_MATRIX_SHAPE"] = 2] = "DATA_MATRIX_SHAPE";
  21301. /**
  21302. * Specifies whether to use compact mode for Data Matrix (type {@link Boolean}, or "true" or "false"
  21303. * {@link String } value).
  21304. * The compact encoding mode also supports the encoding of characters that are not in the ISO-8859-1
  21305. * character set via ECIs.
  21306. * Please note that in that case, the most compact character encoding is chosen for characters in
  21307. * the input that are not in the ISO-8859-1 character set. Based on experience, some scanners do not
  21308. * support encodings like cp-1256 (Arabic). In such cases the encoding can be forced to UTF-8 by
  21309. * means of the {@link #CHARACTER_SET} encoding hint.
  21310. * Compact encoding also provides GS1-FNC1 support when {@link #GS1_FORMAT} is selected. In this case
  21311. * group-separator character (ASCII 29 decimal) can be used to encode the positions of FNC1 codewords
  21312. * for the purpose of delimiting AIs.
  21313. * This option and {@link #FORCE_C40} are mutually exclusive.
  21314. */
  21315. EncodeHintType[EncodeHintType["DATA_MATRIX_COMPACT"] = 3] = "DATA_MATRIX_COMPACT";
  21316. /**
  21317. * Specifies a minimum barcode size (type {@link Dimension}). Only applicable to Data Matrix now.
  21318. *
  21319. * @deprecated use width/height params in
  21320. * {@link com.google.zxing.datamatrix.DataMatrixWriter#encode(String, BarcodeFormat, int, int)}
  21321. */
  21322. /*@Deprecated*/
  21323. EncodeHintType[EncodeHintType["MIN_SIZE"] = 4] = "MIN_SIZE";
  21324. /**
  21325. * Specifies a maximum barcode size (type {@link Dimension}). Only applicable to Data Matrix now.
  21326. *
  21327. * @deprecated without replacement
  21328. */
  21329. /*@Deprecated*/
  21330. EncodeHintType[EncodeHintType["MAX_SIZE"] = 5] = "MAX_SIZE";
  21331. /**
  21332. * Specifies margin, in pixels, to use when generating the barcode. The meaning can vary
  21333. * by format; for example it controls margin before and after the barcode horizontally for
  21334. * most 1D formats. (Type {@link Integer}, or {@link String} representation of the integer value).
  21335. */
  21336. EncodeHintType[EncodeHintType["MARGIN"] = 6] = "MARGIN";
  21337. /**
  21338. * Specifies whether to use compact mode for PDF417 (type {@link Boolean}, or "true" or "false"
  21339. * {@link String} value).
  21340. */
  21341. EncodeHintType[EncodeHintType["PDF417_COMPACT"] = 7] = "PDF417_COMPACT";
  21342. /**
  21343. * Specifies what compaction mode to use for PDF417 (type
  21344. * {@link com.google.zxing.pdf417.encoder.Compaction Compaction} or {@link String} value of one of its
  21345. * enum values).
  21346. */
  21347. EncodeHintType[EncodeHintType["PDF417_COMPACTION"] = 8] = "PDF417_COMPACTION";
  21348. /**
  21349. * Specifies the minimum and maximum number of rows and columns for PDF417 (type
  21350. * {@link com.google.zxing.pdf417.encoder.Dimensions Dimensions}).
  21351. */
  21352. EncodeHintType[EncodeHintType["PDF417_DIMENSIONS"] = 9] = "PDF417_DIMENSIONS";
  21353. /**
  21354. * Specifies the required number of layers for an Aztec code.
  21355. * A negative number (-1, -2, -3, -4) specifies a compact Aztec code.
  21356. * 0 indicates to use the minimum number of layers (the default).
  21357. * A positive number (1, 2, .. 32) specifies a normal (non-compact) Aztec code.
  21358. * (Type {@link Integer}, or {@link String} representation of the integer value).
  21359. */
  21360. EncodeHintType[EncodeHintType["AZTEC_LAYERS"] = 10] = "AZTEC_LAYERS";
  21361. /**
  21362. * Specifies the exact version of QR code to be encoded.
  21363. * (Type {@link Integer}, or {@link String} representation of the integer value).
  21364. */
  21365. EncodeHintType[EncodeHintType["QR_VERSION"] = 11] = "QR_VERSION";
  21366. /**
  21367. * Specifies whether the data should be encoded to the GS1 standard (type {@link Boolean}, or "true" or "false"
  21368. * {@link String } value).
  21369. */
  21370. EncodeHintType[EncodeHintType["GS1_FORMAT"] = 12] = "GS1_FORMAT";
  21371. /**
  21372. * Forces C40 encoding for data-matrix (type {@link Boolean}, or "true" or "false") {@link String } value). This
  21373. * option and {@link #DATA_MATRIX_COMPACT} are mutually exclusive.
  21374. */
  21375. EncodeHintType[EncodeHintType["FORCE_C40"] = 13] = "FORCE_C40";
  21376. })(EncodeHintType || (EncodeHintType = {}));
  21377. var EncodeHintType$1 = EncodeHintType;
  21378. /*
  21379. * Copyright 2008 ZXing authors
  21380. *
  21381. * Licensed under the Apache License, Version 2.0 (the "License");
  21382. * you may not use this file except in compliance with the License.
  21383. * You may obtain a copy of the License at
  21384. *
  21385. * http://www.apache.org/licenses/LICENSE-2.0
  21386. *
  21387. * Unless required by applicable law or agreed to in writing, software
  21388. * distributed under the License is distributed on an "AS IS" BASIS,
  21389. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21390. * See the License for the specific language governing permissions and
  21391. * limitations under the License.
  21392. */
  21393. /**
  21394. * <p>Implements Reed-Solomon encoding, as the name implies.</p>
  21395. *
  21396. * @author Sean Owen
  21397. * @author William Rucklidge
  21398. */
  21399. class ReedSolomonEncoder {
  21400. /**
  21401. * A reed solomon error-correcting encoding constructor is created by
  21402. * passing as Galois Field with of size equal to the number of code
  21403. * words (symbols) in the alphabet (the number of values in each
  21404. * element of arrays that are encoded/decoded).
  21405. * @param field A galois field with a number of elements equal to the size
  21406. * of the alphabet of symbols to encode.
  21407. */
  21408. constructor(field) {
  21409. this.field = field;
  21410. this.cachedGenerators = [];
  21411. this.cachedGenerators.push(new GenericGFPoly(field, Int32Array.from([1])));
  21412. }
  21413. buildGenerator(degree /*int*/) {
  21414. const cachedGenerators = this.cachedGenerators;
  21415. if (degree >= cachedGenerators.length) {
  21416. let lastGenerator = cachedGenerators[cachedGenerators.length - 1];
  21417. const field = this.field;
  21418. for (let d = cachedGenerators.length; d <= degree; d++) {
  21419. const nextGenerator = lastGenerator.multiply(new GenericGFPoly(field, Int32Array.from([1, field.exp(d - 1 + field.getGeneratorBase())])));
  21420. cachedGenerators.push(nextGenerator);
  21421. lastGenerator = nextGenerator;
  21422. }
  21423. }
  21424. return cachedGenerators[degree];
  21425. }
  21426. /**
  21427. * <p>Encode a sequence of code words (symbols) using Reed-Solomon to allow decoders
  21428. * to detect and correct errors that may have been introduced when the resulting
  21429. * data is stored or transmitted.</p>
  21430. *
  21431. * @param toEncode array used for both and output. Caller initializes the array with
  21432. * the code words (symbols) to be encoded followed by empty elements allocated to make
  21433. * space for error-correction code words in the encoded output. The array contains
  21434. * the encdoded output when encode returns. Code words are encoded as numbers from
  21435. * 0 to n-1, where n is the number of possible code words (symbols), as determined
  21436. * by the size of the Galois Field passed in the constructor of this object.
  21437. * @param ecBytes the number of elements reserved in the array (first parameter)
  21438. * to store error-correction code words. Thus, the number of code words (symbols)
  21439. * to encode in the first parameter is thus toEncode.length - ecBytes.
  21440. * Note, the use of "bytes" in the name of this parameter is misleading, as there may
  21441. * be more or fewer than 256 symbols being encoded, as determined by the number of
  21442. * elements in the Galois Field passed as a constructor to this object.
  21443. * @throws IllegalArgumentException thrown in response to validation errros.
  21444. */
  21445. encode(toEncode, ecBytes /*int*/) {
  21446. if (ecBytes === 0) {
  21447. throw new IllegalArgumentException('No error correction bytes');
  21448. }
  21449. const dataBytes = toEncode.length - ecBytes;
  21450. if (dataBytes <= 0) {
  21451. throw new IllegalArgumentException('No data bytes provided');
  21452. }
  21453. const generator = this.buildGenerator(ecBytes);
  21454. const infoCoefficients = new Int32Array(dataBytes);
  21455. System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes);
  21456. let info = new GenericGFPoly(this.field, infoCoefficients);
  21457. info = info.multiplyByMonomial(ecBytes, 1);
  21458. const remainder = info.divide(generator)[1];
  21459. const coefficients = remainder.getCoefficients();
  21460. const numZeroCoefficients = ecBytes - coefficients.length;
  21461. for (let i = 0; i < numZeroCoefficients; i++) {
  21462. toEncode[dataBytes + i] = 0;
  21463. }
  21464. System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length);
  21465. }
  21466. }
  21467. /*
  21468. * Copyright 2008 ZXing authors
  21469. *
  21470. * Licensed under the Apache License, Version 2.0 (the "License");
  21471. * you may not use this file except in compliance with the License.
  21472. * You may obtain a copy of the License at
  21473. *
  21474. * http://www.apache.org/licenses/LICENSE-2.0
  21475. *
  21476. * Unless required by applicable law or agreed to in writing, software
  21477. * distributed under the License is distributed on an "AS IS" BASIS,
  21478. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21479. * See the License for the specific language governing permissions and
  21480. * limitations under the License.
  21481. */
  21482. /**
  21483. * @author Satoru Takabayashi
  21484. * @author Daniel Switkin
  21485. * @author Sean Owen
  21486. */
  21487. class MaskUtil {
  21488. constructor() {
  21489. // do nothing
  21490. }
  21491. /**
  21492. * Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and
  21493. * give penalty to them. Example: 00000 or 11111.
  21494. */
  21495. static applyMaskPenaltyRule1(matrix) {
  21496. return MaskUtil.applyMaskPenaltyRule1Internal(matrix, true) + MaskUtil.applyMaskPenaltyRule1Internal(matrix, false);
  21497. }
  21498. /**
  21499. * Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give
  21500. * penalty to them. This is actually equivalent to the spec's rule, which is to find MxN blocks and give a
  21501. * penalty proportional to (M-1)x(N-1), because this is the number of 2x2 blocks inside such a block.
  21502. */
  21503. static applyMaskPenaltyRule2(matrix) {
  21504. let penalty = 0;
  21505. const array = matrix.getArray();
  21506. const width = matrix.getWidth();
  21507. const height = matrix.getHeight();
  21508. for (let y = 0; y < height - 1; y++) {
  21509. const arrayY = array[y];
  21510. for (let x = 0; x < width - 1; x++) {
  21511. const value = arrayY[x];
  21512. if (value === arrayY[x + 1] && value === array[y + 1][x] && value === array[y + 1][x + 1]) {
  21513. penalty++;
  21514. }
  21515. }
  21516. }
  21517. return MaskUtil.N2 * penalty;
  21518. }
  21519. /**
  21520. * Apply mask penalty rule 3 and return the penalty. Find consecutive runs of 1:1:3:1:1:4
  21521. * starting with black, or 4:1:1:3:1:1 starting with white, and give penalty to them. If we
  21522. * find patterns like 000010111010000, we give penalty once.
  21523. */
  21524. static applyMaskPenaltyRule3(matrix) {
  21525. let numPenalties = 0;
  21526. const array = matrix.getArray();
  21527. const width = matrix.getWidth();
  21528. const height = matrix.getHeight();
  21529. for (let y = 0; y < height; y++) {
  21530. for (let x = 0; x < width; x++) {
  21531. const arrayY = array[y]; // We can at least optimize this access
  21532. if (x + 6 < width &&
  21533. arrayY[x] === 1 &&
  21534. arrayY[x + 1] === 0 &&
  21535. arrayY[x + 2] === 1 &&
  21536. arrayY[x + 3] === 1 &&
  21537. arrayY[x + 4] === 1 &&
  21538. arrayY[x + 5] === 0 &&
  21539. arrayY[x + 6] === 1 &&
  21540. (MaskUtil.isWhiteHorizontal(arrayY, x - 4, x) || MaskUtil.isWhiteHorizontal(arrayY, x + 7, x + 11))) {
  21541. numPenalties++;
  21542. }
  21543. if (y + 6 < height &&
  21544. array[y][x] === 1 &&
  21545. array[y + 1][x] === 0 &&
  21546. array[y + 2][x] === 1 &&
  21547. array[y + 3][x] === 1 &&
  21548. array[y + 4][x] === 1 &&
  21549. array[y + 5][x] === 0 &&
  21550. array[y + 6][x] === 1 &&
  21551. (MaskUtil.isWhiteVertical(array, x, y - 4, y) || MaskUtil.isWhiteVertical(array, x, y + 7, y + 11))) {
  21552. numPenalties++;
  21553. }
  21554. }
  21555. }
  21556. return numPenalties * MaskUtil.N3;
  21557. }
  21558. static isWhiteHorizontal(rowArray, from /*int*/, to /*int*/) {
  21559. from = Math.max(from, 0);
  21560. to = Math.min(to, rowArray.length);
  21561. for (let i = from; i < to; i++) {
  21562. if (rowArray[i] === 1) {
  21563. return false;
  21564. }
  21565. }
  21566. return true;
  21567. }
  21568. static isWhiteVertical(array, col /*int*/, from /*int*/, to /*int*/) {
  21569. from = Math.max(from, 0);
  21570. to = Math.min(to, array.length);
  21571. for (let i = from; i < to; i++) {
  21572. if (array[i][col] === 1) {
  21573. return false;
  21574. }
  21575. }
  21576. return true;
  21577. }
  21578. /**
  21579. * Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give
  21580. * penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance.
  21581. */
  21582. static applyMaskPenaltyRule4(matrix) {
  21583. let numDarkCells = 0;
  21584. const array = matrix.getArray();
  21585. const width = matrix.getWidth();
  21586. const height = matrix.getHeight();
  21587. for (let y = 0; y < height; y++) {
  21588. const arrayY = array[y];
  21589. for (let x = 0; x < width; x++) {
  21590. if (arrayY[x] === 1) {
  21591. numDarkCells++;
  21592. }
  21593. }
  21594. }
  21595. const numTotalCells = matrix.getHeight() * matrix.getWidth();
  21596. const fivePercentVariances = Math.floor(Math.abs(numDarkCells * 2 - numTotalCells) * 10 / numTotalCells);
  21597. return fivePercentVariances * MaskUtil.N4;
  21598. }
  21599. /**
  21600. * Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
  21601. * pattern conditions.
  21602. */
  21603. static getDataMaskBit(maskPattern /*int*/, x /*int*/, y /*int*/) {
  21604. let intermediate; /*int*/
  21605. let temp; /*int*/
  21606. switch (maskPattern) {
  21607. case 0:
  21608. intermediate = (y + x) & 0x1;
  21609. break;
  21610. case 1:
  21611. intermediate = y & 0x1;
  21612. break;
  21613. case 2:
  21614. intermediate = x % 3;
  21615. break;
  21616. case 3:
  21617. intermediate = (y + x) % 3;
  21618. break;
  21619. case 4:
  21620. intermediate = (Math.floor(y / 2) + Math.floor(x / 3)) & 0x1;
  21621. break;
  21622. case 5:
  21623. temp = y * x;
  21624. intermediate = (temp & 0x1) + (temp % 3);
  21625. break;
  21626. case 6:
  21627. temp = y * x;
  21628. intermediate = ((temp & 0x1) + (temp % 3)) & 0x1;
  21629. break;
  21630. case 7:
  21631. temp = y * x;
  21632. intermediate = ((temp % 3) + ((y + x) & 0x1)) & 0x1;
  21633. break;
  21634. default:
  21635. throw new IllegalArgumentException('Invalid mask pattern: ' + maskPattern);
  21636. }
  21637. return intermediate === 0;
  21638. }
  21639. /**
  21640. * Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both
  21641. * vertical and horizontal orders respectively.
  21642. */
  21643. static applyMaskPenaltyRule1Internal(matrix, isHorizontal) {
  21644. let penalty = 0;
  21645. const iLimit = isHorizontal ? matrix.getHeight() : matrix.getWidth();
  21646. const jLimit = isHorizontal ? matrix.getWidth() : matrix.getHeight();
  21647. const array = matrix.getArray();
  21648. for (let i = 0; i < iLimit; i++) {
  21649. let numSameBitCells = 0;
  21650. let prevBit = -1;
  21651. for (let j = 0; j < jLimit; j++) {
  21652. const bit = isHorizontal ? array[i][j] : array[j][i];
  21653. if (bit === prevBit) {
  21654. numSameBitCells++;
  21655. }
  21656. else {
  21657. if (numSameBitCells >= 5) {
  21658. penalty += MaskUtil.N1 + (numSameBitCells - 5);
  21659. }
  21660. numSameBitCells = 1; // Include the cell itself.
  21661. prevBit = bit;
  21662. }
  21663. }
  21664. if (numSameBitCells >= 5) {
  21665. penalty += MaskUtil.N1 + (numSameBitCells - 5);
  21666. }
  21667. }
  21668. return penalty;
  21669. }
  21670. }
  21671. // Penalty weights from section 6.8.2.1
  21672. MaskUtil.N1 = 3;
  21673. MaskUtil.N2 = 3;
  21674. MaskUtil.N3 = 40;
  21675. MaskUtil.N4 = 10;
  21676. /*
  21677. * Copyright 2008 ZXing authors
  21678. *
  21679. * Licensed under the Apache License, Version 2.0 (the "License");
  21680. * you may not use this file except in compliance with the License.
  21681. * You may obtain a copy of the License at
  21682. *
  21683. * http://www.apache.org/licenses/LICENSE-2.0
  21684. *
  21685. * Unless required by applicable law or agreed to in writing, software
  21686. * distributed under the License is distributed on an "AS IS" BASIS,
  21687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21688. * See the License for the specific language governing permissions and
  21689. * limitations under the License.
  21690. */
  21691. /**
  21692. * JAVAPORT: The original code was a 2D array of ints, but since it only ever gets assigned
  21693. * -1, 0, and 1, I'm going to use less memory and go with bytes.
  21694. *
  21695. * @author dswitkin@google.com (Daniel Switkin)
  21696. */
  21697. class ByteMatrix {
  21698. constructor(width /*int*/, height /*int*/) {
  21699. this.width = width;
  21700. this.height = height;
  21701. const bytes = new Array(height); // [height][width]
  21702. for (let i = 0; i !== height; i++) {
  21703. bytes[i] = new Uint8Array(width);
  21704. }
  21705. this.bytes = bytes;
  21706. }
  21707. getHeight() {
  21708. return this.height;
  21709. }
  21710. getWidth() {
  21711. return this.width;
  21712. }
  21713. get(x /*int*/, y /*int*/) {
  21714. return this.bytes[y][x];
  21715. }
  21716. /**
  21717. * @return an internal representation as bytes, in row-major order. array[y][x] represents point (x,y)
  21718. */
  21719. getArray() {
  21720. return this.bytes;
  21721. }
  21722. // TYPESCRIPTPORT: preffer to let two methods instead of override to avoid type comparison inside
  21723. setNumber(x /*int*/, y /*int*/, value /*byte|int*/) {
  21724. this.bytes[y][x] = value;
  21725. }
  21726. // public set(x: number /*int*/, y: number /*int*/, value: number /*int*/): void {
  21727. // bytes[y][x] = (byte) value
  21728. // }
  21729. setBoolean(x /*int*/, y /*int*/, value) {
  21730. this.bytes[y][x] = /*(byte) */ (value ? 1 : 0);
  21731. }
  21732. clear(value /*byte*/) {
  21733. for (const aByte of this.bytes) {
  21734. Arrays.fill(aByte, value);
  21735. }
  21736. }
  21737. equals(o) {
  21738. if (!(o instanceof ByteMatrix)) {
  21739. return false;
  21740. }
  21741. const other = o;
  21742. if (this.width !== other.width) {
  21743. return false;
  21744. }
  21745. if (this.height !== other.height) {
  21746. return false;
  21747. }
  21748. for (let y = 0, height = this.height; y < height; ++y) {
  21749. const bytesY = this.bytes[y];
  21750. const otherBytesY = other.bytes[y];
  21751. for (let x = 0, width = this.width; x < width; ++x) {
  21752. if (bytesY[x] !== otherBytesY[x]) {
  21753. return false;
  21754. }
  21755. }
  21756. }
  21757. return true;
  21758. }
  21759. /*@Override*/
  21760. toString() {
  21761. const result = new StringBuilder(); // (2 * width * height + 2)
  21762. for (let y = 0, height = this.height; y < height; ++y) {
  21763. const bytesY = this.bytes[y];
  21764. for (let x = 0, width = this.width; x < width; ++x) {
  21765. switch (bytesY[x]) {
  21766. case 0:
  21767. result.append(' 0');
  21768. break;
  21769. case 1:
  21770. result.append(' 1');
  21771. break;
  21772. default:
  21773. result.append(' ');
  21774. break;
  21775. }
  21776. }
  21777. result.append('\n');
  21778. }
  21779. return result.toString();
  21780. }
  21781. }
  21782. /*
  21783. * Copyright 2008 ZXing authors
  21784. *
  21785. * Licensed under the Apache License, Version 2.0 (the "License");
  21786. * you may not use this file except in compliance with the License.
  21787. * You may obtain a copy of the License at
  21788. *
  21789. * http://www.apache.org/licenses/LICENSE-2.0
  21790. *
  21791. * Unless required by applicable law or agreed to in writing, software
  21792. * distributed under the License is distributed on an "AS IS" BASIS,
  21793. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21794. * See the License for the specific language governing permissions and
  21795. * limitations under the License.
  21796. */
  21797. /**
  21798. * @author satorux@google.com (Satoru Takabayashi) - creator
  21799. * @author dswitkin@google.com (Daniel Switkin) - ported from C++
  21800. */
  21801. class QRCode {
  21802. constructor() {
  21803. this.maskPattern = -1;
  21804. }
  21805. getMode() {
  21806. return this.mode;
  21807. }
  21808. getECLevel() {
  21809. return this.ecLevel;
  21810. }
  21811. getVersion() {
  21812. return this.version;
  21813. }
  21814. getMaskPattern() {
  21815. return this.maskPattern;
  21816. }
  21817. getMatrix() {
  21818. return this.matrix;
  21819. }
  21820. /*@Override*/
  21821. toString() {
  21822. const result = new StringBuilder(); // (200)
  21823. result.append('<<\n');
  21824. result.append(' mode: ');
  21825. result.append(this.mode ? this.mode.toString() : 'null');
  21826. result.append('\n ecLevel: ');
  21827. result.append(this.ecLevel ? this.ecLevel.toString() : 'null');
  21828. result.append('\n version: ');
  21829. result.append(this.version ? this.version.toString() : 'null');
  21830. result.append('\n maskPattern: ');
  21831. result.append(this.maskPattern.toString());
  21832. if (this.matrix) {
  21833. result.append('\n matrix:\n');
  21834. result.append(this.matrix.toString());
  21835. }
  21836. else {
  21837. result.append('\n matrix: null\n');
  21838. }
  21839. result.append('>>\n');
  21840. return result.toString();
  21841. }
  21842. setMode(value) {
  21843. this.mode = value;
  21844. }
  21845. setECLevel(value) {
  21846. this.ecLevel = value;
  21847. }
  21848. setVersion(version) {
  21849. this.version = version;
  21850. }
  21851. setMaskPattern(value /*int*/) {
  21852. this.maskPattern = value;
  21853. }
  21854. setMatrix(value) {
  21855. this.matrix = value;
  21856. }
  21857. // Check if "mask_pattern" is valid.
  21858. static isValidMaskPattern(maskPattern /*int*/) {
  21859. return maskPattern >= 0 && maskPattern < QRCode.NUM_MASK_PATTERNS;
  21860. }
  21861. }
  21862. QRCode.NUM_MASK_PATTERNS = 8;
  21863. /**
  21864. * Custom Error class of type Exception.
  21865. */
  21866. class WriterException extends Exception {
  21867. }
  21868. WriterException.kind = 'WriterException';
  21869. /*
  21870. * Copyright 2008 ZXing authors
  21871. *
  21872. * Licensed under the Apache License, Version 2.0 (the "License");
  21873. * you may not use this file except in compliance with the License.
  21874. * You may obtain a copy of the License at
  21875. *
  21876. * http://www.apache.org/licenses/LICENSE-2.0
  21877. *
  21878. * Unless required by applicable law or agreed to in writing, software
  21879. * distributed under the License is distributed on an "AS IS" BASIS,
  21880. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21881. * See the License for the specific language governing permissions and
  21882. * limitations under the License.
  21883. */
  21884. /**
  21885. * @author satorux@google.com (Satoru Takabayashi) - creator
  21886. * @author dswitkin@google.com (Daniel Switkin) - ported from C++
  21887. */
  21888. class MatrixUtil {
  21889. constructor() {
  21890. // do nothing
  21891. }
  21892. // Set all cells to -1 (TYPESCRIPTPORT: 255). -1 (TYPESCRIPTPORT: 255) means that the cell is empty (not set yet).
  21893. //
  21894. // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding
  21895. // with the ByteMatrix initialized all to zero.
  21896. static clearMatrix(matrix) {
  21897. // TYPESCRIPTPORT: we use UintArray se changed here from -1 to 255
  21898. matrix.clear(/*(byte) */ /*-1*/ 255);
  21899. }
  21900. // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
  21901. // success, store the result in "matrix" and return true.
  21902. static buildMatrix(dataBits, ecLevel, version, maskPattern /*int*/, matrix) {
  21903. MatrixUtil.clearMatrix(matrix);
  21904. MatrixUtil.embedBasicPatterns(version, matrix);
  21905. // Type information appear with any version.
  21906. MatrixUtil.embedTypeInfo(ecLevel, maskPattern, matrix);
  21907. // Version info appear if version >= 7.
  21908. MatrixUtil.maybeEmbedVersionInfo(version, matrix);
  21909. // Data should be embedded at end.
  21910. MatrixUtil.embedDataBits(dataBits, maskPattern, matrix);
  21911. }
  21912. // Embed basic patterns. On success, modify the matrix and return true.
  21913. // The basic patterns are:
  21914. // - Position detection patterns
  21915. // - Timing patterns
  21916. // - Dark dot at the left bottom corner
  21917. // - Position adjustment patterns, if need be
  21918. static embedBasicPatterns(version, matrix) {
  21919. // Let's get started with embedding big squares at corners.
  21920. MatrixUtil.embedPositionDetectionPatternsAndSeparators(matrix);
  21921. // Then, embed the dark dot at the left bottom corner.
  21922. MatrixUtil.embedDarkDotAtLeftBottomCorner(matrix);
  21923. // Position adjustment patterns appear if version >= 2.
  21924. MatrixUtil.maybeEmbedPositionAdjustmentPatterns(version, matrix);
  21925. // Timing patterns should be embedded after position adj. patterns.
  21926. MatrixUtil.embedTimingPatterns(matrix);
  21927. }
  21928. // Embed type information. On success, modify the matrix.
  21929. static embedTypeInfo(ecLevel, maskPattern /*int*/, matrix) {
  21930. const typeInfoBits = new BitArray();
  21931. MatrixUtil.makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits);
  21932. for (let i = 0, size = typeInfoBits.getSize(); i < size; ++i) {
  21933. // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
  21934. // "typeInfoBits".
  21935. const bit = typeInfoBits.get(typeInfoBits.getSize() - 1 - i);
  21936. // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
  21937. const coordinates = MatrixUtil.TYPE_INFO_COORDINATES[i];
  21938. const x1 = coordinates[0];
  21939. const y1 = coordinates[1];
  21940. matrix.setBoolean(x1, y1, bit);
  21941. if (i < 8) {
  21942. // Right top corner.
  21943. const x2 = matrix.getWidth() - i - 1;
  21944. const y2 = 8;
  21945. matrix.setBoolean(x2, y2, bit);
  21946. }
  21947. else {
  21948. // Left bottom corner.
  21949. const x2 = 8;
  21950. const y2 = matrix.getHeight() - 7 + (i - 8);
  21951. matrix.setBoolean(x2, y2, bit);
  21952. }
  21953. }
  21954. }
  21955. // Embed version information if need be. On success, modify the matrix and return true.
  21956. // See 8.10 of JISX0510:2004 (p.47) for how to embed version information.
  21957. static maybeEmbedVersionInfo(version, matrix) {
  21958. if (version.getVersionNumber() < 7) { // Version info is necessary if version >= 7.
  21959. return; // Don't need version info.
  21960. }
  21961. const versionInfoBits = new BitArray();
  21962. MatrixUtil.makeVersionInfoBits(version, versionInfoBits);
  21963. let bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0.
  21964. for (let i = 0; i < 6; ++i) {
  21965. for (let j = 0; j < 3; ++j) {
  21966. // Place bits in LSB (least significant bit) to MSB order.
  21967. const bit = versionInfoBits.get(bitIndex);
  21968. bitIndex--;
  21969. // Left bottom corner.
  21970. matrix.setBoolean(i, matrix.getHeight() - 11 + j, bit);
  21971. // Right bottom corner.
  21972. matrix.setBoolean(matrix.getHeight() - 11 + j, i, bit);
  21973. }
  21974. }
  21975. }
  21976. // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true.
  21977. // For debugging purposes, it skips masking process if "getMaskPattern" is -1(TYPESCRIPTPORT: 255).
  21978. // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
  21979. static embedDataBits(dataBits, maskPattern /*int*/, matrix) {
  21980. let bitIndex = 0;
  21981. let direction = -1;
  21982. // Start from the right bottom cell.
  21983. let x = matrix.getWidth() - 1;
  21984. let y = matrix.getHeight() - 1;
  21985. while (x > 0) {
  21986. // Skip the vertical timing pattern.
  21987. if (x === 6) {
  21988. x -= 1;
  21989. }
  21990. while (y >= 0 && y < matrix.getHeight()) {
  21991. for (let i = 0; i < 2; ++i) {
  21992. const xx = x - i;
  21993. // Skip the cell if it's not empty.
  21994. if (!MatrixUtil.isEmpty(matrix.get(xx, y))) {
  21995. continue;
  21996. }
  21997. let bit;
  21998. if (bitIndex < dataBits.getSize()) {
  21999. bit = dataBits.get(bitIndex);
  22000. ++bitIndex;
  22001. }
  22002. else {
  22003. // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
  22004. // in 8.4.9 of JISX0510:2004 (p. 24).
  22005. bit = false;
  22006. }
  22007. // Skip masking if mask_pattern is -1 (TYPESCRIPTPORT: 255).
  22008. if (maskPattern !== 255 && MaskUtil.getDataMaskBit(maskPattern, xx, y)) {
  22009. bit = !bit;
  22010. }
  22011. matrix.setBoolean(xx, y, bit);
  22012. }
  22013. y += direction;
  22014. }
  22015. direction = -direction; // Reverse the direction.
  22016. y += direction;
  22017. x -= 2; // Move to the left.
  22018. }
  22019. // All bits should be consumed.
  22020. if (bitIndex !== dataBits.getSize()) {
  22021. throw new WriterException('Not all bits consumed: ' + bitIndex + '/' + dataBits.getSize());
  22022. }
  22023. }
  22024. // Return the position of the most significant bit set (one: to) in the "value". The most
  22025. // significant bit is position 32. If there is no bit set, return 0. Examples:
  22026. // - findMSBSet(0) => 0
  22027. // - findMSBSet(1) => 1
  22028. // - findMSBSet(255) => 8
  22029. static findMSBSet(value /*int*/) {
  22030. return 32 - Integer.numberOfLeadingZeros(value);
  22031. }
  22032. // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
  22033. // code is used for encoding type information and version information.
  22034. // Example: Calculation of version information of 7.
  22035. // f(x) is created from 7.
  22036. // - 7 = 000111 in 6 bits
  22037. // - f(x) = x^2 + x^1 + x^0
  22038. // g(x) is given by the standard (p. 67)
  22039. // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
  22040. // Multiply f(x) by x^(18 - 6)
  22041. // - f'(x) = f(x) * x^(18 - 6)
  22042. // - f'(x) = x^14 + x^13 + x^12
  22043. // Calculate the remainder of f'(x) / g(x)
  22044. // x^2
  22045. // __________________________________________________
  22046. // g(x) )x^14 + x^13 + x^12
  22047. // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
  22048. // --------------------------------------------------
  22049. // x^11 + x^10 + x^7 + x^4 + x^2
  22050. //
  22051. // The remainder is x^11 + x^10 + x^7 + x^4 + x^2
  22052. // Encode it in binary: 110010010100
  22053. // The return value is 0xc94 (1100 1001 0100)
  22054. //
  22055. // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
  22056. // operations. We don't care if coefficients are positive or negative.
  22057. static calculateBCHCode(value /*int*/, poly /*int*/) {
  22058. if (poly === 0) {
  22059. throw new IllegalArgumentException('0 polynomial');
  22060. }
  22061. // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
  22062. // from 13 to make it 12.
  22063. const msbSetInPoly = MatrixUtil.findMSBSet(poly);
  22064. value <<= msbSetInPoly - 1;
  22065. // Do the division business using exclusive-or operations.
  22066. while (MatrixUtil.findMSBSet(value) >= msbSetInPoly) {
  22067. value ^= poly << (MatrixUtil.findMSBSet(value) - msbSetInPoly);
  22068. }
  22069. // Now the "value" is the remainder (i.e. the BCH code)
  22070. return value;
  22071. }
  22072. // Make bit vector of type information. On success, store the result in "bits" and return true.
  22073. // Encode error correction level and mask pattern. See 8.9 of
  22074. // JISX0510:2004 (p.45) for details.
  22075. static makeTypeInfoBits(ecLevel, maskPattern /*int*/, bits) {
  22076. if (!QRCode.isValidMaskPattern(maskPattern)) {
  22077. throw new WriterException('Invalid mask pattern');
  22078. }
  22079. const typeInfo = (ecLevel.getBits() << 3) | maskPattern;
  22080. bits.appendBits(typeInfo, 5);
  22081. const bchCode = MatrixUtil.calculateBCHCode(typeInfo, MatrixUtil.TYPE_INFO_POLY);
  22082. bits.appendBits(bchCode, 10);
  22083. const maskBits = new BitArray();
  22084. maskBits.appendBits(MatrixUtil.TYPE_INFO_MASK_PATTERN, 15);
  22085. bits.xor(maskBits);
  22086. if (bits.getSize() !== 15) { // Just in case.
  22087. throw new WriterException('should not happen but we got: ' + bits.getSize());
  22088. }
  22089. }
  22090. // Make bit vector of version information. On success, store the result in "bits" and return true.
  22091. // See 8.10 of JISX0510:2004 (p.45) for details.
  22092. static makeVersionInfoBits(version, bits) {
  22093. bits.appendBits(version.getVersionNumber(), 6);
  22094. const bchCode = MatrixUtil.calculateBCHCode(version.getVersionNumber(), MatrixUtil.VERSION_INFO_POLY);
  22095. bits.appendBits(bchCode, 12);
  22096. if (bits.getSize() !== 18) { // Just in case.
  22097. throw new WriterException('should not happen but we got: ' + bits.getSize());
  22098. }
  22099. }
  22100. // Check if "value" is empty.
  22101. static isEmpty(value /*int*/) {
  22102. return value === 255; // -1
  22103. }
  22104. static embedTimingPatterns(matrix) {
  22105. // -8 is for skipping position detection patterns (7: size), and two horizontal/vertical
  22106. // separation patterns (1: size). Thus, 8 = 7 + 1.
  22107. for (let i = 8; i < matrix.getWidth() - 8; ++i) {
  22108. const bit = (i + 1) % 2;
  22109. // Horizontal line.
  22110. if (MatrixUtil.isEmpty(matrix.get(i, 6))) {
  22111. matrix.setNumber(i, 6, bit);
  22112. }
  22113. // Vertical line.
  22114. if (MatrixUtil.isEmpty(matrix.get(6, i))) {
  22115. matrix.setNumber(6, i, bit);
  22116. }
  22117. }
  22118. }
  22119. // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
  22120. static embedDarkDotAtLeftBottomCorner(matrix) {
  22121. if (matrix.get(8, matrix.getHeight() - 8) === 0) {
  22122. throw new WriterException();
  22123. }
  22124. matrix.setNumber(8, matrix.getHeight() - 8, 1);
  22125. }
  22126. static embedHorizontalSeparationPattern(xStart /*int*/, yStart /*int*/, matrix) {
  22127. for (let x = 0; x < 8; ++x) {
  22128. if (!MatrixUtil.isEmpty(matrix.get(xStart + x, yStart))) {
  22129. throw new WriterException();
  22130. }
  22131. matrix.setNumber(xStart + x, yStart, 0);
  22132. }
  22133. }
  22134. static embedVerticalSeparationPattern(xStart /*int*/, yStart /*int*/, matrix) {
  22135. for (let y = 0; y < 7; ++y) {
  22136. if (!MatrixUtil.isEmpty(matrix.get(xStart, yStart + y))) {
  22137. throw new WriterException();
  22138. }
  22139. matrix.setNumber(xStart, yStart + y, 0);
  22140. }
  22141. }
  22142. static embedPositionAdjustmentPattern(xStart /*int*/, yStart /*int*/, matrix) {
  22143. for (let y = 0; y < 5; ++y) {
  22144. const patternY = MatrixUtil.POSITION_ADJUSTMENT_PATTERN[y];
  22145. for (let x = 0; x < 5; ++x) {
  22146. matrix.setNumber(xStart + x, yStart + y, patternY[x]);
  22147. }
  22148. }
  22149. }
  22150. static embedPositionDetectionPattern(xStart /*int*/, yStart /*int*/, matrix) {
  22151. for (let y = 0; y < 7; ++y) {
  22152. const patternY = MatrixUtil.POSITION_DETECTION_PATTERN[y];
  22153. for (let x = 0; x < 7; ++x) {
  22154. matrix.setNumber(xStart + x, yStart + y, patternY[x]);
  22155. }
  22156. }
  22157. }
  22158. // Embed position detection patterns and surrounding vertical/horizontal separators.
  22159. static embedPositionDetectionPatternsAndSeparators(matrix) {
  22160. // Embed three big squares at corners.
  22161. const pdpWidth = MatrixUtil.POSITION_DETECTION_PATTERN[0].length;
  22162. // Left top corner.
  22163. MatrixUtil.embedPositionDetectionPattern(0, 0, matrix);
  22164. // Right top corner.
  22165. MatrixUtil.embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix);
  22166. // Left bottom corner.
  22167. MatrixUtil.embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix);
  22168. // Embed horizontal separation patterns around the squares.
  22169. const hspWidth = 8;
  22170. // Left top corner.
  22171. MatrixUtil.embedHorizontalSeparationPattern(0, hspWidth - 1, matrix);
  22172. // Right top corner.
  22173. MatrixUtil.embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, hspWidth - 1, matrix);
  22174. // Left bottom corner.
  22175. MatrixUtil.embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix);
  22176. // Embed vertical separation patterns around the squares.
  22177. const vspSize = 7;
  22178. // Left top corner.
  22179. MatrixUtil.embedVerticalSeparationPattern(vspSize, 0, matrix);
  22180. // Right top corner.
  22181. MatrixUtil.embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix);
  22182. // Left bottom corner.
  22183. MatrixUtil.embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, matrix);
  22184. }
  22185. // Embed position adjustment patterns if need be.
  22186. static maybeEmbedPositionAdjustmentPatterns(version, matrix) {
  22187. if (version.getVersionNumber() < 2) { // The patterns appear if version >= 2
  22188. return;
  22189. }
  22190. const index = version.getVersionNumber() - 1;
  22191. const coordinates = MatrixUtil.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index];
  22192. for (let i = 0, length = coordinates.length; i !== length; i++) {
  22193. const y = coordinates[i];
  22194. if (y >= 0) {
  22195. for (let j = 0; j !== length; j++) {
  22196. const x = coordinates[j];
  22197. if (x >= 0 && MatrixUtil.isEmpty(matrix.get(x, y))) {
  22198. // If the cell is unset, we embed the position adjustment pattern here.
  22199. // -2 is necessary since the x/y coordinates point to the center of the pattern, not the
  22200. // left top corner.
  22201. MatrixUtil.embedPositionAdjustmentPattern(x - 2, y - 2, matrix);
  22202. }
  22203. }
  22204. }
  22205. }
  22206. }
  22207. }
  22208. MatrixUtil.POSITION_DETECTION_PATTERN = Array.from([
  22209. Int32Array.from([1, 1, 1, 1, 1, 1, 1]),
  22210. Int32Array.from([1, 0, 0, 0, 0, 0, 1]),
  22211. Int32Array.from([1, 0, 1, 1, 1, 0, 1]),
  22212. Int32Array.from([1, 0, 1, 1, 1, 0, 1]),
  22213. Int32Array.from([1, 0, 1, 1, 1, 0, 1]),
  22214. Int32Array.from([1, 0, 0, 0, 0, 0, 1]),
  22215. Int32Array.from([1, 1, 1, 1, 1, 1, 1]),
  22216. ]);
  22217. MatrixUtil.POSITION_ADJUSTMENT_PATTERN = Array.from([
  22218. Int32Array.from([1, 1, 1, 1, 1]),
  22219. Int32Array.from([1, 0, 0, 0, 1]),
  22220. Int32Array.from([1, 0, 1, 0, 1]),
  22221. Int32Array.from([1, 0, 0, 0, 1]),
  22222. Int32Array.from([1, 1, 1, 1, 1]),
  22223. ]);
  22224. // From Appendix E. Table 1, JIS0510X:2004 (71: p). The table was double-checked by komatsu.
  22225. MatrixUtil.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = Array.from([
  22226. Int32Array.from([-1, -1, -1, -1, -1, -1, -1]),
  22227. Int32Array.from([6, 18, -1, -1, -1, -1, -1]),
  22228. Int32Array.from([6, 22, -1, -1, -1, -1, -1]),
  22229. Int32Array.from([6, 26, -1, -1, -1, -1, -1]),
  22230. Int32Array.from([6, 30, -1, -1, -1, -1, -1]),
  22231. Int32Array.from([6, 34, -1, -1, -1, -1, -1]),
  22232. Int32Array.from([6, 22, 38, -1, -1, -1, -1]),
  22233. Int32Array.from([6, 24, 42, -1, -1, -1, -1]),
  22234. Int32Array.from([6, 26, 46, -1, -1, -1, -1]),
  22235. Int32Array.from([6, 28, 50, -1, -1, -1, -1]),
  22236. Int32Array.from([6, 30, 54, -1, -1, -1, -1]),
  22237. Int32Array.from([6, 32, 58, -1, -1, -1, -1]),
  22238. Int32Array.from([6, 34, 62, -1, -1, -1, -1]),
  22239. Int32Array.from([6, 26, 46, 66, -1, -1, -1]),
  22240. Int32Array.from([6, 26, 48, 70, -1, -1, -1]),
  22241. Int32Array.from([6, 26, 50, 74, -1, -1, -1]),
  22242. Int32Array.from([6, 30, 54, 78, -1, -1, -1]),
  22243. Int32Array.from([6, 30, 56, 82, -1, -1, -1]),
  22244. Int32Array.from([6, 30, 58, 86, -1, -1, -1]),
  22245. Int32Array.from([6, 34, 62, 90, -1, -1, -1]),
  22246. Int32Array.from([6, 28, 50, 72, 94, -1, -1]),
  22247. Int32Array.from([6, 26, 50, 74, 98, -1, -1]),
  22248. Int32Array.from([6, 30, 54, 78, 102, -1, -1]),
  22249. Int32Array.from([6, 28, 54, 80, 106, -1, -1]),
  22250. Int32Array.from([6, 32, 58, 84, 110, -1, -1]),
  22251. Int32Array.from([6, 30, 58, 86, 114, -1, -1]),
  22252. Int32Array.from([6, 34, 62, 90, 118, -1, -1]),
  22253. Int32Array.from([6, 26, 50, 74, 98, 122, -1]),
  22254. Int32Array.from([6, 30, 54, 78, 102, 126, -1]),
  22255. Int32Array.from([6, 26, 52, 78, 104, 130, -1]),
  22256. Int32Array.from([6, 30, 56, 82, 108, 134, -1]),
  22257. Int32Array.from([6, 34, 60, 86, 112, 138, -1]),
  22258. Int32Array.from([6, 30, 58, 86, 114, 142, -1]),
  22259. Int32Array.from([6, 34, 62, 90, 118, 146, -1]),
  22260. Int32Array.from([6, 30, 54, 78, 102, 126, 150]),
  22261. Int32Array.from([6, 24, 50, 76, 102, 128, 154]),
  22262. Int32Array.from([6, 28, 54, 80, 106, 132, 158]),
  22263. Int32Array.from([6, 32, 58, 84, 110, 136, 162]),
  22264. Int32Array.from([6, 26, 54, 82, 110, 138, 166]),
  22265. Int32Array.from([6, 30, 58, 86, 114, 142, 170]),
  22266. ]);
  22267. // Type info cells at the left top corner.
  22268. MatrixUtil.TYPE_INFO_COORDINATES = Array.from([
  22269. Int32Array.from([8, 0]),
  22270. Int32Array.from([8, 1]),
  22271. Int32Array.from([8, 2]),
  22272. Int32Array.from([8, 3]),
  22273. Int32Array.from([8, 4]),
  22274. Int32Array.from([8, 5]),
  22275. Int32Array.from([8, 7]),
  22276. Int32Array.from([8, 8]),
  22277. Int32Array.from([7, 8]),
  22278. Int32Array.from([5, 8]),
  22279. Int32Array.from([4, 8]),
  22280. Int32Array.from([3, 8]),
  22281. Int32Array.from([2, 8]),
  22282. Int32Array.from([1, 8]),
  22283. Int32Array.from([0, 8]),
  22284. ]);
  22285. // From Appendix D in JISX0510:2004 (p. 67)
  22286. MatrixUtil.VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101
  22287. // From Appendix C in JISX0510:2004 (p.65).
  22288. MatrixUtil.TYPE_INFO_POLY = 0x537;
  22289. MatrixUtil.TYPE_INFO_MASK_PATTERN = 0x5412;
  22290. /*
  22291. * Copyright 2008 ZXing authors
  22292. *
  22293. * Licensed under the Apache License, Version 2.0 (the "License");
  22294. * you may not use this file except in compliance with the License.
  22295. * You may obtain a copy of the License at
  22296. *
  22297. * http://www.apache.org/licenses/LICENSE-2.0
  22298. *
  22299. * Unless required by applicable law or agreed to in writing, software
  22300. * distributed under the License is distributed on an "AS IS" BASIS,
  22301. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22302. * See the License for the specific language governing permissions and
  22303. * limitations under the License.
  22304. */
  22305. /*namespace com.google.zxing.qrcode.encoder {*/
  22306. class BlockPair {
  22307. constructor(dataBytes, errorCorrectionBytes) {
  22308. this.dataBytes = dataBytes;
  22309. this.errorCorrectionBytes = errorCorrectionBytes;
  22310. }
  22311. getDataBytes() {
  22312. return this.dataBytes;
  22313. }
  22314. getErrorCorrectionBytes() {
  22315. return this.errorCorrectionBytes;
  22316. }
  22317. }
  22318. /*
  22319. * Copyright 2008 ZXing authors
  22320. *
  22321. * Licensed under the Apache License, Version 2.0 (the "License");
  22322. * you may not use this file except in compliance with the License.
  22323. * You may obtain a copy of the License at
  22324. *
  22325. * http://www.apache.org/licenses/LICENSE-2.0
  22326. *
  22327. * Unless required by applicable law or agreed to in writing, software
  22328. * distributed under the License is distributed on an "AS IS" BASIS,
  22329. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22330. * See the License for the specific language governing permissions and
  22331. * limitations under the License.
  22332. */
  22333. /*import java.io.UnsupportedEncodingException;*/
  22334. /*import java.util.ArrayList;*/
  22335. /*import java.util.Collection;*/
  22336. /*import java.util.Map;*/
  22337. /**
  22338. * @author satorux@google.com (Satoru Takabayashi) - creator
  22339. * @author dswitkin@google.com (Daniel Switkin) - ported from C++
  22340. */
  22341. class Encoder {
  22342. // TYPESCRIPTPORT: changed to UTF8, the default for js
  22343. constructor() { }
  22344. // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.
  22345. // Basically it applies four rules and summate all penalties.
  22346. static calculateMaskPenalty(matrix) {
  22347. return MaskUtil.applyMaskPenaltyRule1(matrix)
  22348. + MaskUtil.applyMaskPenaltyRule2(matrix)
  22349. + MaskUtil.applyMaskPenaltyRule3(matrix)
  22350. + MaskUtil.applyMaskPenaltyRule4(matrix);
  22351. }
  22352. /**
  22353. * @param content text to encode
  22354. * @param ecLevel error correction level to use
  22355. * @return {@link QRCode} representing the encoded QR code
  22356. * @throws WriterException if encoding can't succeed, because of for example invalid content
  22357. * or configuration
  22358. */
  22359. // public static encode(content: string, ecLevel: ErrorCorrectionLevel): QRCode /*throws WriterException*/ {
  22360. // return encode(content, ecLevel, null)
  22361. // }
  22362. static encode(content, ecLevel, hints = null) {
  22363. // Determine what character encoding has been specified by the caller, if any
  22364. let encoding = Encoder.DEFAULT_BYTE_MODE_ENCODING;
  22365. const hasEncodingHint = hints !== null && undefined !== hints.get(EncodeHintType$1.CHARACTER_SET);
  22366. if (hasEncodingHint) {
  22367. encoding = hints.get(EncodeHintType$1.CHARACTER_SET).toString();
  22368. }
  22369. // Pick an encoding mode appropriate for the content. Note that this will not attempt to use
  22370. // multiple modes / segments even if that were more efficient. Twould be nice.
  22371. const mode = this.chooseMode(content, encoding);
  22372. // This will store the header information, like mode and
  22373. // length, as well as "header" segments like an ECI segment.
  22374. const headerBits = new BitArray();
  22375. // Append ECI segment if applicable
  22376. if (mode === Mode$1.BYTE && (hasEncodingHint || Encoder.DEFAULT_BYTE_MODE_ENCODING !== encoding)) {
  22377. const eci = CharacterSetECI.getCharacterSetECIByName(encoding);
  22378. if (eci !== undefined) {
  22379. this.appendECI(eci, headerBits);
  22380. }
  22381. }
  22382. // (With ECI in place,) Write the mode marker
  22383. this.appendModeInfo(mode, headerBits);
  22384. // Collect data within the main segment, separately, to count its size if needed. Don't add it to
  22385. // main payload yet.
  22386. const dataBits = new BitArray();
  22387. this.appendBytes(content, mode, dataBits, encoding);
  22388. let version;
  22389. if (hints !== null && undefined !== hints.get(EncodeHintType$1.QR_VERSION)) {
  22390. const versionNumber = Number.parseInt(hints.get(EncodeHintType$1.QR_VERSION).toString(), 10);
  22391. version = Version$1.getVersionForNumber(versionNumber);
  22392. const bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, version);
  22393. if (!this.willFit(bitsNeeded, version, ecLevel)) {
  22394. throw new WriterException('Data too big for requested version');
  22395. }
  22396. }
  22397. else {
  22398. version = this.recommendVersion(ecLevel, mode, headerBits, dataBits);
  22399. }
  22400. const headerAndDataBits = new BitArray();
  22401. headerAndDataBits.appendBitArray(headerBits);
  22402. // Find "length" of main segment and write it
  22403. const numLetters = mode === Mode$1.BYTE ? dataBits.getSizeInBytes() : content.length;
  22404. this.appendLengthInfo(numLetters, version, mode, headerAndDataBits);
  22405. // Put data together into the overall payload
  22406. headerAndDataBits.appendBitArray(dataBits);
  22407. const ecBlocks = version.getECBlocksForLevel(ecLevel);
  22408. const numDataBytes = version.getTotalCodewords() - ecBlocks.getTotalECCodewords();
  22409. // Terminate the bits properly.
  22410. this.terminateBits(numDataBytes, headerAndDataBits);
  22411. // Interleave data bits with error correction code.
  22412. const finalBits = this.interleaveWithECBytes(headerAndDataBits, version.getTotalCodewords(), numDataBytes, ecBlocks.getNumBlocks());
  22413. const qrCode = new QRCode();
  22414. qrCode.setECLevel(ecLevel);
  22415. qrCode.setMode(mode);
  22416. qrCode.setVersion(version);
  22417. // Choose the mask pattern and set to "qrCode".
  22418. const dimension = version.getDimensionForVersion();
  22419. const matrix = new ByteMatrix(dimension, dimension);
  22420. const maskPattern = this.chooseMaskPattern(finalBits, ecLevel, version, matrix);
  22421. qrCode.setMaskPattern(maskPattern);
  22422. // Build the matrix and set it to "qrCode".
  22423. MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);
  22424. qrCode.setMatrix(matrix);
  22425. return qrCode;
  22426. }
  22427. /**
  22428. * Decides the smallest version of QR code that will contain all of the provided data.
  22429. *
  22430. * @throws WriterException if the data cannot fit in any version
  22431. */
  22432. static recommendVersion(ecLevel, mode, headerBits, dataBits) {
  22433. // Hard part: need to know version to know how many bits length takes. But need to know how many
  22434. // bits it takes to know version. First we take a guess at version by assuming version will be
  22435. // the minimum, 1:
  22436. const provisionalBitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, Version$1.getVersionForNumber(1));
  22437. const provisionalVersion = this.chooseVersion(provisionalBitsNeeded, ecLevel);
  22438. // Use that guess to calculate the right version. I am still not sure this works in 100% of cases.
  22439. const bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion);
  22440. return this.chooseVersion(bitsNeeded, ecLevel);
  22441. }
  22442. static calculateBitsNeeded(mode, headerBits, dataBits, version) {
  22443. return headerBits.getSize() + mode.getCharacterCountBits(version) + dataBits.getSize();
  22444. }
  22445. /**
  22446. * @return the code point of the table used in alphanumeric mode or
  22447. * -1 if there is no corresponding code in the table.
  22448. */
  22449. static getAlphanumericCode(code /*int*/) {
  22450. if (code < Encoder.ALPHANUMERIC_TABLE.length) {
  22451. return Encoder.ALPHANUMERIC_TABLE[code];
  22452. }
  22453. return -1;
  22454. }
  22455. // public static chooseMode(content: string): Mode {
  22456. // return chooseMode(content, null);
  22457. // }
  22458. /**
  22459. * Choose the best mode by examining the content. Note that 'encoding' is used as a hint;
  22460. * if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.
  22461. */
  22462. static chooseMode(content, encoding = null) {
  22463. if (CharacterSetECI.SJIS.getName() === encoding && this.isOnlyDoubleByteKanji(content)) {
  22464. // Choose Kanji mode if all input are double-byte characters
  22465. return Mode$1.KANJI;
  22466. }
  22467. let hasNumeric = false;
  22468. let hasAlphanumeric = false;
  22469. for (let i = 0, length = content.length; i < length; ++i) {
  22470. const c = content.charAt(i);
  22471. if (Encoder.isDigit(c)) {
  22472. hasNumeric = true;
  22473. }
  22474. else if (this.getAlphanumericCode(c.charCodeAt(0)) !== -1) {
  22475. hasAlphanumeric = true;
  22476. }
  22477. else {
  22478. return Mode$1.BYTE;
  22479. }
  22480. }
  22481. if (hasAlphanumeric) {
  22482. return Mode$1.ALPHANUMERIC;
  22483. }
  22484. if (hasNumeric) {
  22485. return Mode$1.NUMERIC;
  22486. }
  22487. return Mode$1.BYTE;
  22488. }
  22489. static isOnlyDoubleByteKanji(content) {
  22490. let bytes;
  22491. try {
  22492. bytes = StringEncoding.encode(content, CharacterSetECI.SJIS); // content.getBytes("Shift_JIS"))
  22493. }
  22494. catch (ignored /*: UnsupportedEncodingException*/) {
  22495. return false;
  22496. }
  22497. const length = bytes.length;
  22498. if (length % 2 !== 0) {
  22499. return false;
  22500. }
  22501. for (let i = 0; i < length; i += 2) {
  22502. const byte1 = bytes[i] & 0xFF;
  22503. if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {
  22504. return false;
  22505. }
  22506. }
  22507. return true;
  22508. }
  22509. static chooseMaskPattern(bits, ecLevel, version, matrix) {
  22510. let minPenalty = Number.MAX_SAFE_INTEGER; // Lower penalty is better.
  22511. let bestMaskPattern = -1;
  22512. // We try all mask patterns to choose the best one.
  22513. for (let maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {
  22514. MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);
  22515. let penalty = this.calculateMaskPenalty(matrix);
  22516. if (penalty < minPenalty) {
  22517. minPenalty = penalty;
  22518. bestMaskPattern = maskPattern;
  22519. }
  22520. }
  22521. return bestMaskPattern;
  22522. }
  22523. static chooseVersion(numInputBits /*int*/, ecLevel) {
  22524. for (let versionNum = 1; versionNum <= 40; versionNum++) {
  22525. const version = Version$1.getVersionForNumber(versionNum);
  22526. if (Encoder.willFit(numInputBits, version, ecLevel)) {
  22527. return version;
  22528. }
  22529. }
  22530. throw new WriterException('Data too big');
  22531. }
  22532. /**
  22533. * @return true if the number of input bits will fit in a code with the specified version and
  22534. * error correction level.
  22535. */
  22536. static willFit(numInputBits /*int*/, version, ecLevel) {
  22537. // In the following comments, we use numbers of Version 7-H.
  22538. // numBytes = 196
  22539. const numBytes = version.getTotalCodewords();
  22540. // getNumECBytes = 130
  22541. const ecBlocks = version.getECBlocksForLevel(ecLevel);
  22542. const numEcBytes = ecBlocks.getTotalECCodewords();
  22543. // getNumDataBytes = 196 - 130 = 66
  22544. const numDataBytes = numBytes - numEcBytes;
  22545. const totalInputBytes = (numInputBits + 7) / 8;
  22546. return numDataBytes >= totalInputBytes;
  22547. }
  22548. /**
  22549. * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).
  22550. */
  22551. static terminateBits(numDataBytes /*int*/, bits) {
  22552. const capacity = numDataBytes * 8;
  22553. if (bits.getSize() > capacity) {
  22554. throw new WriterException('data bits cannot fit in the QR Code' + bits.getSize() + ' > ' +
  22555. capacity);
  22556. }
  22557. for (let i = 0; i < 4 && bits.getSize() < capacity; ++i) {
  22558. bits.appendBit(false);
  22559. }
  22560. // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.
  22561. // If the last byte isn't 8-bit aligned, we'll add padding bits.
  22562. const numBitsInLastByte = bits.getSize() & 0x07;
  22563. if (numBitsInLastByte > 0) {
  22564. for (let i = numBitsInLastByte; i < 8; i++) {
  22565. bits.appendBit(false);
  22566. }
  22567. }
  22568. // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).
  22569. const numPaddingBytes = numDataBytes - bits.getSizeInBytes();
  22570. for (let i = 0; i < numPaddingBytes; ++i) {
  22571. bits.appendBits((i & 0x01) === 0 ? 0xEC : 0x11, 8);
  22572. }
  22573. if (bits.getSize() !== capacity) {
  22574. throw new WriterException('Bits size does not equal capacity');
  22575. }
  22576. }
  22577. /**
  22578. * Get number of data bytes and number of error correction bytes for block id "blockID". Store
  22579. * the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
  22580. * JISX0510:2004 (p.30)
  22581. */
  22582. static getNumDataBytesAndNumECBytesForBlockID(numTotalBytes /*int*/, numDataBytes /*int*/, numRSBlocks /*int*/, blockID /*int*/, numDataBytesInBlock, numECBytesInBlock) {
  22583. if (blockID >= numRSBlocks) {
  22584. throw new WriterException('Block ID too large');
  22585. }
  22586. // numRsBlocksInGroup2 = 196 % 5 = 1
  22587. const numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
  22588. // numRsBlocksInGroup1 = 5 - 1 = 4
  22589. const numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
  22590. // numTotalBytesInGroup1 = 196 / 5 = 39
  22591. const numTotalBytesInGroup1 = Math.floor(numTotalBytes / numRSBlocks);
  22592. // numTotalBytesInGroup2 = 39 + 1 = 40
  22593. const numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
  22594. // numDataBytesInGroup1 = 66 / 5 = 13
  22595. const numDataBytesInGroup1 = Math.floor(numDataBytes / numRSBlocks);
  22596. // numDataBytesInGroup2 = 13 + 1 = 14
  22597. const numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
  22598. // numEcBytesInGroup1 = 39 - 13 = 26
  22599. const numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
  22600. // numEcBytesInGroup2 = 40 - 14 = 26
  22601. const numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
  22602. // Sanity checks.
  22603. // 26 = 26
  22604. if (numEcBytesInGroup1 !== numEcBytesInGroup2) {
  22605. throw new WriterException('EC bytes mismatch');
  22606. }
  22607. // 5 = 4 + 1.
  22608. if (numRSBlocks !== numRsBlocksInGroup1 + numRsBlocksInGroup2) {
  22609. throw new WriterException('RS blocks mismatch');
  22610. }
  22611. // 196 = (13 + 26) * 4 + (14 + 26) * 1
  22612. if (numTotalBytes !==
  22613. ((numDataBytesInGroup1 + numEcBytesInGroup1) *
  22614. numRsBlocksInGroup1) +
  22615. ((numDataBytesInGroup2 + numEcBytesInGroup2) *
  22616. numRsBlocksInGroup2)) {
  22617. throw new WriterException('Total bytes mismatch');
  22618. }
  22619. if (blockID < numRsBlocksInGroup1) {
  22620. numDataBytesInBlock[0] = numDataBytesInGroup1;
  22621. numECBytesInBlock[0] = numEcBytesInGroup1;
  22622. }
  22623. else {
  22624. numDataBytesInBlock[0] = numDataBytesInGroup2;
  22625. numECBytesInBlock[0] = numEcBytesInGroup2;
  22626. }
  22627. }
  22628. /**
  22629. * Interleave "bits" with corresponding error correction bytes. On success, store the result in
  22630. * "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
  22631. */
  22632. static interleaveWithECBytes(bits, numTotalBytes /*int*/, numDataBytes /*int*/, numRSBlocks /*int*/) {
  22633. // "bits" must have "getNumDataBytes" bytes of data.
  22634. if (bits.getSizeInBytes() !== numDataBytes) {
  22635. throw new WriterException('Number of bits and data bytes does not match');
  22636. }
  22637. // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll
  22638. // store the divided data bytes blocks and error correction bytes blocks into "blocks".
  22639. let dataBytesOffset = 0;
  22640. let maxNumDataBytes = 0;
  22641. let maxNumEcBytes = 0;
  22642. // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
  22643. const blocks = new Array(); // new Array<BlockPair>(numRSBlocks)
  22644. for (let i = 0; i < numRSBlocks; ++i) {
  22645. const numDataBytesInBlock = new Int32Array(1);
  22646. const numEcBytesInBlock = new Int32Array(1);
  22647. Encoder.getNumDataBytesAndNumECBytesForBlockID(numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock);
  22648. const size = numDataBytesInBlock[0];
  22649. const dataBytes = new Uint8Array(size);
  22650. bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size);
  22651. const ecBytes = Encoder.generateECBytes(dataBytes, numEcBytesInBlock[0]);
  22652. blocks.push(new BlockPair(dataBytes, ecBytes));
  22653. maxNumDataBytes = Math.max(maxNumDataBytes, size);
  22654. maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.length);
  22655. dataBytesOffset += numDataBytesInBlock[0];
  22656. }
  22657. if (numDataBytes !== dataBytesOffset) {
  22658. throw new WriterException('Data bytes does not match offset');
  22659. }
  22660. const result = new BitArray();
  22661. // First, place data blocks.
  22662. for (let i = 0; i < maxNumDataBytes; ++i) {
  22663. for (const block of blocks) {
  22664. const dataBytes = block.getDataBytes();
  22665. if (i < dataBytes.length) {
  22666. result.appendBits(dataBytes[i], 8);
  22667. }
  22668. }
  22669. }
  22670. // Then, place error correction blocks.
  22671. for (let i = 0; i < maxNumEcBytes; ++i) {
  22672. for (const block of blocks) {
  22673. const ecBytes = block.getErrorCorrectionBytes();
  22674. if (i < ecBytes.length) {
  22675. result.appendBits(ecBytes[i], 8);
  22676. }
  22677. }
  22678. }
  22679. if (numTotalBytes !== result.getSizeInBytes()) { // Should be same.
  22680. throw new WriterException('Interleaving error: ' + numTotalBytes + ' and ' +
  22681. result.getSizeInBytes() + ' differ.');
  22682. }
  22683. return result;
  22684. }
  22685. static generateECBytes(dataBytes, numEcBytesInBlock /*int*/) {
  22686. const numDataBytes = dataBytes.length;
  22687. const toEncode = new Int32Array(numDataBytes + numEcBytesInBlock); // int[numDataBytes + numEcBytesInBlock]
  22688. for (let i = 0; i < numDataBytes; i++) {
  22689. toEncode[i] = dataBytes[i] & 0xFF;
  22690. }
  22691. new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock);
  22692. const ecBytes = new Uint8Array(numEcBytesInBlock);
  22693. for (let i = 0; i < numEcBytesInBlock; i++) {
  22694. ecBytes[i] = /*(byte) */ toEncode[numDataBytes + i];
  22695. }
  22696. return ecBytes;
  22697. }
  22698. /**
  22699. * Append mode info. On success, store the result in "bits".
  22700. */
  22701. static appendModeInfo(mode, bits) {
  22702. bits.appendBits(mode.getBits(), 4);
  22703. }
  22704. /**
  22705. * Append length info. On success, store the result in "bits".
  22706. */
  22707. static appendLengthInfo(numLetters /*int*/, version, mode, bits) {
  22708. const numBits = mode.getCharacterCountBits(version);
  22709. if (numLetters >= (1 << numBits)) {
  22710. throw new WriterException(numLetters + ' is bigger than ' + ((1 << numBits) - 1));
  22711. }
  22712. bits.appendBits(numLetters, numBits);
  22713. }
  22714. /**
  22715. * Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".
  22716. */
  22717. static appendBytes(content, mode, bits, encoding) {
  22718. switch (mode) {
  22719. case Mode$1.NUMERIC:
  22720. Encoder.appendNumericBytes(content, bits);
  22721. break;
  22722. case Mode$1.ALPHANUMERIC:
  22723. Encoder.appendAlphanumericBytes(content, bits);
  22724. break;
  22725. case Mode$1.BYTE:
  22726. Encoder.append8BitBytes(content, bits, encoding);
  22727. break;
  22728. case Mode$1.KANJI:
  22729. Encoder.appendKanjiBytes(content, bits);
  22730. break;
  22731. default:
  22732. throw new WriterException('Invalid mode: ' + mode);
  22733. }
  22734. }
  22735. static getDigit(singleCharacter) {
  22736. return singleCharacter.charCodeAt(0) - 48;
  22737. }
  22738. static isDigit(singleCharacter) {
  22739. const cn = Encoder.getDigit(singleCharacter);
  22740. return cn >= 0 && cn <= 9;
  22741. }
  22742. static appendNumericBytes(content, bits) {
  22743. const length = content.length;
  22744. let i = 0;
  22745. while (i < length) {
  22746. const num1 = Encoder.getDigit(content.charAt(i));
  22747. if (i + 2 < length) {
  22748. // Encode three numeric letters in ten bits.
  22749. const num2 = Encoder.getDigit(content.charAt(i + 1));
  22750. const num3 = Encoder.getDigit(content.charAt(i + 2));
  22751. bits.appendBits(num1 * 100 + num2 * 10 + num3, 10);
  22752. i += 3;
  22753. }
  22754. else if (i + 1 < length) {
  22755. // Encode two numeric letters in seven bits.
  22756. const num2 = Encoder.getDigit(content.charAt(i + 1));
  22757. bits.appendBits(num1 * 10 + num2, 7);
  22758. i += 2;
  22759. }
  22760. else {
  22761. // Encode one numeric letter in four bits.
  22762. bits.appendBits(num1, 4);
  22763. i++;
  22764. }
  22765. }
  22766. }
  22767. static appendAlphanumericBytes(content, bits) {
  22768. const length = content.length;
  22769. let i = 0;
  22770. while (i < length) {
  22771. const code1 = Encoder.getAlphanumericCode(content.charCodeAt(i));
  22772. if (code1 === -1) {
  22773. throw new WriterException();
  22774. }
  22775. if (i + 1 < length) {
  22776. const code2 = Encoder.getAlphanumericCode(content.charCodeAt(i + 1));
  22777. if (code2 === -1) {
  22778. throw new WriterException();
  22779. }
  22780. // Encode two alphanumeric letters in 11 bits.
  22781. bits.appendBits(code1 * 45 + code2, 11);
  22782. i += 2;
  22783. }
  22784. else {
  22785. // Encode one alphanumeric letter in six bits.
  22786. bits.appendBits(code1, 6);
  22787. i++;
  22788. }
  22789. }
  22790. }
  22791. static append8BitBytes(content, bits, encoding) {
  22792. let bytes;
  22793. try {
  22794. bytes = StringEncoding.encode(content, encoding);
  22795. }
  22796. catch (uee /*: UnsupportedEncodingException*/) {
  22797. throw new WriterException(uee);
  22798. }
  22799. for (let i = 0, length = bytes.length; i !== length; i++) {
  22800. const b = bytes[i];
  22801. bits.appendBits(b, 8);
  22802. }
  22803. }
  22804. /**
  22805. * @throws WriterException
  22806. */
  22807. static appendKanjiBytes(content, bits) {
  22808. let bytes;
  22809. try {
  22810. bytes = StringEncoding.encode(content, CharacterSetECI.SJIS);
  22811. }
  22812. catch (uee /*: UnsupportedEncodingException*/) {
  22813. throw new WriterException(uee);
  22814. }
  22815. const length = bytes.length;
  22816. for (let i = 0; i < length; i += 2) {
  22817. const byte1 = bytes[i] & 0xFF;
  22818. const byte2 = bytes[i + 1] & 0xFF;
  22819. const code = ((byte1 << 8) & 0xFFFFFFFF) | byte2;
  22820. let subtracted = -1;
  22821. if (code >= 0x8140 && code <= 0x9ffc) {
  22822. subtracted = code - 0x8140;
  22823. }
  22824. else if (code >= 0xe040 && code <= 0xebbf) {
  22825. subtracted = code - 0xc140;
  22826. }
  22827. if (subtracted === -1) {
  22828. throw new WriterException('Invalid byte sequence');
  22829. }
  22830. const encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff);
  22831. bits.appendBits(encoded, 13);
  22832. }
  22833. }
  22834. static appendECI(eci, bits) {
  22835. bits.appendBits(Mode$1.ECI.getBits(), 4);
  22836. // This is correct for values up to 127, which is all we need now.
  22837. bits.appendBits(eci.getValue(), 8);
  22838. }
  22839. }
  22840. // The original table is defined in the table 5 of JISX0510:2004 (p.19).
  22841. Encoder.ALPHANUMERIC_TABLE = Int32Array.from([
  22842. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  22843. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  22844. 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,
  22845. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1,
  22846. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  22847. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,
  22848. ]);
  22849. Encoder.DEFAULT_BYTE_MODE_ENCODING = CharacterSetECI.UTF8.getName(); // "ISO-8859-1"
  22850. /**
  22851. * @deprecated Moving to @zxing/browser
  22852. */
  22853. class BrowserQRCodeSvgWriter {
  22854. /**
  22855. * Writes and renders a QRCode SVG element.
  22856. *
  22857. * @param contents
  22858. * @param width
  22859. * @param height
  22860. * @param hints
  22861. */
  22862. write(contents, width, height, hints = null) {
  22863. if (contents.length === 0) {
  22864. throw new IllegalArgumentException('Found empty contents');
  22865. }
  22866. // if (format != BarcodeFormat.QR_CODE) {
  22867. // throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format)
  22868. // }
  22869. if (width < 0 || height < 0) {
  22870. throw new IllegalArgumentException('Requested dimensions are too small: ' + width + 'x' + height);
  22871. }
  22872. let errorCorrectionLevel = ErrorCorrectionLevel.L;
  22873. let quietZone = BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE;
  22874. if (hints !== null) {
  22875. if (undefined !== hints.get(EncodeHintType$1.ERROR_CORRECTION)) {
  22876. errorCorrectionLevel = ErrorCorrectionLevel.fromString(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());
  22877. }
  22878. if (undefined !== hints.get(EncodeHintType$1.MARGIN)) {
  22879. quietZone = Number.parseInt(hints.get(EncodeHintType$1.MARGIN).toString(), 10);
  22880. }
  22881. }
  22882. const code = Encoder.encode(contents, errorCorrectionLevel, hints);
  22883. return this.renderResult(code, width, height, quietZone);
  22884. }
  22885. /**
  22886. * Renders the result and then appends it to the DOM.
  22887. */
  22888. writeToDom(containerElement, contents, width, height, hints = null) {
  22889. if (typeof containerElement === 'string') {
  22890. containerElement = document.querySelector(containerElement);
  22891. }
  22892. const svgElement = this.write(contents, width, height, hints);
  22893. if (containerElement)
  22894. containerElement.appendChild(svgElement);
  22895. }
  22896. /**
  22897. * Note that the input matrix uses 0 == white, 1 == black.
  22898. * The output matrix uses 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
  22899. */
  22900. renderResult(code, width /*int*/, height /*int*/, quietZone /*int*/) {
  22901. const input = code.getMatrix();
  22902. if (input === null) {
  22903. throw new IllegalStateException();
  22904. }
  22905. const inputWidth = input.getWidth();
  22906. const inputHeight = input.getHeight();
  22907. const qrWidth = inputWidth + (quietZone * 2);
  22908. const qrHeight = inputHeight + (quietZone * 2);
  22909. const outputWidth = Math.max(width, qrWidth);
  22910. const outputHeight = Math.max(height, qrHeight);
  22911. const multiple = Math.min(Math.floor(outputWidth / qrWidth), Math.floor(outputHeight / qrHeight));
  22912. // Padding includes both the quiet zone and the extra white pixels to accommodate the requested
  22913. // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
  22914. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
  22915. // handle all the padding from 100x100 (the actual QR) up to 200x160.
  22916. const leftPadding = Math.floor((outputWidth - (inputWidth * multiple)) / 2);
  22917. const topPadding = Math.floor((outputHeight - (inputHeight * multiple)) / 2);
  22918. const svgElement = this.createSVGElement(outputWidth, outputHeight);
  22919. for (let inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
  22920. // Write the contents of this row of the barcode
  22921. for (let inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
  22922. if (input.get(inputX, inputY) === 1) {
  22923. const svgRectElement = this.createSvgRectElement(outputX, outputY, multiple, multiple);
  22924. svgElement.appendChild(svgRectElement);
  22925. }
  22926. }
  22927. }
  22928. return svgElement;
  22929. }
  22930. /**
  22931. * Creates a SVG element.
  22932. *
  22933. * @param w SVG's width attribute
  22934. * @param h SVG's height attribute
  22935. */
  22936. createSVGElement(w, h) {
  22937. const svgElement = document.createElementNS(BrowserQRCodeSvgWriter.SVG_NS, 'svg');
  22938. svgElement.setAttributeNS(null, 'height', w.toString());
  22939. svgElement.setAttributeNS(null, 'width', h.toString());
  22940. return svgElement;
  22941. }
  22942. /**
  22943. * Creates a SVG rect element.
  22944. *
  22945. * @param x Element's x coordinate
  22946. * @param y Element's y coordinate
  22947. * @param w Element's width attribute
  22948. * @param h Element's height attribute
  22949. */
  22950. createSvgRectElement(x, y, w, h) {
  22951. const rect = document.createElementNS(BrowserQRCodeSvgWriter.SVG_NS, 'rect');
  22952. rect.setAttributeNS(null, 'x', x.toString());
  22953. rect.setAttributeNS(null, 'y', y.toString());
  22954. rect.setAttributeNS(null, 'height', w.toString());
  22955. rect.setAttributeNS(null, 'width', h.toString());
  22956. rect.setAttributeNS(null, 'fill', '#000000');
  22957. return rect;
  22958. }
  22959. }
  22960. BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE = 4;
  22961. /**
  22962. * SVG markup NameSpace
  22963. */
  22964. BrowserQRCodeSvgWriter.SVG_NS = 'http://www.w3.org/2000/svg';
  22965. /*
  22966. * Copyright 2008 ZXing authors
  22967. *
  22968. * Licensed under the Apache License, Version 2.0 (the "License");
  22969. * you may not use this file except in compliance with the License.
  22970. * You may obtain a copy of the License at
  22971. *
  22972. * http://www.apache.org/licenses/LICENSE-2.0
  22973. *
  22974. * Unless required by applicable law or agreed to in writing, software
  22975. * distributed under the License is distributed on an "AS IS" BASIS,
  22976. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22977. * See the License for the specific language governing permissions and
  22978. * limitations under the License.
  22979. */
  22980. /*import java.util.Map;*/
  22981. /**
  22982. * This object renders a QR Code as a BitMatrix 2D array of greyscale values.
  22983. *
  22984. * @author dswitkin@google.com (Daniel Switkin)
  22985. */
  22986. class QRCodeWriter {
  22987. /*@Override*/
  22988. // public encode(contents: string, format: BarcodeFormat, width: number /*int*/, height: number /*int*/): BitMatrix
  22989. // /*throws WriterException */ {
  22990. // return encode(contents, format, width, height, null)
  22991. // }
  22992. /*@Override*/
  22993. encode(contents, format, width /*int*/, height /*int*/, hints) {
  22994. if (contents.length === 0) {
  22995. throw new IllegalArgumentException('Found empty contents');
  22996. }
  22997. if (format !== BarcodeFormat$1.QR_CODE) {
  22998. throw new IllegalArgumentException('Can only encode QR_CODE, but got ' + format);
  22999. }
  23000. if (width < 0 || height < 0) {
  23001. throw new IllegalArgumentException(`Requested dimensions are too small: ${width}x${height}`);
  23002. }
  23003. let errorCorrectionLevel = ErrorCorrectionLevel.L;
  23004. let quietZone = QRCodeWriter.QUIET_ZONE_SIZE;
  23005. if (hints !== null) {
  23006. if (undefined !== hints.get(EncodeHintType$1.ERROR_CORRECTION)) {
  23007. errorCorrectionLevel = ErrorCorrectionLevel.fromString(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());
  23008. }
  23009. if (undefined !== hints.get(EncodeHintType$1.MARGIN)) {
  23010. quietZone = Number.parseInt(hints.get(EncodeHintType$1.MARGIN).toString(), 10);
  23011. }
  23012. }
  23013. const code = Encoder.encode(contents, errorCorrectionLevel, hints);
  23014. return QRCodeWriter.renderResult(code, width, height, quietZone);
  23015. }
  23016. // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses
  23017. // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
  23018. static renderResult(code, width /*int*/, height /*int*/, quietZone /*int*/) {
  23019. const input = code.getMatrix();
  23020. if (input === null) {
  23021. throw new IllegalStateException();
  23022. }
  23023. const inputWidth = input.getWidth();
  23024. const inputHeight = input.getHeight();
  23025. const qrWidth = inputWidth + (quietZone * 2);
  23026. const qrHeight = inputHeight + (quietZone * 2);
  23027. const outputWidth = Math.max(width, qrWidth);
  23028. const outputHeight = Math.max(height, qrHeight);
  23029. const multiple = Math.min(Math.floor(outputWidth / qrWidth), Math.floor(outputHeight / qrHeight));
  23030. // Padding includes both the quiet zone and the extra white pixels to accommodate the requested
  23031. // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
  23032. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
  23033. // handle all the padding from 100x100 (the actual QR) up to 200x160.
  23034. const leftPadding = Math.floor((outputWidth - (inputWidth * multiple)) / 2);
  23035. const topPadding = Math.floor((outputHeight - (inputHeight * multiple)) / 2);
  23036. const output = new BitMatrix(outputWidth, outputHeight);
  23037. for (let inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
  23038. // Write the contents of this row of the barcode
  23039. for (let inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
  23040. if (input.get(inputX, inputY) === 1) {
  23041. output.setRegion(outputX, outputY, multiple, multiple);
  23042. }
  23043. }
  23044. }
  23045. return output;
  23046. }
  23047. }
  23048. QRCodeWriter.QUIET_ZONE_SIZE = 4;
  23049. /*
  23050. * Copyright 2008 ZXing authors
  23051. *
  23052. * Licensed under the Apache License, Version 2.0 (the "License");
  23053. * you may not use this file except in compliance with the License.
  23054. * You may obtain a copy of the License at
  23055. *
  23056. * http://www.apache.org/licenses/LICENSE-2.0
  23057. *
  23058. * Unless required by applicable law or agreed to in writing, software
  23059. * distributed under the License is distributed on an "AS IS" BASIS,
  23060. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23061. * See the License for the specific language governing permissions and
  23062. * limitations under the License.
  23063. */
  23064. /*import java.util.Map;*/
  23065. /**
  23066. * This is a factory class which finds the appropriate Writer subclass for the BarcodeFormat
  23067. * requested and encodes the barcode with the supplied contents.
  23068. *
  23069. * @author dswitkin@google.com (Daniel Switkin)
  23070. */
  23071. class MultiFormatWriter {
  23072. /*@Override*/
  23073. // public encode(contents: string,
  23074. // format: BarcodeFormat,
  23075. // width: number /*int*/,
  23076. // height: number /*int*/): BitMatrix /*throws WriterException */ {
  23077. // return encode(contents, format, width, height, null)
  23078. // }
  23079. /*@Override*/
  23080. encode(contents, format, width /*int*/, height /*int*/, hints) {
  23081. let writer;
  23082. switch (format) {
  23083. // case BarcodeFormat.EAN_8:
  23084. // writer = new EAN8Writer()
  23085. // break
  23086. // case BarcodeFormat.UPC_E:
  23087. // writer = new UPCEWriter()
  23088. // break
  23089. // case BarcodeFormat.EAN_13:
  23090. // writer = new EAN13Writer()
  23091. // break
  23092. // case BarcodeFormat.UPC_A:
  23093. // writer = new UPCAWriter()
  23094. // break
  23095. case BarcodeFormat$1.QR_CODE:
  23096. writer = new QRCodeWriter();
  23097. break;
  23098. // case BarcodeFormat.CODE_39:
  23099. // writer = new Code39Writer()
  23100. // break
  23101. // case BarcodeFormat.CODE_93:
  23102. // writer = new Code93Writer()
  23103. // break
  23104. // case BarcodeFormat.CODE_128:
  23105. // writer = new Code128Writer()
  23106. // break
  23107. // case BarcodeFormat.ITF:
  23108. // writer = new ITFWriter()
  23109. // break
  23110. // case BarcodeFormat.PDF_417:
  23111. // writer = new PDF417Writer()
  23112. // break
  23113. // case BarcodeFormat.CODABAR:
  23114. // writer = new CodaBarWriter()
  23115. // break
  23116. // case BarcodeFormat.DATA_MATRIX:
  23117. // writer = new DataMatrixWriter()
  23118. // break
  23119. // case BarcodeFormat.AZTEC:
  23120. // writer = new AztecWriter()
  23121. // break
  23122. default:
  23123. throw new IllegalArgumentException('No encoder available for format ' + format);
  23124. }
  23125. return writer.encode(contents, format, width, height, hints);
  23126. }
  23127. }
  23128. /*
  23129. * Copyright 2009 ZXing authors
  23130. *
  23131. * Licensed under the Apache License, Version 2.0 (the "License");
  23132. * you may not use this file except in compliance with the License.
  23133. * You may obtain a copy of the License at
  23134. *
  23135. * http://www.apache.org/licenses/LICENSE-2.0
  23136. *
  23137. * Unless required by applicable law or agreed to in writing, software
  23138. * distributed under the License is distributed on an "AS IS" BASIS,
  23139. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23140. * See the License for the specific language governing permissions and
  23141. * limitations under the License.
  23142. */
  23143. /**
  23144. * This object extends LuminanceSource around an array of YUV data returned from the camera driver,
  23145. * with the option to crop to a rectangle within the full data. This can be used to exclude
  23146. * superfluous pixels around the perimeter and speed up decoding.
  23147. *
  23148. * It works for any pixel format where the Y channel is planar and appears first, including
  23149. * YCbCr_420_SP and YCbCr_422_SP.
  23150. *
  23151. * @author dswitkin@google.com (Daniel Switkin)
  23152. */
  23153. class PlanarYUVLuminanceSource extends LuminanceSource {
  23154. constructor(yuvData, dataWidth /*int*/, dataHeight /*int*/, left /*int*/, top /*int*/, width /*int*/, height /*int*/, reverseHorizontal) {
  23155. super(width, height);
  23156. this.yuvData = yuvData;
  23157. this.dataWidth = dataWidth;
  23158. this.dataHeight = dataHeight;
  23159. this.left = left;
  23160. this.top = top;
  23161. if (left + width > dataWidth || top + height > dataHeight) {
  23162. throw new IllegalArgumentException('Crop rectangle does not fit within image data.');
  23163. }
  23164. if (reverseHorizontal) {
  23165. this.reverseHorizontal(width, height);
  23166. }
  23167. }
  23168. /*@Override*/
  23169. getRow(y /*int*/, row) {
  23170. if (y < 0 || y >= this.getHeight()) {
  23171. throw new IllegalArgumentException('Requested row is outside the image: ' + y);
  23172. }
  23173. const width = this.getWidth();
  23174. if (row === null || row === undefined || row.length < width) {
  23175. row = new Uint8ClampedArray(width);
  23176. }
  23177. const offset = (y + this.top) * this.dataWidth + this.left;
  23178. System.arraycopy(this.yuvData, offset, row, 0, width);
  23179. return row;
  23180. }
  23181. /*@Override*/
  23182. getMatrix() {
  23183. const width = this.getWidth();
  23184. const height = this.getHeight();
  23185. // If the caller asks for the entire underlying image, save the copy and give them the
  23186. // original data. The docs specifically warn that result.length must be ignored.
  23187. if (width === this.dataWidth && height === this.dataHeight) {
  23188. return this.yuvData;
  23189. }
  23190. const area = width * height;
  23191. const matrix = new Uint8ClampedArray(area);
  23192. let inputOffset = this.top * this.dataWidth + this.left;
  23193. // If the width matches the full width of the underlying data, perform a single copy.
  23194. if (width === this.dataWidth) {
  23195. System.arraycopy(this.yuvData, inputOffset, matrix, 0, area);
  23196. return matrix;
  23197. }
  23198. // Otherwise copy one cropped row at a time.
  23199. for (let y = 0; y < height; y++) {
  23200. const outputOffset = y * width;
  23201. System.arraycopy(this.yuvData, inputOffset, matrix, outputOffset, width);
  23202. inputOffset += this.dataWidth;
  23203. }
  23204. return matrix;
  23205. }
  23206. /*@Override*/
  23207. isCropSupported() {
  23208. return true;
  23209. }
  23210. /*@Override*/
  23211. crop(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
  23212. return new PlanarYUVLuminanceSource(this.yuvData, this.dataWidth, this.dataHeight, this.left + left, this.top + top, width, height, false);
  23213. }
  23214. renderThumbnail() {
  23215. const width = this.getWidth() / PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;
  23216. const height = this.getHeight() / PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;
  23217. const pixels = new Int32Array(width * height);
  23218. const yuv = this.yuvData;
  23219. let inputOffset = this.top * this.dataWidth + this.left;
  23220. for (let y = 0; y < height; y++) {
  23221. const outputOffset = y * width;
  23222. for (let x = 0; x < width; x++) {
  23223. const grey = yuv[inputOffset + x * PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR] & 0xff;
  23224. pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
  23225. }
  23226. inputOffset += this.dataWidth * PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;
  23227. }
  23228. return pixels;
  23229. }
  23230. /**
  23231. * @return width of image from {@link #renderThumbnail()}
  23232. */
  23233. getThumbnailWidth() {
  23234. return this.getWidth() / PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;
  23235. }
  23236. /**
  23237. * @return height of image from {@link #renderThumbnail()}
  23238. */
  23239. getThumbnailHeight() {
  23240. return this.getHeight() / PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;
  23241. }
  23242. reverseHorizontal(width /*int*/, height /*int*/) {
  23243. const yuvData = this.yuvData;
  23244. for (let y = 0, rowStart = this.top * this.dataWidth + this.left; y < height; y++, rowStart += this.dataWidth) {
  23245. const middle = rowStart + width / 2;
  23246. for (let x1 = rowStart, x2 = rowStart + width - 1; x1 < middle; x1++, x2--) {
  23247. const temp = yuvData[x1];
  23248. yuvData[x1] = yuvData[x2];
  23249. yuvData[x2] = temp;
  23250. }
  23251. }
  23252. }
  23253. invert() {
  23254. return new InvertedLuminanceSource(this);
  23255. }
  23256. }
  23257. PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR = 2;
  23258. /*
  23259. * Copyright 2009 ZXing authors
  23260. *
  23261. * Licensed under the Apache License, Version 2.0 (the "License");
  23262. * you may not use this file except in compliance with the License.
  23263. * You may obtain a copy of the License at
  23264. *
  23265. * http://www.apache.org/licenses/LICENSE-2.0
  23266. *
  23267. * Unless required by applicable law or agreed to in writing, software
  23268. * distributed under the License is distributed on an "AS IS" BASIS,
  23269. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23270. * See the License for the specific language governing permissions and
  23271. * limitations under the License.
  23272. */
  23273. /**
  23274. * This class is used to help decode images from files which arrive as RGB data from
  23275. * an ARGB pixel array. It does not support rotation.
  23276. *
  23277. * @author dswitkin@google.com (Daniel Switkin)
  23278. * @author Betaminos
  23279. */
  23280. class RGBLuminanceSource extends LuminanceSource {
  23281. constructor(luminances, width /*int*/, height /*int*/, dataWidth /*int*/, dataHeight /*int*/, left /*int*/, top /*int*/) {
  23282. super(width, height);
  23283. this.dataWidth = dataWidth;
  23284. this.dataHeight = dataHeight;
  23285. this.left = left;
  23286. this.top = top;
  23287. if (luminances.BYTES_PER_ELEMENT === 4) { // Int32Array
  23288. const size = width * height;
  23289. const luminancesUint8Array = new Uint8ClampedArray(size);
  23290. for (let offset = 0; offset < size; offset++) {
  23291. const pixel = luminances[offset];
  23292. const r = (pixel >> 16) & 0xff; // red
  23293. const g2 = (pixel >> 7) & 0x1fe; // 2 * green
  23294. const b = pixel & 0xff; // blue
  23295. // Calculate green-favouring average cheaply
  23296. luminancesUint8Array[offset] = /*(byte) */ ((r + g2 + b) / 4) & 0xFF;
  23297. }
  23298. this.luminances = luminancesUint8Array;
  23299. }
  23300. else {
  23301. this.luminances = luminances;
  23302. }
  23303. if (undefined === dataWidth) {
  23304. this.dataWidth = width;
  23305. }
  23306. if (undefined === dataHeight) {
  23307. this.dataHeight = height;
  23308. }
  23309. if (undefined === left) {
  23310. this.left = 0;
  23311. }
  23312. if (undefined === top) {
  23313. this.top = 0;
  23314. }
  23315. if (this.left + width > this.dataWidth || this.top + height > this.dataHeight) {
  23316. throw new IllegalArgumentException('Crop rectangle does not fit within image data.');
  23317. }
  23318. }
  23319. /*@Override*/
  23320. getRow(y /*int*/, row) {
  23321. if (y < 0 || y >= this.getHeight()) {
  23322. throw new IllegalArgumentException('Requested row is outside the image: ' + y);
  23323. }
  23324. const width = this.getWidth();
  23325. if (row === null || row === undefined || row.length < width) {
  23326. row = new Uint8ClampedArray(width);
  23327. }
  23328. const offset = (y + this.top) * this.dataWidth + this.left;
  23329. System.arraycopy(this.luminances, offset, row, 0, width);
  23330. return row;
  23331. }
  23332. /*@Override*/
  23333. getMatrix() {
  23334. const width = this.getWidth();
  23335. const height = this.getHeight();
  23336. // If the caller asks for the entire underlying image, save the copy and give them the
  23337. // original data. The docs specifically warn that result.length must be ignored.
  23338. if (width === this.dataWidth && height === this.dataHeight) {
  23339. return this.luminances;
  23340. }
  23341. const area = width * height;
  23342. const matrix = new Uint8ClampedArray(area);
  23343. let inputOffset = this.top * this.dataWidth + this.left;
  23344. // If the width matches the full width of the underlying data, perform a single copy.
  23345. if (width === this.dataWidth) {
  23346. System.arraycopy(this.luminances, inputOffset, matrix, 0, area);
  23347. return matrix;
  23348. }
  23349. // Otherwise copy one cropped row at a time.
  23350. for (let y = 0; y < height; y++) {
  23351. const outputOffset = y * width;
  23352. System.arraycopy(this.luminances, inputOffset, matrix, outputOffset, width);
  23353. inputOffset += this.dataWidth;
  23354. }
  23355. return matrix;
  23356. }
  23357. /*@Override*/
  23358. isCropSupported() {
  23359. return true;
  23360. }
  23361. /*@Override*/
  23362. crop(left /*int*/, top /*int*/, width /*int*/, height /*int*/) {
  23363. return new RGBLuminanceSource(this.luminances, width, height, this.dataWidth, this.dataHeight, this.left + left, this.top + top);
  23364. }
  23365. invert() {
  23366. return new InvertedLuminanceSource(this);
  23367. }
  23368. }
  23369. /**
  23370. * Just to make a shortcut between Java code and TS code.
  23371. */
  23372. class Charset extends CharacterSetECI {
  23373. static forName(name) {
  23374. return this.getCharacterSetECIByName(name);
  23375. }
  23376. }
  23377. /**
  23378. * Just to make a shortcut between Java code and TS code.
  23379. */
  23380. class StandardCharsets {
  23381. }
  23382. StandardCharsets.ISO_8859_1 = CharacterSetECI.ISO8859_1;
  23383. /**
  23384. * Symbol Character Placement Program. Adapted from Annex M.1 in ISO/IEC 16022:2000(E).
  23385. */
  23386. class DefaultPlacement {
  23387. /**
  23388. * Main constructor
  23389. *
  23390. * @param codewords the codewords to place
  23391. * @param numcols the number of columns
  23392. * @param numrows the number of rows
  23393. */
  23394. constructor(codewords, numcols, numrows) {
  23395. this.codewords = codewords;
  23396. this.numcols = numcols;
  23397. this.numrows = numrows;
  23398. this.bits = new Uint8Array(numcols * numrows);
  23399. Arrays.fill(this.bits, 2); // Initialize with "not set" value
  23400. }
  23401. getNumrows() {
  23402. return this.numrows;
  23403. }
  23404. getNumcols() {
  23405. return this.numcols;
  23406. }
  23407. getBits() {
  23408. return this.bits;
  23409. }
  23410. getBit(col, row) {
  23411. return this.bits[row * this.numcols + col] === 1;
  23412. }
  23413. setBit(col, row, bit) {
  23414. this.bits[row * this.numcols + col] = bit ? 1 : 0;
  23415. }
  23416. noBit(col, row) {
  23417. return this.bits[row * this.numcols + col] === 2;
  23418. }
  23419. place() {
  23420. let pos = 0;
  23421. let row = 4;
  23422. let col = 0;
  23423. do {
  23424. // repeatedly first check for one of the special corner cases, then...
  23425. if (row === this.numrows && col === 0) {
  23426. this.corner1(pos++);
  23427. }
  23428. if (row === this.numrows - 2 && col === 0 && this.numcols % 4 !== 0) {
  23429. this.corner2(pos++);
  23430. }
  23431. if (row === this.numrows - 2 && col === 0 && this.numcols % 8 === 4) {
  23432. this.corner3(pos++);
  23433. }
  23434. if (row === this.numrows + 4 && col === 2 && this.numcols % 8 === 0) {
  23435. this.corner4(pos++);
  23436. }
  23437. // sweep upward diagonally, inserting successive characters...
  23438. do {
  23439. if (row < this.numrows && col >= 0 && this.noBit(col, row)) {
  23440. this.utah(row, col, pos++);
  23441. }
  23442. row -= 2;
  23443. col += 2;
  23444. } while (row >= 0 && col < this.numcols);
  23445. row++;
  23446. col += 3;
  23447. // and then sweep downward diagonally, inserting successive characters, ...
  23448. do {
  23449. if (row >= 0 && col < this.numcols && this.noBit(col, row)) {
  23450. this.utah(row, col, pos++);
  23451. }
  23452. row += 2;
  23453. col -= 2;
  23454. } while (row < this.numrows && col >= 0);
  23455. row += 3;
  23456. col++;
  23457. // ...until the entire array is scanned
  23458. } while (row < this.numrows || col < this.numcols);
  23459. // Lastly, if the lower right-hand corner is untouched, fill in fixed pattern
  23460. if (this.noBit(this.numcols - 1, this.numrows - 1)) {
  23461. this.setBit(this.numcols - 1, this.numrows - 1, true);
  23462. this.setBit(this.numcols - 2, this.numrows - 2, true);
  23463. }
  23464. }
  23465. module(row, col, pos, bit) {
  23466. if (row < 0) {
  23467. row += this.numrows;
  23468. col += 4 - ((this.numrows + 4) % 8);
  23469. }
  23470. if (col < 0) {
  23471. col += this.numcols;
  23472. row += 4 - ((this.numcols + 4) % 8);
  23473. }
  23474. // Note the conversion:
  23475. let v = this.codewords.charCodeAt(pos);
  23476. v &= 1 << (8 - bit);
  23477. this.setBit(col, row, v !== 0);
  23478. }
  23479. /**
  23480. * Places the 8 bits of a utah-shaped symbol character in ECC200.
  23481. *
  23482. * @param row the row
  23483. * @param col the column
  23484. * @param pos character position
  23485. */
  23486. utah(row, col, pos) {
  23487. this.module(row - 2, col - 2, pos, 1);
  23488. this.module(row - 2, col - 1, pos, 2);
  23489. this.module(row - 1, col - 2, pos, 3);
  23490. this.module(row - 1, col - 1, pos, 4);
  23491. this.module(row - 1, col, pos, 5);
  23492. this.module(row, col - 2, pos, 6);
  23493. this.module(row, col - 1, pos, 7);
  23494. this.module(row, col, pos, 8);
  23495. }
  23496. corner1(pos) {
  23497. this.module(this.numrows - 1, 0, pos, 1);
  23498. this.module(this.numrows - 1, 1, pos, 2);
  23499. this.module(this.numrows - 1, 2, pos, 3);
  23500. this.module(0, this.numcols - 2, pos, 4);
  23501. this.module(0, this.numcols - 1, pos, 5);
  23502. this.module(1, this.numcols - 1, pos, 6);
  23503. this.module(2, this.numcols - 1, pos, 7);
  23504. this.module(3, this.numcols - 1, pos, 8);
  23505. }
  23506. corner2(pos) {
  23507. this.module(this.numrows - 3, 0, pos, 1);
  23508. this.module(this.numrows - 2, 0, pos, 2);
  23509. this.module(this.numrows - 1, 0, pos, 3);
  23510. this.module(0, this.numcols - 4, pos, 4);
  23511. this.module(0, this.numcols - 3, pos, 5);
  23512. this.module(0, this.numcols - 2, pos, 6);
  23513. this.module(0, this.numcols - 1, pos, 7);
  23514. this.module(1, this.numcols - 1, pos, 8);
  23515. }
  23516. corner3(pos) {
  23517. this.module(this.numrows - 3, 0, pos, 1);
  23518. this.module(this.numrows - 2, 0, pos, 2);
  23519. this.module(this.numrows - 1, 0, pos, 3);
  23520. this.module(0, this.numcols - 2, pos, 4);
  23521. this.module(0, this.numcols - 1, pos, 5);
  23522. this.module(1, this.numcols - 1, pos, 6);
  23523. this.module(2, this.numcols - 1, pos, 7);
  23524. this.module(3, this.numcols - 1, pos, 8);
  23525. }
  23526. corner4(pos) {
  23527. this.module(this.numrows - 1, 0, pos, 1);
  23528. this.module(this.numrows - 1, this.numcols - 1, pos, 2);
  23529. this.module(0, this.numcols - 3, pos, 3);
  23530. this.module(0, this.numcols - 2, pos, 4);
  23531. this.module(0, this.numcols - 1, pos, 5);
  23532. this.module(1, this.numcols - 3, pos, 6);
  23533. this.module(1, this.numcols - 2, pos, 7);
  23534. this.module(1, this.numcols - 1, pos, 8);
  23535. }
  23536. }
  23537. /**
  23538. * Lookup table which factors to use for which number of error correction codewords.
  23539. * See FACTORS.
  23540. */
  23541. const FACTOR_SETS = [
  23542. 5, 7, 10, 11, 12, 14, 18, 20, 24, 28, 36, 42, 48, 56, 62, 68,
  23543. ];
  23544. /**
  23545. * Precomputed polynomial factors for ECC 200.
  23546. */
  23547. const FACTORS = [
  23548. [228, 48, 15, 111, 62],
  23549. [23, 68, 144, 134, 240, 92, 254],
  23550. [28, 24, 185, 166, 223, 248, 116, 255, 110, 61],
  23551. [175, 138, 205, 12, 194, 168, 39, 245, 60, 97, 120],
  23552. [41, 153, 158, 91, 61, 42, 142, 213, 97, 178, 100, 242],
  23553. [156, 97, 192, 252, 95, 9, 157, 119, 138, 45, 18, 186, 83, 185],
  23554. [
  23555. 83, 195, 100, 39, 188, 75, 66, 61, 241, 213, 109, 129, 94, 254, 225, 48, 90,
  23556. 188,
  23557. ],
  23558. [
  23559. 15, 195, 244, 9, 233, 71, 168, 2, 188, 160, 153, 145, 253, 79, 108, 82, 27,
  23560. 174, 186, 172,
  23561. ],
  23562. [
  23563. 52, 190, 88, 205, 109, 39, 176, 21, 155, 197, 251, 223, 155, 21, 5, 172,
  23564. 254, 124, 12, 181, 184, 96, 50, 193,
  23565. ],
  23566. [
  23567. 211, 231, 43, 97, 71, 96, 103, 174, 37, 151, 170, 53, 75, 34, 249, 121, 17,
  23568. 138, 110, 213, 141, 136, 120, 151, 233, 168, 93, 255,
  23569. ],
  23570. [
  23571. 245, 127, 242, 218, 130, 250, 162, 181, 102, 120, 84, 179, 220, 251, 80,
  23572. 182, 229, 18, 2, 4, 68, 33, 101, 137, 95, 119, 115, 44, 175, 184, 59, 25,
  23573. 225, 98, 81, 112,
  23574. ],
  23575. [
  23576. 77, 193, 137, 31, 19, 38, 22, 153, 247, 105, 122, 2, 245, 133, 242, 8, 175,
  23577. 95, 100, 9, 167, 105, 214, 111, 57, 121, 21, 1, 253, 57, 54, 101, 248, 202,
  23578. 69, 50, 150, 177, 226, 5, 9, 5,
  23579. ],
  23580. [
  23581. 245, 132, 172, 223, 96, 32, 117, 22, 238, 133, 238, 231, 205, 188, 237, 87,
  23582. 191, 106, 16, 147, 118, 23, 37, 90, 170, 205, 131, 88, 120, 100, 66, 138,
  23583. 186, 240, 82, 44, 176, 87, 187, 147, 160, 175, 69, 213, 92, 253, 225, 19,
  23584. ],
  23585. [
  23586. 175, 9, 223, 238, 12, 17, 220, 208, 100, 29, 175, 170, 230, 192, 215, 235,
  23587. 150, 159, 36, 223, 38, 200, 132, 54, 228, 146, 218, 234, 117, 203, 29, 232,
  23588. 144, 238, 22, 150, 201, 117, 62, 207, 164, 13, 137, 245, 127, 67, 247, 28,
  23589. 155, 43, 203, 107, 233, 53, 143, 46,
  23590. ],
  23591. [
  23592. 242, 93, 169, 50, 144, 210, 39, 118, 202, 188, 201, 189, 143, 108, 196, 37,
  23593. 185, 112, 134, 230, 245, 63, 197, 190, 250, 106, 185, 221, 175, 64, 114, 71,
  23594. 161, 44, 147, 6, 27, 218, 51, 63, 87, 10, 40, 130, 188, 17, 163, 31, 176,
  23595. 170, 4, 107, 232, 7, 94, 166, 224, 124, 86, 47, 11, 204,
  23596. ],
  23597. [
  23598. 220, 228, 173, 89, 251, 149, 159, 56, 89, 33, 147, 244, 154, 36, 73, 127,
  23599. 213, 136, 248, 180, 234, 197, 158, 177, 68, 122, 93, 213, 15, 160, 227, 236,
  23600. 66, 139, 153, 185, 202, 167, 179, 25, 220, 232, 96, 210, 231, 136, 223, 239,
  23601. 181, 241, 59, 52, 172, 25, 49, 232, 211, 189, 64, 54, 108, 153, 132, 63, 96,
  23602. 103, 82, 186,
  23603. ],
  23604. ];
  23605. const /*final*/ MODULO_VALUE = 0x12d;
  23606. const static_LOG = (LOG, ALOG) => {
  23607. let p = 1;
  23608. for (let i = 0; i < 255; i++) {
  23609. ALOG[i] = p;
  23610. LOG[p] = i;
  23611. p *= 2;
  23612. if (p >= 256) {
  23613. p ^= MODULO_VALUE;
  23614. }
  23615. }
  23616. return {
  23617. LOG,
  23618. ALOG,
  23619. };
  23620. };
  23621. const { LOG, ALOG } = static_LOG([], []);
  23622. (function (SymbolShapeHint) {
  23623. SymbolShapeHint[SymbolShapeHint["FORCE_NONE"] = 0] = "FORCE_NONE";
  23624. SymbolShapeHint[SymbolShapeHint["FORCE_SQUARE"] = 1] = "FORCE_SQUARE";
  23625. SymbolShapeHint[SymbolShapeHint["FORCE_RECTANGLE"] = 2] = "FORCE_RECTANGLE";
  23626. })(exports.DataMatrixSymbolShapeHint || (exports.DataMatrixSymbolShapeHint = {}));
  23627. /**
  23628. * Padding character
  23629. */
  23630. const PAD = 129;
  23631. /**
  23632. * mode latch to C40 encodation mode
  23633. */
  23634. const LATCH_TO_C40 = 230;
  23635. /**
  23636. * mode latch to Base 256 encodation mode
  23637. */
  23638. const LATCH_TO_BASE256 = 231;
  23639. /**
  23640. * FNC1 Codeword
  23641. */
  23642. // private static FNC1 = 232;
  23643. /**
  23644. * Structured Append Codeword
  23645. */
  23646. // private static STRUCTURED_APPEND = 233;
  23647. /**
  23648. * Reader Programming
  23649. */
  23650. // private static READER_PROGRAMMING = 234;
  23651. /**
  23652. * Upper Shift
  23653. */
  23654. const UPPER_SHIFT = 235;
  23655. /**
  23656. * 05 Macro
  23657. */
  23658. const MACRO_05 = 236;
  23659. /**
  23660. * 06 Macro
  23661. */
  23662. const MACRO_06 = 237;
  23663. /**
  23664. * mode latch to ANSI X.12 encodation mode
  23665. */
  23666. const LATCH_TO_ANSIX12 = 238;
  23667. /**
  23668. * mode latch to Text encodation mode
  23669. */
  23670. const LATCH_TO_TEXT = 239;
  23671. /**
  23672. * mode latch to EDIFACT encodation mode
  23673. */
  23674. const LATCH_TO_EDIFACT = 240;
  23675. /**
  23676. * ECI character (Extended Channel Interpretation)
  23677. */
  23678. // private export const ECI = 241;
  23679. /**
  23680. * Unlatch from C40 encodation
  23681. */
  23682. const C40_UNLATCH = 254;
  23683. /**
  23684. * Unlatch from X12 encodation
  23685. */
  23686. const X12_UNLATCH = 254;
  23687. /**
  23688. * 05 Macro header
  23689. */
  23690. const MACRO_05_HEADER = '[)>\u001E05\u001D';
  23691. /**
  23692. * 06 Macro header
  23693. */
  23694. const MACRO_06_HEADER = '[)>\u001E06\u001D';
  23695. /**
  23696. * Macro trailer
  23697. */
  23698. const MACRO_TRAILER = '\u001E\u0004';
  23699. const ASCII_ENCODATION = 0;
  23700. const C40_ENCODATION = 1;
  23701. const TEXT_ENCODATION = 2;
  23702. const X12_ENCODATION = 3;
  23703. const EDIFACT_ENCODATION = 4;
  23704. const BASE256_ENCODATION = 5;
  23705. /**
  23706. * Error Correction Code for ECC200.
  23707. */
  23708. class ErrorCorrection$1 {
  23709. /**
  23710. * Creates the ECC200 error correction for an encoded message.
  23711. *
  23712. * @param codewords the codewords
  23713. * @param symbolInfo information about the symbol to be encoded
  23714. * @return the codewords with interleaved error correction.
  23715. */
  23716. static encodeECC200(codewords, symbolInfo) {
  23717. if (codewords.length !== symbolInfo.getDataCapacity()) {
  23718. throw new Error('The number of codewords does not match the selected symbol');
  23719. }
  23720. const sb = new StringBuilder();
  23721. sb.append(codewords);
  23722. const blockCount = symbolInfo.getInterleavedBlockCount();
  23723. if (blockCount === 1) {
  23724. const ecc = this.createECCBlock(codewords, symbolInfo.getErrorCodewords());
  23725. sb.append(ecc);
  23726. }
  23727. else {
  23728. // sb.setLength(sb.capacity());
  23729. const dataSizes = [];
  23730. const errorSizes = [];
  23731. for (let i = 0; i < blockCount; i++) {
  23732. dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i + 1);
  23733. errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i + 1);
  23734. }
  23735. for (let block = 0; block < blockCount; block++) {
  23736. const temp = new StringBuilder();
  23737. for (let d = block; d < symbolInfo.getDataCapacity(); d += blockCount) {
  23738. temp.append(codewords.charAt(d));
  23739. }
  23740. const ecc = this.createECCBlock(temp.toString(), errorSizes[block]);
  23741. let pos = 0;
  23742. for (let e = block; e < errorSizes[block] * blockCount; e += blockCount) {
  23743. sb.setCharAt(symbolInfo.getDataCapacity() + e, ecc.charAt(pos++));
  23744. }
  23745. }
  23746. }
  23747. return sb.toString();
  23748. }
  23749. static createECCBlock(codewords, numECWords) {
  23750. let table = -1;
  23751. for (let i = 0; i < FACTOR_SETS.length; i++) {
  23752. if (FACTOR_SETS[i] === numECWords) {
  23753. table = i;
  23754. break;
  23755. }
  23756. }
  23757. if (table < 0) {
  23758. throw new Error('Illegal number of error correction codewords specified: ' + numECWords);
  23759. }
  23760. const poly = FACTORS[table];
  23761. const ecc = [];
  23762. for (let i = 0; i < numECWords; i++) {
  23763. ecc[i] = 0;
  23764. }
  23765. for (let i = 0; i < codewords.length; i++) {
  23766. let m = ecc[numECWords - 1] ^ codewords.charAt(i).charCodeAt(0);
  23767. for (let k = numECWords - 1; k > 0; k--) {
  23768. if (m !== 0 && poly[k] !== 0) {
  23769. ecc[k] = ecc[k - 1] ^ ALOG[(LOG[m] + LOG[poly[k]]) % 255];
  23770. }
  23771. else {
  23772. ecc[k] = ecc[k - 1];
  23773. }
  23774. }
  23775. if (m !== 0 && poly[0] !== 0) {
  23776. ecc[0] = ALOG[(LOG[m] + LOG[poly[0]]) % 255];
  23777. }
  23778. else {
  23779. ecc[0] = 0;
  23780. }
  23781. }
  23782. const eccReversed = [];
  23783. for (let i = 0; i < numECWords; i++) {
  23784. eccReversed[i] = ecc[numECWords - i - 1];
  23785. }
  23786. return eccReversed.map(c => String.fromCharCode(c)).join('');
  23787. }
  23788. }
  23789. class ASCIIEncoder {
  23790. getEncodingMode() {
  23791. return ASCII_ENCODATION;
  23792. }
  23793. encode(context) {
  23794. // step B
  23795. const n = HighLevelEncoder.determineConsecutiveDigitCount(context.getMessage(), context.pos);
  23796. if (n >= 2) {
  23797. context.writeCodeword(this.encodeASCIIDigits(context.getMessage().charCodeAt(context.pos), context.getMessage().charCodeAt(context.pos + 1)));
  23798. context.pos += 2;
  23799. }
  23800. else {
  23801. const c = context.getCurrentChar();
  23802. const newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());
  23803. if (newMode !== this.getEncodingMode()) {
  23804. switch (newMode) {
  23805. case BASE256_ENCODATION:
  23806. context.writeCodeword(LATCH_TO_BASE256);
  23807. context.signalEncoderChange(BASE256_ENCODATION);
  23808. return;
  23809. case C40_ENCODATION:
  23810. context.writeCodeword(LATCH_TO_C40);
  23811. context.signalEncoderChange(C40_ENCODATION);
  23812. return;
  23813. case X12_ENCODATION:
  23814. context.writeCodeword(LATCH_TO_ANSIX12);
  23815. context.signalEncoderChange(X12_ENCODATION);
  23816. break;
  23817. case TEXT_ENCODATION:
  23818. context.writeCodeword(LATCH_TO_TEXT);
  23819. context.signalEncoderChange(TEXT_ENCODATION);
  23820. break;
  23821. case EDIFACT_ENCODATION:
  23822. context.writeCodeword(LATCH_TO_EDIFACT);
  23823. context.signalEncoderChange(EDIFACT_ENCODATION);
  23824. break;
  23825. default:
  23826. throw new Error('Illegal mode: ' + newMode);
  23827. }
  23828. }
  23829. else if (HighLevelEncoder.isExtendedASCII(c)) {
  23830. context.writeCodeword(UPPER_SHIFT);
  23831. context.writeCodeword(c - 128 + 1);
  23832. context.pos++;
  23833. }
  23834. else {
  23835. context.writeCodeword(c + 1);
  23836. context.pos++;
  23837. }
  23838. }
  23839. }
  23840. encodeASCIIDigits(digit1, digit2) {
  23841. if (HighLevelEncoder.isDigit(digit1) && HighLevelEncoder.isDigit(digit2)) {
  23842. const num = (digit1 - 48) * 10 + (digit2 - 48);
  23843. return num + 130;
  23844. }
  23845. throw new Error('not digits: ' + digit1 + digit2);
  23846. }
  23847. }
  23848. class Base256Encoder {
  23849. getEncodingMode() {
  23850. return BASE256_ENCODATION;
  23851. }
  23852. encode(context) {
  23853. const buffer = new StringBuilder();
  23854. buffer.append(0o0); // Initialize length field
  23855. while (context.hasMoreCharacters()) {
  23856. const c = context.getCurrentChar();
  23857. buffer.append(c);
  23858. context.pos++;
  23859. const newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());
  23860. if (newMode !== this.getEncodingMode()) {
  23861. // Return to ASCII encodation, which will actually handle latch to new mode
  23862. context.signalEncoderChange(ASCII_ENCODATION);
  23863. break;
  23864. }
  23865. }
  23866. const dataCount = buffer.length() - 1;
  23867. const lengthFieldSize = 1;
  23868. const currentSize = context.getCodewordCount() + dataCount + lengthFieldSize;
  23869. context.updateSymbolInfo(currentSize);
  23870. const mustPad = context.getSymbolInfo().getDataCapacity() - currentSize > 0;
  23871. if (context.hasMoreCharacters() || mustPad) {
  23872. if (dataCount <= 249) {
  23873. buffer.setCharAt(0, StringUtils.getCharAt(dataCount));
  23874. }
  23875. else if (dataCount <= 1555) {
  23876. buffer.setCharAt(0, StringUtils.getCharAt(Math.floor(dataCount / 250) + 249));
  23877. buffer.insert(1, StringUtils.getCharAt(dataCount % 250));
  23878. }
  23879. else {
  23880. throw new Error('Message length not in valid ranges: ' + dataCount);
  23881. }
  23882. }
  23883. for (let i = 0, c = buffer.length(); i < c; i++) {
  23884. context.writeCodeword(this.randomize255State(buffer.charAt(i).charCodeAt(0), context.getCodewordCount() + 1));
  23885. }
  23886. }
  23887. randomize255State(ch, codewordPosition) {
  23888. const pseudoRandom = ((149 * codewordPosition) % 255) + 1;
  23889. const tempVariable = ch + pseudoRandom;
  23890. if (tempVariable <= 255) {
  23891. return tempVariable;
  23892. }
  23893. else {
  23894. return tempVariable - 256;
  23895. }
  23896. }
  23897. }
  23898. class C40Encoder {
  23899. getEncodingMode() {
  23900. return C40_ENCODATION;
  23901. }
  23902. encodeMaximal(context) {
  23903. const buffer = new StringBuilder();
  23904. let lastCharSize = 0;
  23905. let backtrackStartPosition = context.pos;
  23906. let backtrackBufferLength = 0;
  23907. while (context.hasMoreCharacters()) {
  23908. const c = context.getCurrentChar();
  23909. context.pos++;
  23910. lastCharSize = this.encodeChar(c, buffer);
  23911. if (buffer.length() % 3 === 0) {
  23912. backtrackStartPosition = context.pos;
  23913. backtrackBufferLength = buffer.length();
  23914. }
  23915. }
  23916. if (backtrackBufferLength !== buffer.length()) {
  23917. const unwritten = Math.floor((buffer.length() / 3) * 2);
  23918. const curCodewordCount = Math.floor(context.getCodewordCount() + unwritten + 1); // +1 for the latch to C40
  23919. context.updateSymbolInfo(curCodewordCount);
  23920. const available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;
  23921. const rest = Math.floor(buffer.length() % 3);
  23922. if ((rest === 2 && available !== 2) ||
  23923. (rest === 1 && (lastCharSize > 3 || available !== 1))) {
  23924. // buffer.setLength(backtrackBufferLength);
  23925. context.pos = backtrackStartPosition;
  23926. }
  23927. }
  23928. if (buffer.length() > 0) {
  23929. context.writeCodeword(LATCH_TO_C40);
  23930. }
  23931. this.handleEOD(context, buffer);
  23932. }
  23933. encode(context) {
  23934. // step C
  23935. const buffer = new StringBuilder();
  23936. while (context.hasMoreCharacters()) {
  23937. const c = context.getCurrentChar();
  23938. context.pos++;
  23939. let lastCharSize = this.encodeChar(c, buffer);
  23940. const unwritten = Math.floor(buffer.length() / 3) * 2;
  23941. const curCodewordCount = context.getCodewordCount() + unwritten;
  23942. context.updateSymbolInfo(curCodewordCount);
  23943. const available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;
  23944. if (!context.hasMoreCharacters()) {
  23945. // Avoid having a single C40 value in the last triplet
  23946. const removed = new StringBuilder();
  23947. if (buffer.length() % 3 === 2 && available !== 2) {
  23948. lastCharSize = this.backtrackOneCharacter(context, buffer, removed, lastCharSize);
  23949. }
  23950. while (buffer.length() % 3 === 1 &&
  23951. (lastCharSize > 3 || available !== 1)) {
  23952. lastCharSize = this.backtrackOneCharacter(context, buffer, removed, lastCharSize);
  23953. }
  23954. break;
  23955. }
  23956. const count = buffer.length();
  23957. if (count % 3 === 0) {
  23958. const newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());
  23959. if (newMode !== this.getEncodingMode()) {
  23960. // Return to ASCII encodation, which will actually handle latch to new mode
  23961. context.signalEncoderChange(ASCII_ENCODATION);
  23962. break;
  23963. }
  23964. }
  23965. }
  23966. this.handleEOD(context, buffer);
  23967. }
  23968. backtrackOneCharacter(context, buffer, removed, lastCharSize) {
  23969. const count = buffer.length();
  23970. const test = buffer.toString().substring(0, count - lastCharSize);
  23971. buffer.setLengthToZero();
  23972. buffer.append(test);
  23973. // buffer.delete(count - lastCharSize, count);
  23974. /*for (let i = count - lastCharSize; i < count; i++) {
  23975. buffer.deleteCharAt(i);
  23976. }*/
  23977. context.pos--;
  23978. const c = context.getCurrentChar();
  23979. lastCharSize = this.encodeChar(c, removed);
  23980. context.resetSymbolInfo(); // Deal with possible reduction in symbol size
  23981. return lastCharSize;
  23982. }
  23983. writeNextTriplet(context, buffer) {
  23984. context.writeCodewords(this.encodeToCodewords(buffer.toString()));
  23985. const test = buffer.toString().substring(3);
  23986. buffer.setLengthToZero();
  23987. buffer.append(test);
  23988. // buffer.delete(0, 3);
  23989. /*for (let i = 0; i < 3; i++) {
  23990. buffer.deleteCharAt(i);
  23991. }*/
  23992. }
  23993. /**
  23994. * Handle "end of data" situations
  23995. *
  23996. * @param context the encoder context
  23997. * @param buffer the buffer with the remaining encoded characters
  23998. */
  23999. handleEOD(context, buffer) {
  24000. const unwritten = Math.floor((buffer.length() / 3) * 2);
  24001. const rest = buffer.length() % 3;
  24002. const curCodewordCount = context.getCodewordCount() + unwritten;
  24003. context.updateSymbolInfo(curCodewordCount);
  24004. const available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;
  24005. if (rest === 2) {
  24006. buffer.append('\0'); // Shift 1
  24007. while (buffer.length() >= 3) {
  24008. this.writeNextTriplet(context, buffer);
  24009. }
  24010. if (context.hasMoreCharacters()) {
  24011. context.writeCodeword(C40_UNLATCH);
  24012. }
  24013. }
  24014. else if (available === 1 && rest === 1) {
  24015. while (buffer.length() >= 3) {
  24016. this.writeNextTriplet(context, buffer);
  24017. }
  24018. if (context.hasMoreCharacters()) {
  24019. context.writeCodeword(C40_UNLATCH);
  24020. }
  24021. // else no unlatch
  24022. context.pos--;
  24023. }
  24024. else if (rest === 0) {
  24025. while (buffer.length() >= 3) {
  24026. this.writeNextTriplet(context, buffer);
  24027. }
  24028. if (available > 0 || context.hasMoreCharacters()) {
  24029. context.writeCodeword(C40_UNLATCH);
  24030. }
  24031. }
  24032. else {
  24033. throw new Error('Unexpected case. Please report!');
  24034. }
  24035. context.signalEncoderChange(ASCII_ENCODATION);
  24036. }
  24037. encodeChar(c, sb) {
  24038. if (c === ' '.charCodeAt(0)) {
  24039. sb.append(0o3);
  24040. return 1;
  24041. }
  24042. if (c >= '0'.charCodeAt(0) && c <= '9'.charCodeAt(0)) {
  24043. sb.append(c - 48 + 4);
  24044. return 1;
  24045. }
  24046. if (c >= 'A'.charCodeAt(0) && c <= 'Z'.charCodeAt(0)) {
  24047. sb.append(c - 65 + 14);
  24048. return 1;
  24049. }
  24050. if (c < ' '.charCodeAt(0)) {
  24051. sb.append(0o0); // Shift 1 Set
  24052. sb.append(c);
  24053. return 2;
  24054. }
  24055. if (c <= '/'.charCodeAt(0)) {
  24056. sb.append(0o1); // Shift 2 Set
  24057. sb.append(c - 33);
  24058. return 2;
  24059. }
  24060. if (c <= '@'.charCodeAt(0)) {
  24061. sb.append(0o1); // Shift 2 Set
  24062. sb.append(c - 58 + 15);
  24063. return 2;
  24064. }
  24065. if (c <= '_'.charCodeAt(0)) {
  24066. sb.append(0o1); // Shift 2 Set
  24067. sb.append(c - 91 + 22);
  24068. return 2;
  24069. }
  24070. if (c <= 127) {
  24071. sb.append(0o2); // Shift 3 Set
  24072. sb.append(c - 96);
  24073. return 2;
  24074. }
  24075. sb.append(`${0o1}\u001e`); // Shift 2, Upper Shift
  24076. let len = 2;
  24077. len += this.encodeChar(c - 128, sb);
  24078. return len;
  24079. }
  24080. encodeToCodewords(sb) {
  24081. const v = 1600 * sb.charCodeAt(0) + 40 * sb.charCodeAt(1) + sb.charCodeAt(2) + 1;
  24082. const cw1 = v / 256;
  24083. const cw2 = v % 256;
  24084. const result = new StringBuilder();
  24085. result.append(cw1);
  24086. result.append(cw2);
  24087. return result.toString();
  24088. }
  24089. }
  24090. class EdifactEncoder {
  24091. getEncodingMode() {
  24092. return EDIFACT_ENCODATION;
  24093. }
  24094. encode(context) {
  24095. // step F
  24096. const buffer = new StringBuilder();
  24097. while (context.hasMoreCharacters()) {
  24098. const c = context.getCurrentChar();
  24099. this.encodeChar(c, buffer);
  24100. context.pos++;
  24101. const count = buffer.length();
  24102. if (count >= 4) {
  24103. context.writeCodewords(this.encodeToCodewords(buffer.toString()));
  24104. const test = buffer.toString().substring(4);
  24105. buffer.setLengthToZero();
  24106. buffer.append(test);
  24107. // buffer.delete(0, 4);
  24108. // for (let i = 0; i < 4; i++) {
  24109. // buffer.deleteCharAt(i);
  24110. // }
  24111. const newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());
  24112. if (newMode !== this.getEncodingMode()) {
  24113. // Return to ASCII encodation, which will actually handle latch to new mode
  24114. context.signalEncoderChange(ASCII_ENCODATION);
  24115. break;
  24116. }
  24117. }
  24118. }
  24119. buffer.append(StringUtils.getCharAt(31)); // Unlatch
  24120. this.handleEOD(context, buffer);
  24121. }
  24122. /**
  24123. * Handle "end of data" situations
  24124. *
  24125. * @param context the encoder context
  24126. * @param buffer the buffer with the remaining encoded characters
  24127. */
  24128. handleEOD(context, buffer) {
  24129. try {
  24130. const count = buffer.length();
  24131. if (count === 0) {
  24132. return; // Already finished
  24133. }
  24134. if (count === 1) {
  24135. // Only an unlatch at the end
  24136. context.updateSymbolInfo();
  24137. let available = context.getSymbolInfo().getDataCapacity() -
  24138. context.getCodewordCount();
  24139. const remaining = context.getRemainingCharacters();
  24140. // The following two lines are a hack inspired by the 'fix' from https://sourceforge.net/p/barcode4j/svn/221/
  24141. if (remaining > available) {
  24142. context.updateSymbolInfo(context.getCodewordCount() + 1);
  24143. available =
  24144. context.getSymbolInfo().getDataCapacity() -
  24145. context.getCodewordCount();
  24146. }
  24147. if (remaining <= available && available <= 2) {
  24148. return; // No unlatch
  24149. }
  24150. }
  24151. if (count > 4) {
  24152. throw new Error('Count must not exceed 4');
  24153. }
  24154. const restChars = count - 1;
  24155. const encoded = this.encodeToCodewords(buffer.toString());
  24156. const endOfSymbolReached = !context.hasMoreCharacters();
  24157. let restInAscii = endOfSymbolReached && restChars <= 2;
  24158. if (restChars <= 2) {
  24159. context.updateSymbolInfo(context.getCodewordCount() + restChars);
  24160. const available = context.getSymbolInfo().getDataCapacity() -
  24161. context.getCodewordCount();
  24162. if (available >= 3) {
  24163. restInAscii = false;
  24164. context.updateSymbolInfo(context.getCodewordCount() + encoded.length);
  24165. // available = context.symbolInfo.dataCapacity - context.getCodewordCount();
  24166. }
  24167. }
  24168. if (restInAscii) {
  24169. context.resetSymbolInfo();
  24170. context.pos -= restChars;
  24171. }
  24172. else {
  24173. context.writeCodewords(encoded);
  24174. }
  24175. }
  24176. finally {
  24177. context.signalEncoderChange(ASCII_ENCODATION);
  24178. }
  24179. }
  24180. encodeChar(c, sb) {
  24181. if (c >= ' '.charCodeAt(0) && c <= '?'.charCodeAt(0)) {
  24182. sb.append(c);
  24183. }
  24184. else if (c >= '@'.charCodeAt(0) && c <= '^'.charCodeAt(0)) {
  24185. sb.append(StringUtils.getCharAt(c - 64));
  24186. }
  24187. else {
  24188. HighLevelEncoder.illegalCharacter(StringUtils.getCharAt(c));
  24189. }
  24190. }
  24191. encodeToCodewords(sb) {
  24192. const len = sb.length;
  24193. if (len === 0) {
  24194. throw new Error('StringBuilder must not be empty');
  24195. }
  24196. const c1 = sb.charAt(0).charCodeAt(0);
  24197. const c2 = len >= 2 ? sb.charAt(1).charCodeAt(0) : 0;
  24198. const c3 = len >= 3 ? sb.charAt(2).charCodeAt(0) : 0;
  24199. const c4 = len >= 4 ? sb.charAt(3).charCodeAt(0) : 0;
  24200. const v = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4;
  24201. const cw1 = (v >> 16) & 255;
  24202. const cw2 = (v >> 8) & 255;
  24203. const cw3 = v & 255;
  24204. const res = new StringBuilder();
  24205. res.append(cw1);
  24206. if (len >= 2) {
  24207. res.append(cw2);
  24208. }
  24209. if (len >= 3) {
  24210. res.append(cw3);
  24211. }
  24212. return res.toString();
  24213. }
  24214. }
  24215. /**
  24216. * Symbol info table for DataMatrix.
  24217. */
  24218. class SymbolInfo {
  24219. constructor(rectangular, dataCapacity, errorCodewords, matrixWidth, matrixHeight, dataRegions, rsBlockData = 0, rsBlockError = 0) {
  24220. this.rectangular = rectangular;
  24221. this.dataCapacity = dataCapacity;
  24222. this.errorCodewords = errorCodewords;
  24223. this.matrixWidth = matrixWidth;
  24224. this.matrixHeight = matrixHeight;
  24225. this.dataRegions = dataRegions;
  24226. this.rsBlockData = rsBlockData;
  24227. this.rsBlockError = rsBlockError;
  24228. }
  24229. static lookup(dataCodewords, shape = 0 /* FORCE_NONE */, minSize = null, maxSize = null, fail = true) {
  24230. for (const symbol of PROD_SYMBOLS) {
  24231. if (shape === 1 /* FORCE_SQUARE */ && symbol.rectangular) {
  24232. continue;
  24233. }
  24234. if (shape === 2 /* FORCE_RECTANGLE */ && !symbol.rectangular) {
  24235. continue;
  24236. }
  24237. if (minSize != null &&
  24238. (symbol.getSymbolWidth() < minSize.getWidth() ||
  24239. symbol.getSymbolHeight() < minSize.getHeight())) {
  24240. continue;
  24241. }
  24242. if (maxSize != null &&
  24243. (symbol.getSymbolWidth() > maxSize.getWidth() ||
  24244. symbol.getSymbolHeight() > maxSize.getHeight())) {
  24245. continue;
  24246. }
  24247. if (dataCodewords <= symbol.dataCapacity) {
  24248. return symbol;
  24249. }
  24250. }
  24251. if (fail) {
  24252. throw new Error("Can't find a symbol arrangement that matches the message. Data codewords: " +
  24253. dataCodewords);
  24254. }
  24255. return null;
  24256. }
  24257. getHorizontalDataRegions() {
  24258. switch (this.dataRegions) {
  24259. case 1:
  24260. return 1;
  24261. case 2:
  24262. case 4:
  24263. return 2;
  24264. case 16:
  24265. return 4;
  24266. case 36:
  24267. return 6;
  24268. default:
  24269. throw new Error('Cannot handle this number of data regions');
  24270. }
  24271. }
  24272. getVerticalDataRegions() {
  24273. switch (this.dataRegions) {
  24274. case 1:
  24275. case 2:
  24276. return 1;
  24277. case 4:
  24278. return 2;
  24279. case 16:
  24280. return 4;
  24281. case 36:
  24282. return 6;
  24283. default:
  24284. throw new Error('Cannot handle this number of data regions');
  24285. }
  24286. }
  24287. getSymbolDataWidth() {
  24288. return this.getHorizontalDataRegions() * this.matrixWidth;
  24289. }
  24290. getSymbolDataHeight() {
  24291. return this.getVerticalDataRegions() * this.matrixHeight;
  24292. }
  24293. getSymbolWidth() {
  24294. return this.getSymbolDataWidth() + this.getHorizontalDataRegions() * 2;
  24295. }
  24296. getSymbolHeight() {
  24297. return this.getSymbolDataHeight() + this.getVerticalDataRegions() * 2;
  24298. }
  24299. getCodewordCount() {
  24300. return this.dataCapacity + this.errorCodewords;
  24301. }
  24302. getInterleavedBlockCount() {
  24303. if (!this.rsBlockData)
  24304. return 1;
  24305. return this.dataCapacity / this.rsBlockData;
  24306. }
  24307. getDataCapacity() {
  24308. return this.dataCapacity;
  24309. }
  24310. getErrorCodewords() {
  24311. return this.errorCodewords;
  24312. }
  24313. getDataLengthForInterleavedBlock(index) {
  24314. return this.rsBlockData;
  24315. }
  24316. getErrorLengthForInterleavedBlock(index) {
  24317. return this.rsBlockError;
  24318. }
  24319. }
  24320. class DataMatrixSymbolInfo144 extends SymbolInfo {
  24321. constructor() {
  24322. super(false, 1558, 620, 22, 22, 36, -1, 62);
  24323. }
  24324. getInterleavedBlockCount() {
  24325. return 10;
  24326. }
  24327. getDataLengthForInterleavedBlock(index) {
  24328. return index <= 8 ? 156 : 155;
  24329. }
  24330. }
  24331. const PROD_SYMBOLS = [
  24332. new SymbolInfo(false, 3, 5, 8, 8, 1),
  24333. new SymbolInfo(false, 5, 7, 10, 10, 1),
  24334. /*rect*/ new SymbolInfo(true, 5, 7, 16, 6, 1),
  24335. new SymbolInfo(false, 8, 10, 12, 12, 1),
  24336. /*rect*/ new SymbolInfo(true, 10, 11, 14, 6, 2),
  24337. new SymbolInfo(false, 12, 12, 14, 14, 1),
  24338. /*rect*/ new SymbolInfo(true, 16, 14, 24, 10, 1),
  24339. new SymbolInfo(false, 18, 14, 16, 16, 1),
  24340. new SymbolInfo(false, 22, 18, 18, 18, 1),
  24341. /*rect*/ new SymbolInfo(true, 22, 18, 16, 10, 2),
  24342. new SymbolInfo(false, 30, 20, 20, 20, 1),
  24343. /*rect*/ new SymbolInfo(true, 32, 24, 16, 14, 2),
  24344. new SymbolInfo(false, 36, 24, 22, 22, 1),
  24345. new SymbolInfo(false, 44, 28, 24, 24, 1),
  24346. /*rect*/ new SymbolInfo(true, 49, 28, 22, 14, 2),
  24347. new SymbolInfo(false, 62, 36, 14, 14, 4),
  24348. new SymbolInfo(false, 86, 42, 16, 16, 4),
  24349. new SymbolInfo(false, 114, 48, 18, 18, 4),
  24350. new SymbolInfo(false, 144, 56, 20, 20, 4),
  24351. new SymbolInfo(false, 174, 68, 22, 22, 4),
  24352. new SymbolInfo(false, 204, 84, 24, 24, 4, 102, 42),
  24353. new SymbolInfo(false, 280, 112, 14, 14, 16, 140, 56),
  24354. new SymbolInfo(false, 368, 144, 16, 16, 16, 92, 36),
  24355. new SymbolInfo(false, 456, 192, 18, 18, 16, 114, 48),
  24356. new SymbolInfo(false, 576, 224, 20, 20, 16, 144, 56),
  24357. new SymbolInfo(false, 696, 272, 22, 22, 16, 174, 68),
  24358. new SymbolInfo(false, 816, 336, 24, 24, 16, 136, 56),
  24359. new SymbolInfo(false, 1050, 408, 18, 18, 36, 175, 68),
  24360. new SymbolInfo(false, 1304, 496, 20, 20, 36, 163, 62),
  24361. new DataMatrixSymbolInfo144(),
  24362. ];
  24363. class EncoderContext {
  24364. constructor(msg) {
  24365. this.msg = msg;
  24366. this.pos = 0;
  24367. this.skipAtEnd = 0;
  24368. // From this point on Strings are not Unicode anymore!
  24369. const msgBinary = msg.split('').map(c => c.charCodeAt(0));
  24370. const sb = new StringBuilder();
  24371. for (let i = 0, c = msgBinary.length; i < c; i++) {
  24372. const ch = String.fromCharCode(msgBinary[i] & 0xff);
  24373. if (ch === '?' && msg.charAt(i) !== '?') {
  24374. throw new Error('Message contains characters outside ISO-8859-1 encoding.');
  24375. }
  24376. sb.append(ch);
  24377. }
  24378. this.msg = sb.toString(); // Not Unicode here!
  24379. this.shape = 0 /* FORCE_NONE */;
  24380. this.codewords = new StringBuilder();
  24381. this.newEncoding = -1;
  24382. }
  24383. setSymbolShape(shape) {
  24384. this.shape = shape;
  24385. }
  24386. setSizeConstraints(minSize, maxSize) {
  24387. this.minSize = minSize;
  24388. this.maxSize = maxSize;
  24389. }
  24390. getMessage() {
  24391. return this.msg;
  24392. }
  24393. setSkipAtEnd(count) {
  24394. this.skipAtEnd = count;
  24395. }
  24396. getCurrentChar() {
  24397. return this.msg.charCodeAt(this.pos);
  24398. }
  24399. getCurrent() {
  24400. return this.msg.charCodeAt(this.pos);
  24401. }
  24402. getCodewords() {
  24403. return this.codewords;
  24404. }
  24405. writeCodewords(codewords) {
  24406. this.codewords.append(codewords);
  24407. }
  24408. writeCodeword(codeword) {
  24409. this.codewords.append(codeword);
  24410. }
  24411. getCodewordCount() {
  24412. return this.codewords.length();
  24413. }
  24414. getNewEncoding() {
  24415. return this.newEncoding;
  24416. }
  24417. signalEncoderChange(encoding) {
  24418. this.newEncoding = encoding;
  24419. }
  24420. resetEncoderSignal() {
  24421. this.newEncoding = -1;
  24422. }
  24423. hasMoreCharacters() {
  24424. return this.pos < this.getTotalMessageCharCount();
  24425. }
  24426. getTotalMessageCharCount() {
  24427. return this.msg.length - this.skipAtEnd;
  24428. }
  24429. getRemainingCharacters() {
  24430. return this.getTotalMessageCharCount() - this.pos;
  24431. }
  24432. getSymbolInfo() {
  24433. return this.symbolInfo;
  24434. }
  24435. updateSymbolInfo(len = this.getCodewordCount()) {
  24436. if (this.symbolInfo == null || len > this.symbolInfo.getDataCapacity()) {
  24437. this.symbolInfo = SymbolInfo.lookup(len, this.shape, this.minSize, this.maxSize, true);
  24438. }
  24439. }
  24440. resetSymbolInfo() {
  24441. this.symbolInfo = null;
  24442. }
  24443. }
  24444. class X12Encoder extends C40Encoder {
  24445. getEncodingMode() {
  24446. return X12_ENCODATION;
  24447. }
  24448. encode(context) {
  24449. // step C
  24450. const buffer = new StringBuilder();
  24451. while (context.hasMoreCharacters()) {
  24452. const c = context.getCurrentChar();
  24453. context.pos++;
  24454. this.encodeChar(c, buffer);
  24455. const count = buffer.length();
  24456. if (count % 3 === 0) {
  24457. this.writeNextTriplet(context, buffer);
  24458. const newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());
  24459. if (newMode !== this.getEncodingMode()) {
  24460. // Return to ASCII encodation, which will actually handle latch to new mode
  24461. context.signalEncoderChange(ASCII_ENCODATION);
  24462. break;
  24463. }
  24464. }
  24465. }
  24466. this.handleEOD(context, buffer);
  24467. }
  24468. encodeChar(c, sb) {
  24469. switch (c) {
  24470. case 13: // CR (Carriage return)
  24471. sb.append(0o0);
  24472. break;
  24473. case '*'.charCodeAt(0):
  24474. sb.append(0o1);
  24475. break;
  24476. case '>'.charCodeAt(0):
  24477. sb.append(0o2);
  24478. break;
  24479. case ' '.charCodeAt(0):
  24480. sb.append(0o3);
  24481. break;
  24482. default:
  24483. if (c >= '0'.charCodeAt(0) && c <= '9'.charCodeAt(0)) {
  24484. sb.append(c - 48 + 4);
  24485. }
  24486. else if (c >= 'A'.charCodeAt(0) && c <= 'Z'.charCodeAt(0)) {
  24487. sb.append(c - 65 + 14);
  24488. }
  24489. else {
  24490. HighLevelEncoder.illegalCharacter(StringUtils.getCharAt(c));
  24491. }
  24492. break;
  24493. }
  24494. return 1;
  24495. }
  24496. handleEOD(context, buffer) {
  24497. context.updateSymbolInfo();
  24498. const available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount();
  24499. const count = buffer.length();
  24500. context.pos -= count;
  24501. if (context.getRemainingCharacters() > 1 ||
  24502. available > 1 ||
  24503. context.getRemainingCharacters() !== available) {
  24504. context.writeCodeword(X12_UNLATCH);
  24505. }
  24506. if (context.getNewEncoding() < 0) {
  24507. context.signalEncoderChange(ASCII_ENCODATION);
  24508. }
  24509. }
  24510. }
  24511. class TextEncoder$1 extends C40Encoder {
  24512. getEncodingMode() {
  24513. return TEXT_ENCODATION;
  24514. }
  24515. encodeChar(c, sb) {
  24516. if (c === ' '.charCodeAt(0)) {
  24517. sb.append(0o3);
  24518. return 1;
  24519. }
  24520. if (c >= '0'.charCodeAt(0) && c <= '9'.charCodeAt(0)) {
  24521. sb.append(c - 48 + 4);
  24522. return 1;
  24523. }
  24524. if (c >= 'a'.charCodeAt(0) && c <= 'z'.charCodeAt(0)) {
  24525. sb.append(c - 97 + 14);
  24526. return 1;
  24527. }
  24528. if (c < ' '.charCodeAt(0)) {
  24529. sb.append(0o0); // Shift 1 Set
  24530. sb.append(c);
  24531. return 2;
  24532. }
  24533. if (c <= '/'.charCodeAt(0)) {
  24534. sb.append(0o1); // Shift 2 Set
  24535. sb.append(c - 33);
  24536. return 2;
  24537. }
  24538. if (c <= '@'.charCodeAt(0)) {
  24539. sb.append(0o1); // Shift 2 Set
  24540. sb.append(c - 58 + 15);
  24541. return 2;
  24542. }
  24543. if (c >= '['.charCodeAt(0) && c <= '_'.charCodeAt(0)) {
  24544. sb.append(0o1); // Shift 2 Set
  24545. sb.append(c - 91 + 22);
  24546. return 2;
  24547. }
  24548. if (c === '`'.charCodeAt(0)) {
  24549. sb.append(0o2); // Shift 3 Set
  24550. sb.append(0); // '`' - 96 == 0
  24551. return 2;
  24552. }
  24553. if (c <= 'Z'.charCodeAt(0)) {
  24554. sb.append(0o2); // Shift 3 Set
  24555. sb.append(c - 65 + 1);
  24556. return 2;
  24557. }
  24558. if (c <= 127) {
  24559. sb.append(0o2); // Shift 3 Set
  24560. sb.append(c - 123 + 27);
  24561. return 2;
  24562. }
  24563. sb.append(`${0o1}\u001e`); // Shift 2, Upper Shift
  24564. let len = 2;
  24565. len += this.encodeChar(c - 128, sb);
  24566. return len;
  24567. }
  24568. }
  24569. // tslint:disable-next-line:no-circular-imports
  24570. /**
  24571. * DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in
  24572. * annex S.
  24573. */
  24574. class HighLevelEncoder {
  24575. static randomize253State(codewordPosition) {
  24576. const pseudoRandom = ((149 * codewordPosition) % 253) + 1;
  24577. const tempVariable = PAD + pseudoRandom;
  24578. return tempVariable <= 254 ? tempVariable : tempVariable - 254;
  24579. }
  24580. /**
  24581. * Performs message encoding of a DataMatrix message using the algorithm described in annex P
  24582. * of ISO/IEC 16022:2000(E).
  24583. *
  24584. * @param msg the message
  24585. * @param shape requested shape. May be {@code SymbolShapeHint.FORCE_NONE},
  24586. * {@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}.
  24587. * @param minSize the minimum symbol size constraint or null for no constraint
  24588. * @param maxSize the maximum symbol size constraint or null for no constraint
  24589. * @param forceC40 enforce C40 encoding
  24590. * @return the encoded message (the char values range from 0 to 255)
  24591. */
  24592. static encodeHighLevel(msg, shape = 0 /* FORCE_NONE */, minSize = null, maxSize = null, forceC40 = false) {
  24593. // the codewords 0..255 are encoded as Unicode characters
  24594. const c40Encoder = new C40Encoder();
  24595. const encoders = [
  24596. new ASCIIEncoder(),
  24597. c40Encoder,
  24598. new TextEncoder$1(),
  24599. new X12Encoder(),
  24600. new EdifactEncoder(),
  24601. new Base256Encoder(),
  24602. ];
  24603. const context = new EncoderContext(msg);
  24604. context.setSymbolShape(shape);
  24605. context.setSizeConstraints(minSize, maxSize);
  24606. if (msg.startsWith(MACRO_05_HEADER) && msg.endsWith(MACRO_TRAILER)) {
  24607. context.writeCodeword(MACRO_05);
  24608. context.setSkipAtEnd(2);
  24609. context.pos += MACRO_05_HEADER.length;
  24610. }
  24611. else if (msg.startsWith(MACRO_06_HEADER) && msg.endsWith(MACRO_TRAILER)) {
  24612. context.writeCodeword(MACRO_06);
  24613. context.setSkipAtEnd(2);
  24614. context.pos += MACRO_06_HEADER.length;
  24615. }
  24616. let encodingMode = ASCII_ENCODATION; // Default mode
  24617. if (forceC40) {
  24618. c40Encoder.encodeMaximal(context);
  24619. encodingMode = context.getNewEncoding();
  24620. context.resetEncoderSignal();
  24621. }
  24622. while (context.hasMoreCharacters()) {
  24623. encoders[encodingMode].encode(context);
  24624. if (context.getNewEncoding() >= 0) {
  24625. encodingMode = context.getNewEncoding();
  24626. context.resetEncoderSignal();
  24627. }
  24628. }
  24629. const len = context.getCodewordCount();
  24630. context.updateSymbolInfo();
  24631. const capacity = context.getSymbolInfo().getDataCapacity();
  24632. if (len < capacity &&
  24633. encodingMode !== ASCII_ENCODATION &&
  24634. encodingMode !== BASE256_ENCODATION &&
  24635. encodingMode !== EDIFACT_ENCODATION) {
  24636. context.writeCodeword('\u00fe'); // Unlatch (254)
  24637. }
  24638. // Padding
  24639. const codewords = context.getCodewords();
  24640. if (codewords.length() < capacity) {
  24641. codewords.append(PAD);
  24642. }
  24643. while (codewords.length() < capacity) {
  24644. codewords.append(this.randomize253State(codewords.length() + 1));
  24645. }
  24646. return context.getCodewords().toString();
  24647. }
  24648. static lookAheadTest(msg, startpos, currentMode) {
  24649. const newMode = this.lookAheadTestIntern(msg, startpos, currentMode);
  24650. if (currentMode === X12_ENCODATION && newMode === X12_ENCODATION) {
  24651. const endpos = Math.min(startpos + 3, msg.length);
  24652. for (let i = startpos; i < endpos; i++) {
  24653. if (!this.isNativeX12(msg.charCodeAt(i))) {
  24654. return ASCII_ENCODATION;
  24655. }
  24656. }
  24657. }
  24658. else if (currentMode === EDIFACT_ENCODATION &&
  24659. newMode === EDIFACT_ENCODATION) {
  24660. const endpos = Math.min(startpos + 4, msg.length);
  24661. for (let i = startpos; i < endpos; i++) {
  24662. if (!this.isNativeEDIFACT(msg.charCodeAt(i))) {
  24663. return ASCII_ENCODATION;
  24664. }
  24665. }
  24666. }
  24667. return newMode;
  24668. }
  24669. static lookAheadTestIntern(msg, startpos, currentMode) {
  24670. if (startpos >= msg.length) {
  24671. return currentMode;
  24672. }
  24673. let charCounts;
  24674. // step J
  24675. if (currentMode === ASCII_ENCODATION) {
  24676. charCounts = [0, 1, 1, 1, 1, 1.25];
  24677. }
  24678. else {
  24679. charCounts = [1, 2, 2, 2, 2, 2.25];
  24680. charCounts[currentMode] = 0;
  24681. }
  24682. let charsProcessed = 0;
  24683. const mins = new Uint8Array(6);
  24684. const intCharCounts = [];
  24685. while (true) {
  24686. // step K
  24687. if (startpos + charsProcessed === msg.length) {
  24688. Arrays.fill(mins, 0);
  24689. Arrays.fill(intCharCounts, 0);
  24690. const min = this.findMinimums(charCounts, intCharCounts, Integer.MAX_VALUE, mins);
  24691. const minCount = this.getMinimumCount(mins);
  24692. if (intCharCounts[ASCII_ENCODATION] === min) {
  24693. return ASCII_ENCODATION;
  24694. }
  24695. if (minCount === 1) {
  24696. if (mins[BASE256_ENCODATION] > 0) {
  24697. return BASE256_ENCODATION;
  24698. }
  24699. if (mins[EDIFACT_ENCODATION] > 0) {
  24700. return EDIFACT_ENCODATION;
  24701. }
  24702. if (mins[TEXT_ENCODATION] > 0) {
  24703. return TEXT_ENCODATION;
  24704. }
  24705. if (mins[X12_ENCODATION] > 0) {
  24706. return X12_ENCODATION;
  24707. }
  24708. }
  24709. return C40_ENCODATION;
  24710. }
  24711. const c = msg.charCodeAt(startpos + charsProcessed);
  24712. charsProcessed++;
  24713. // step L
  24714. if (this.isDigit(c)) {
  24715. charCounts[ASCII_ENCODATION] += 0.5;
  24716. }
  24717. else if (this.isExtendedASCII(c)) {
  24718. charCounts[ASCII_ENCODATION] = Math.ceil(charCounts[ASCII_ENCODATION]);
  24719. charCounts[ASCII_ENCODATION] += 2.0;
  24720. }
  24721. else {
  24722. charCounts[ASCII_ENCODATION] = Math.ceil(charCounts[ASCII_ENCODATION]);
  24723. charCounts[ASCII_ENCODATION]++;
  24724. }
  24725. // step M
  24726. if (this.isNativeC40(c)) {
  24727. charCounts[C40_ENCODATION] += 2.0 / 3.0;
  24728. }
  24729. else if (this.isExtendedASCII(c)) {
  24730. charCounts[C40_ENCODATION] += 8.0 / 3.0;
  24731. }
  24732. else {
  24733. charCounts[C40_ENCODATION] += 4.0 / 3.0;
  24734. }
  24735. // step N
  24736. if (this.isNativeText(c)) {
  24737. charCounts[TEXT_ENCODATION] += 2.0 / 3.0;
  24738. }
  24739. else if (this.isExtendedASCII(c)) {
  24740. charCounts[TEXT_ENCODATION] += 8.0 / 3.0;
  24741. }
  24742. else {
  24743. charCounts[TEXT_ENCODATION] += 4.0 / 3.0;
  24744. }
  24745. // step O
  24746. if (this.isNativeX12(c)) {
  24747. charCounts[X12_ENCODATION] += 2.0 / 3.0;
  24748. }
  24749. else if (this.isExtendedASCII(c)) {
  24750. charCounts[X12_ENCODATION] += 13.0 / 3.0;
  24751. }
  24752. else {
  24753. charCounts[X12_ENCODATION] += 10.0 / 3.0;
  24754. }
  24755. // step P
  24756. if (this.isNativeEDIFACT(c)) {
  24757. charCounts[EDIFACT_ENCODATION] += 3.0 / 4.0;
  24758. }
  24759. else if (this.isExtendedASCII(c)) {
  24760. charCounts[EDIFACT_ENCODATION] += 17.0 / 4.0;
  24761. }
  24762. else {
  24763. charCounts[EDIFACT_ENCODATION] += 13.0 / 4.0;
  24764. }
  24765. // step Q
  24766. if (this.isSpecialB256(c)) {
  24767. charCounts[BASE256_ENCODATION] += 4.0;
  24768. }
  24769. else {
  24770. charCounts[BASE256_ENCODATION]++;
  24771. }
  24772. // step R
  24773. if (charsProcessed >= 4) {
  24774. Arrays.fill(mins, 0);
  24775. Arrays.fill(intCharCounts, 0);
  24776. this.findMinimums(charCounts, intCharCounts, Integer.MAX_VALUE, mins);
  24777. if (intCharCounts[ASCII_ENCODATION] <
  24778. this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[EDIFACT_ENCODATION])) {
  24779. return ASCII_ENCODATION;
  24780. }
  24781. if (intCharCounts[BASE256_ENCODATION] < intCharCounts[ASCII_ENCODATION] ||
  24782. intCharCounts[BASE256_ENCODATION] + 1 <
  24783. this.min(intCharCounts[C40_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[EDIFACT_ENCODATION])) {
  24784. return BASE256_ENCODATION;
  24785. }
  24786. if (intCharCounts[EDIFACT_ENCODATION] + 1 <
  24787. this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[ASCII_ENCODATION])) {
  24788. return EDIFACT_ENCODATION;
  24789. }
  24790. if (intCharCounts[TEXT_ENCODATION] + 1 <
  24791. this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[EDIFACT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[ASCII_ENCODATION])) {
  24792. return TEXT_ENCODATION;
  24793. }
  24794. if (intCharCounts[X12_ENCODATION] + 1 <
  24795. this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[EDIFACT_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[ASCII_ENCODATION])) {
  24796. return X12_ENCODATION;
  24797. }
  24798. if (intCharCounts[C40_ENCODATION] + 1 <
  24799. this.min(intCharCounts[ASCII_ENCODATION], intCharCounts[BASE256_ENCODATION], intCharCounts[EDIFACT_ENCODATION], intCharCounts[TEXT_ENCODATION])) {
  24800. if (intCharCounts[C40_ENCODATION] < intCharCounts[X12_ENCODATION]) {
  24801. return C40_ENCODATION;
  24802. }
  24803. if (intCharCounts[C40_ENCODATION] === intCharCounts[X12_ENCODATION]) {
  24804. let p = startpos + charsProcessed + 1;
  24805. while (p < msg.length) {
  24806. const tc = msg.charCodeAt(p);
  24807. if (this.isX12TermSep(tc)) {
  24808. return X12_ENCODATION;
  24809. }
  24810. if (!this.isNativeX12(tc)) {
  24811. break;
  24812. }
  24813. p++;
  24814. }
  24815. return C40_ENCODATION;
  24816. }
  24817. }
  24818. }
  24819. }
  24820. }
  24821. static min(f1, f2, f3, f4, f5) {
  24822. const val = Math.min(f1, Math.min(f2, Math.min(f3, f4)));
  24823. if (f5 === undefined) {
  24824. return val;
  24825. }
  24826. else {
  24827. return Math.min(val, f5);
  24828. }
  24829. }
  24830. static findMinimums(charCounts, intCharCounts, min, mins) {
  24831. for (let i = 0; i < 6; i++) {
  24832. const current = (intCharCounts[i] = Math.ceil(charCounts[i]));
  24833. if (min > current) {
  24834. min = current;
  24835. Arrays.fill(mins, 0);
  24836. }
  24837. if (min === current) {
  24838. mins[i] = mins[i] + 1;
  24839. }
  24840. }
  24841. return min;
  24842. }
  24843. static getMinimumCount(mins) {
  24844. let minCount = 0;
  24845. for (let i = 0; i < 6; i++) {
  24846. minCount += mins[i];
  24847. }
  24848. return minCount || 0;
  24849. }
  24850. static isDigit(ch) {
  24851. return ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0);
  24852. }
  24853. static isExtendedASCII(ch) {
  24854. return ch >= 128 && ch <= 255;
  24855. }
  24856. static isNativeC40(ch) {
  24857. return (ch === ' '.charCodeAt(0) ||
  24858. (ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0)) ||
  24859. (ch >= 'A'.charCodeAt(0) && ch <= 'Z'.charCodeAt(0)));
  24860. }
  24861. static isNativeText(ch) {
  24862. return (ch === ' '.charCodeAt(0) ||
  24863. (ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0)) ||
  24864. (ch >= 'a'.charCodeAt(0) && ch <= 'z'.charCodeAt(0)));
  24865. }
  24866. static isNativeX12(ch) {
  24867. return (this.isX12TermSep(ch) ||
  24868. ch === ' '.charCodeAt(0) ||
  24869. (ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0)) ||
  24870. (ch >= 'A'.charCodeAt(0) && ch <= 'Z'.charCodeAt(0)));
  24871. }
  24872. static isX12TermSep(ch) {
  24873. return (ch === 13 || // CR
  24874. ch === '*'.charCodeAt(0) ||
  24875. ch === '>'.charCodeAt(0));
  24876. }
  24877. static isNativeEDIFACT(ch) {
  24878. return ch >= ' '.charCodeAt(0) && ch <= '^'.charCodeAt(0);
  24879. }
  24880. static isSpecialB256(ch) {
  24881. return false; // TODO NOT IMPLEMENTED YET!!!
  24882. }
  24883. /**
  24884. * Determines the number of consecutive characters that are encodable using numeric compaction.
  24885. *
  24886. * @param msg the message
  24887. * @param startpos the start position within the message
  24888. * @return the requested character count
  24889. */
  24890. static determineConsecutiveDigitCount(msg, startpos = 0) {
  24891. const len = msg.length;
  24892. let idx = startpos;
  24893. while (idx < len && this.isDigit(msg.charCodeAt(idx))) {
  24894. idx++;
  24895. }
  24896. return idx - startpos;
  24897. }
  24898. static illegalCharacter(singleCharacter) {
  24899. let hex = Integer.toHexString(singleCharacter.charCodeAt(0));
  24900. hex = '0000'.substring(0, 4 - hex.length) + hex;
  24901. throw new Error('Illegal character: ' + singleCharacter + ' (0x' + hex + ')');
  24902. }
  24903. }
  24904. /**
  24905. * Set of CharsetEncoders for a given input string
  24906. *
  24907. * Invariants:
  24908. * - The list contains only encoders from CharacterSetECI (list is shorter then the list of encoders available on
  24909. * the platform for which ECI values are defined).
  24910. * - The list contains encoders at least one encoder for every character in the input.
  24911. * - The first encoder in the list is always the ISO-8859-1 encoder even of no character in the input can be encoded
  24912. * by it.
  24913. * - If the input contains a character that is not in ISO-8859-1 then the last two entries in the list will be the
  24914. * UTF-8 encoder and the UTF-16BE encoder.
  24915. *
  24916. * @author Alex Geller
  24917. */
  24918. class CharsetEncoder {
  24919. constructor(charset) {
  24920. this.charset = charset;
  24921. this.name = charset.name;
  24922. }
  24923. canEncode(c) {
  24924. try {
  24925. return StringEncoding.encode(c, this.charset) != null;
  24926. }
  24927. catch (ex) {
  24928. return false;
  24929. }
  24930. }
  24931. }
  24932. class ECIEncoderSet {
  24933. /**
  24934. * Constructs an encoder set
  24935. *
  24936. * @param stringToEncode the string that needs to be encoded
  24937. * @param priorityCharset The preferred {@link Charset} or null.
  24938. * @param fnc1 fnc1 denotes the character in the input that represents the FNC1 character or -1 for a non-GS1 bar
  24939. * code. When specified, it is considered an error to pass it as argument to the methods canEncode() or encode().
  24940. */
  24941. constructor(stringToEncode, priorityCharset, fnc1) {
  24942. this.ENCODERS = [
  24943. 'IBM437',
  24944. 'ISO-8859-2',
  24945. 'ISO-8859-3',
  24946. 'ISO-8859-4',
  24947. 'ISO-8859-5',
  24948. 'ISO-8859-6',
  24949. 'ISO-8859-7',
  24950. 'ISO-8859-8',
  24951. 'ISO-8859-9',
  24952. 'ISO-8859-10',
  24953. 'ISO-8859-11',
  24954. 'ISO-8859-13',
  24955. 'ISO-8859-14',
  24956. 'ISO-8859-15',
  24957. 'ISO-8859-16',
  24958. 'windows-1250',
  24959. 'windows-1251',
  24960. 'windows-1252',
  24961. 'windows-1256',
  24962. 'Shift_JIS',
  24963. ].map(name => new CharsetEncoder(Charset.forName(name)));
  24964. this.encoders = [];
  24965. const neededEncoders = [];
  24966. // we always need the ISO-8859-1 encoder. It is the default encoding
  24967. neededEncoders.push(new CharsetEncoder(StandardCharsets.ISO_8859_1));
  24968. let needUnicodeEncoder = priorityCharset != null && priorityCharset.name.startsWith('UTF');
  24969. // Walk over the input string and see if all characters can be encoded with the list of encoders
  24970. for (let i = 0; i < stringToEncode.length; i++) {
  24971. let canEncode = false;
  24972. for (const encoder of neededEncoders) {
  24973. const singleCharacter = stringToEncode.charAt(i);
  24974. const c = singleCharacter.charCodeAt(0);
  24975. if (c === fnc1 || encoder.canEncode(singleCharacter)) {
  24976. canEncode = true;
  24977. break;
  24978. }
  24979. }
  24980. if (!canEncode) {
  24981. // for the character at position i we don't yet have an encoder in the list
  24982. for (const encoder of this.ENCODERS) {
  24983. if (encoder.canEncode(stringToEncode.charAt(i))) {
  24984. // Good, we found an encoder that can encode the character. We add him to the list and continue scanning
  24985. // the input
  24986. neededEncoders.push(encoder);
  24987. canEncode = true;
  24988. break;
  24989. }
  24990. }
  24991. }
  24992. if (!canEncode) {
  24993. // The character is not encodeable by any of the single byte encoders so we remember that we will need a
  24994. // Unicode encoder.
  24995. needUnicodeEncoder = true;
  24996. }
  24997. }
  24998. if (neededEncoders.length === 1 && !needUnicodeEncoder) {
  24999. // the entire input can be encoded by the ISO-8859-1 encoder
  25000. this.encoders = [neededEncoders[0]];
  25001. }
  25002. else {
  25003. // we need more than one single byte encoder or we need a Unicode encoder.
  25004. // In this case we append a UTF-8 and UTF-16 encoder to the list
  25005. this.encoders = [];
  25006. let index = 0;
  25007. for (const encoder of neededEncoders) {
  25008. this.encoders[index++] = encoder;
  25009. }
  25010. // this.encoders[index] = new CharsetEncoder(StandardCharsets.UTF_8);
  25011. // this.encoders[index + 1] = new CharsetEncoder(StandardCharsets.UTF_16BE);
  25012. }
  25013. // Compute priorityEncoderIndex by looking up priorityCharset in encoders
  25014. let priorityEncoderIndexValue = -1;
  25015. if (priorityCharset != null) {
  25016. for (let i = 0; i < this.encoders.length; i++) {
  25017. if (this.encoders[i] != null &&
  25018. priorityCharset.name === this.encoders[i].name) {
  25019. priorityEncoderIndexValue = i;
  25020. break;
  25021. }
  25022. }
  25023. }
  25024. this.priorityEncoderIndex = priorityEncoderIndexValue;
  25025. // invariants
  25026. // if(this?.encoders?.[0].name !== StandardCharsets.ISO_8859_1)){
  25027. // throw new Error("ISO-8859-1 must be the first encoder");
  25028. // }
  25029. }
  25030. length() {
  25031. return this.encoders.length;
  25032. }
  25033. getCharsetName(index) {
  25034. if (!(index < this.length())) {
  25035. throw new Error('index must be less than length');
  25036. }
  25037. return this.encoders[index].name;
  25038. }
  25039. getCharset(index) {
  25040. if (!(index < this.length())) {
  25041. throw new Error('index must be less than length');
  25042. }
  25043. return this.encoders[index].charset;
  25044. }
  25045. getECIValue(encoderIndex) {
  25046. return this.encoders[encoderIndex].charset.getValueIdentifier();
  25047. }
  25048. /*
  25049. * returns -1 if no priority charset was defined
  25050. */
  25051. getPriorityEncoderIndex() {
  25052. return this.priorityEncoderIndex;
  25053. }
  25054. canEncode(c, encoderIndex) {
  25055. if (!(encoderIndex < this.length())) {
  25056. throw new Error('index must be less than length');
  25057. }
  25058. return true;
  25059. }
  25060. encode(c, encoderIndex) {
  25061. if (!(encoderIndex < this.length())) {
  25062. throw new Error('index must be less than length');
  25063. }
  25064. return StringEncoding.encode(StringUtils.getCharAt(c), this.encoders[encoderIndex].name);
  25065. }
  25066. }
  25067. const COST_PER_ECI = 3; // approximated (latch + 2 codewords)
  25068. class MinimalECIInput {
  25069. /**
  25070. * Constructs a minimal input
  25071. *
  25072. * @param stringToEncode the character string to encode
  25073. * @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm
  25074. * chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority
  25075. * charset to encode any character in the input that can be encoded by it if the charset is among the
  25076. * supported charsets.
  25077. * @param fnc1 denotes the character in the input that represents the FNC1 character or -1 if this is not GS1
  25078. * input.
  25079. */
  25080. constructor(stringToEncode, priorityCharset, fnc1) {
  25081. this.fnc1 = fnc1;
  25082. const encoderSet = new ECIEncoderSet(stringToEncode, priorityCharset, fnc1);
  25083. if (encoderSet.length() === 1) {
  25084. // optimization for the case when all can be encoded without ECI in ISO-8859-1
  25085. for (let i = 0; i < this.bytes.length; i++) {
  25086. const c = stringToEncode.charAt(i).charCodeAt(0);
  25087. this.bytes[i] = c === fnc1 ? 1000 : c;
  25088. }
  25089. }
  25090. else {
  25091. this.bytes = this.encodeMinimally(stringToEncode, encoderSet, fnc1);
  25092. }
  25093. }
  25094. getFNC1Character() {
  25095. return this.fnc1;
  25096. }
  25097. /**
  25098. * Returns the length of this input. The length is the number
  25099. * of {@code byte}s, FNC1 characters or ECIs in the sequence.
  25100. *
  25101. * @return the number of {@code char}s in this sequence
  25102. */
  25103. length() {
  25104. return this.bytes.length;
  25105. }
  25106. haveNCharacters(index, n) {
  25107. if (index + n - 1 >= this.bytes.length) {
  25108. return false;
  25109. }
  25110. for (let i = 0; i < n; i++) {
  25111. if (this.isECI(index + i)) {
  25112. return false;
  25113. }
  25114. }
  25115. return true;
  25116. }
  25117. /**
  25118. * Returns the {@code byte} value at the specified index. An index ranges from zero
  25119. * to {@code length() - 1}. The first {@code byte} value of the sequence is at
  25120. * index zero, the next at index one, and so on, as for array
  25121. * indexing.
  25122. *
  25123. * @param index the index of the {@code byte} value to be returned
  25124. *
  25125. * @return the specified {@code byte} value as character or the FNC1 character
  25126. *
  25127. * @throws IndexOutOfBoundsException
  25128. * if the {@code index} argument is negative or not less than
  25129. * {@code length()}
  25130. * @throws IllegalArgumentException
  25131. * if the value at the {@code index} argument is an ECI (@see #isECI)
  25132. */
  25133. charAt(index) {
  25134. if (index < 0 || index >= this.length()) {
  25135. throw new Error('' + index);
  25136. }
  25137. if (this.isECI(index)) {
  25138. throw new Error('value at ' + index + ' is not a character but an ECI');
  25139. }
  25140. return this.isFNC1(index) ? this.fnc1 : this.bytes[index];
  25141. }
  25142. /**
  25143. * Returns a {@code CharSequence} that is a subsequence of this sequence.
  25144. * The subsequence starts with the {@code char} value at the specified index and
  25145. * ends with the {@code char} value at index {@code end - 1}. The length
  25146. * (in {@code char}s) of the
  25147. * returned sequence is {@code end - start}, so if {@code start == end}
  25148. * then an empty sequence is returned.
  25149. *
  25150. * @param start the start index, inclusive
  25151. * @param end the end index, exclusive
  25152. *
  25153. * @return the specified subsequence
  25154. *
  25155. * @throws IndexOutOfBoundsException
  25156. * if {@code start} or {@code end} are negative,
  25157. * if {@code end} is greater than {@code length()},
  25158. * or if {@code start} is greater than {@code end}
  25159. * @throws IllegalArgumentException
  25160. * if a value in the range {@code start}-{@code end} is an ECI (@see #isECI)
  25161. */
  25162. subSequence(start, end) {
  25163. if (start < 0 || start > end || end > this.length()) {
  25164. throw new Error('' + start);
  25165. }
  25166. const result = new StringBuilder();
  25167. for (let i = start; i < end; i++) {
  25168. if (this.isECI(i)) {
  25169. throw new Error('value at ' + i + ' is not a character but an ECI');
  25170. }
  25171. result.append(this.charAt(i));
  25172. }
  25173. return result.toString();
  25174. }
  25175. /**
  25176. * Determines if a value is an ECI
  25177. *
  25178. * @param index the index of the value
  25179. *
  25180. * @return true if the value at position {@code index} is an ECI
  25181. *
  25182. * @throws IndexOutOfBoundsException
  25183. * if the {@code index} argument is negative or not less than
  25184. * {@code length()}
  25185. */
  25186. isECI(index) {
  25187. if (index < 0 || index >= this.length()) {
  25188. throw new Error('' + index);
  25189. }
  25190. return this.bytes[index] > 255 && this.bytes[index] <= 999;
  25191. }
  25192. /**
  25193. * Determines if a value is the FNC1 character
  25194. *
  25195. * @param index the index of the value
  25196. *
  25197. * @return true if the value at position {@code index} is the FNC1 character
  25198. *
  25199. * @throws IndexOutOfBoundsException
  25200. * if the {@code index} argument is negative or not less than
  25201. * {@code length()}
  25202. */
  25203. isFNC1(index) {
  25204. if (index < 0 || index >= this.length()) {
  25205. throw new Error('' + index);
  25206. }
  25207. return this.bytes[index] === 1000;
  25208. }
  25209. /**
  25210. * Returns the {@code int} ECI value at the specified index. An index ranges from zero
  25211. * to {@code length() - 1}. The first {@code byte} value of the sequence is at
  25212. * index zero, the next at index one, and so on, as for array
  25213. * indexing.
  25214. *
  25215. * @param index the index of the {@code int} value to be returned
  25216. *
  25217. * @return the specified {@code int} ECI value.
  25218. * The ECI specified the encoding of all bytes with a higher index until the
  25219. * next ECI or until the end of the input if no other ECI follows.
  25220. *
  25221. * @throws IndexOutOfBoundsException
  25222. * if the {@code index} argument is negative or not less than
  25223. * {@code length()}
  25224. * @throws IllegalArgumentException
  25225. * if the value at the {@code index} argument is not an ECI (@see #isECI)
  25226. */
  25227. getECIValue(index) {
  25228. if (index < 0 || index >= this.length()) {
  25229. throw new Error('' + index);
  25230. }
  25231. if (!this.isECI(index)) {
  25232. throw new Error('value at ' + index + ' is not an ECI but a character');
  25233. }
  25234. return this.bytes[index] - 256;
  25235. }
  25236. addEdge(edges, to, edge) {
  25237. if (edges[to][edge.encoderIndex] == null ||
  25238. edges[to][edge.encoderIndex].cachedTotalSize > edge.cachedTotalSize) {
  25239. edges[to][edge.encoderIndex] = edge;
  25240. }
  25241. }
  25242. addEdges(stringToEncode, encoderSet, edges, from, previous, fnc1) {
  25243. const ch = stringToEncode.charAt(from).charCodeAt(0);
  25244. let start = 0;
  25245. let end = encoderSet.length();
  25246. if (encoderSet.getPriorityEncoderIndex() >= 0 &&
  25247. (ch === fnc1 ||
  25248. encoderSet.canEncode(ch, encoderSet.getPriorityEncoderIndex()))) {
  25249. start = encoderSet.getPriorityEncoderIndex();
  25250. end = start + 1;
  25251. }
  25252. for (let i = start; i < end; i++) {
  25253. if (ch === fnc1 || encoderSet.canEncode(ch, i)) {
  25254. this.addEdge(edges, from + 1, new InputEdge(ch, encoderSet, i, previous, fnc1));
  25255. }
  25256. }
  25257. }
  25258. encodeMinimally(stringToEncode, encoderSet, fnc1) {
  25259. const inputLength = stringToEncode.length;
  25260. // Array that represents vertices. There is a vertex for every character and encoding.
  25261. const edges = new InputEdge[inputLength + 1][encoderSet.length()]();
  25262. this.addEdges(stringToEncode, encoderSet, edges, 0, null, fnc1);
  25263. for (let i = 1; i <= inputLength; i++) {
  25264. for (let j = 0; j < encoderSet.length(); j++) {
  25265. if (edges[i][j] != null && i < inputLength) {
  25266. this.addEdges(stringToEncode, encoderSet, edges, i, edges[i][j], fnc1);
  25267. }
  25268. }
  25269. // optimize memory by removing edges that have been passed.
  25270. for (let j = 0; j < encoderSet.length(); j++) {
  25271. edges[i - 1][j] = null;
  25272. }
  25273. }
  25274. let minimalJ = -1;
  25275. let minimalSize = Integer.MAX_VALUE;
  25276. for (let j = 0; j < encoderSet.length(); j++) {
  25277. if (edges[inputLength][j] != null) {
  25278. const edge = edges[inputLength][j];
  25279. if (edge.cachedTotalSize < minimalSize) {
  25280. minimalSize = edge.cachedTotalSize;
  25281. minimalJ = j;
  25282. }
  25283. }
  25284. }
  25285. if (minimalJ < 0) {
  25286. throw new Error('Failed to encode "' + stringToEncode + '"');
  25287. }
  25288. const intsAL = [];
  25289. let current = edges[inputLength][minimalJ];
  25290. while (current != null) {
  25291. if (current.isFNC1()) {
  25292. intsAL.unshift(1000);
  25293. }
  25294. else {
  25295. const bytes = encoderSet.encode(current.c, current.encoderIndex);
  25296. for (let i = bytes.length - 1; i >= 0; i--) {
  25297. intsAL.unshift(bytes[i] & 0xff);
  25298. }
  25299. }
  25300. const previousEncoderIndex = current.previous === null ? 0 : current.previous.encoderIndex;
  25301. if (previousEncoderIndex !== current.encoderIndex) {
  25302. intsAL.unshift(256 + encoderSet.getECIValue(current.encoderIndex));
  25303. }
  25304. current = current.previous;
  25305. }
  25306. const ints = [];
  25307. for (let i = 0; i < ints.length; i++) {
  25308. ints[i] = intsAL[i];
  25309. }
  25310. return ints;
  25311. }
  25312. }
  25313. class InputEdge {
  25314. constructor(c, encoderSet, encoderIndex, previous, fnc1) {
  25315. this.c = c;
  25316. this.encoderSet = encoderSet;
  25317. this.encoderIndex = encoderIndex;
  25318. this.previous = previous;
  25319. this.fnc1 = fnc1;
  25320. this.c = c === fnc1 ? 1000 : c;
  25321. let size = this.isFNC1() ? 1 : encoderSet.encode(c, encoderIndex).length;
  25322. const previousEncoderIndex = previous === null ? 0 : previous.encoderIndex;
  25323. if (previousEncoderIndex !== encoderIndex) {
  25324. size += COST_PER_ECI;
  25325. }
  25326. if (previous != null) {
  25327. size += previous.cachedTotalSize;
  25328. }
  25329. this.cachedTotalSize = size;
  25330. }
  25331. isFNC1() {
  25332. return this.c === 1000;
  25333. }
  25334. }
  25335. var Mode$3;
  25336. (function (Mode) {
  25337. Mode[Mode["ASCII"] = 0] = "ASCII";
  25338. Mode[Mode["C40"] = 1] = "C40";
  25339. Mode[Mode["TEXT"] = 2] = "TEXT";
  25340. Mode[Mode["X12"] = 3] = "X12";
  25341. Mode[Mode["EDF"] = 4] = "EDF";
  25342. Mode[Mode["B256"] = 5] = "B256";
  25343. })(Mode$3 || (Mode$3 = {}));
  25344. const C40_SHIFT2_CHARS = [
  25345. '!',
  25346. '"',
  25347. '#',
  25348. '$',
  25349. '%',
  25350. '&',
  25351. "'",
  25352. '(',
  25353. ')',
  25354. '*',
  25355. '+',
  25356. ',',
  25357. '-',
  25358. '.',
  25359. '/',
  25360. ':',
  25361. ';',
  25362. '<',
  25363. '=',
  25364. '>',
  25365. '?',
  25366. '@',
  25367. '[',
  25368. '\\',
  25369. ']',
  25370. '^',
  25371. '_',
  25372. ];
  25373. class MinimalEncoder {
  25374. static isExtendedASCII(ch, fnc1) {
  25375. return ch !== fnc1 && ch >= 128 && ch <= 255;
  25376. }
  25377. static isInC40Shift1Set(ch) {
  25378. return ch <= 31;
  25379. }
  25380. static isInC40Shift2Set(ch, fnc1) {
  25381. for (const c40Shift2Char of C40_SHIFT2_CHARS) {
  25382. if (c40Shift2Char.charCodeAt(0) === ch) {
  25383. return true;
  25384. }
  25385. }
  25386. return ch === fnc1;
  25387. }
  25388. static isInTextShift1Set(ch) {
  25389. return this.isInC40Shift1Set(ch);
  25390. }
  25391. static isInTextShift2Set(ch, fnc1) {
  25392. return this.isInC40Shift2Set(ch, fnc1);
  25393. }
  25394. /**
  25395. * Performs message encoding of a DataMatrix message
  25396. *
  25397. * @param msg the message
  25398. * @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm
  25399. * chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority
  25400. * charset to encode any character in the input that can be encoded by it if the charset is among the
  25401. * supported charsets.
  25402. * @param fnc1 denotes the character in the input that represents the FNC1 character or -1 if this is not a GS1
  25403. * bar code. If the value is not -1 then a FNC1 is also prepended.
  25404. * @param shape requested shape.
  25405. * @return the encoded message (the char values range from 0 to 255)
  25406. */
  25407. static encodeHighLevel(msg, priorityCharset = null, fnc1 = -1, shape = 0 /* FORCE_NONE */) {
  25408. let macroId = 0;
  25409. if (msg.startsWith(MACRO_05_HEADER) && msg.endsWith(MACRO_TRAILER)) {
  25410. macroId = 5;
  25411. msg = msg.substring(MACRO_05_HEADER.length, msg.length - 2);
  25412. }
  25413. else if (msg.startsWith(MACRO_06_HEADER) && msg.endsWith(MACRO_TRAILER)) {
  25414. macroId = 6;
  25415. msg = msg.substring(MACRO_06_HEADER.length, msg.length - 2);
  25416. }
  25417. return decodeURIComponent(escape(String.fromCharCode(...this.encode(msg, priorityCharset, fnc1, shape, macroId))));
  25418. }
  25419. /**
  25420. * Encodes input minimally and returns an array of the codewords
  25421. *
  25422. * @param input The string to encode
  25423. * @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm
  25424. * chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority
  25425. * charset to encode any character in the input that can be encoded by it if the charset is among the
  25426. * supported charsets.
  25427. * @param fnc1 denotes the character in the input that represents the FNC1 character or -1 if this is not a GS1
  25428. * bar code. If the value is not -1 then a FNC1 is also prepended.
  25429. * @param shape requested shape.
  25430. * @param macroId Prepends the specified macro function in case that a value of 5 or 6 is specified.
  25431. * @return An array of bytes representing the codewords of a minimal encoding.
  25432. */
  25433. static encode(input, priorityCharset, fnc1, shape, macroId) {
  25434. return this.encodeMinimally(new Input(input, priorityCharset, fnc1, shape, macroId)).getBytes();
  25435. }
  25436. static addEdge(edges, edge) {
  25437. const vertexIndex = edge.fromPosition + edge.characterLength;
  25438. if (edges[vertexIndex][edge.getEndMode()] === null ||
  25439. edges[vertexIndex][edge.getEndMode()].cachedTotalSize >
  25440. edge.cachedTotalSize) {
  25441. edges[vertexIndex][edge.getEndMode()] = edge;
  25442. }
  25443. }
  25444. /** @return the number of words in which the string starting at from can be encoded in c40 or text mode.
  25445. * The number of characters encoded is returned in characterLength.
  25446. * The number of characters encoded is also minimal in the sense that the algorithm stops as soon
  25447. * as a character encoding fills a C40 word competely (three C40 values). An exception is at the
  25448. * end of the string where two C40 values are allowed (according to the spec the third c40 value
  25449. * is filled with 0 (Shift 1) in this case).
  25450. */
  25451. static getNumberOfC40Words(input, from, c40, characterLength) {
  25452. let thirdsCount = 0;
  25453. for (let i = from; i < input.length(); i++) {
  25454. if (input.isECI(i)) {
  25455. characterLength[0] = 0;
  25456. return 0;
  25457. }
  25458. const ci = input.charAt(i);
  25459. if ((c40 && HighLevelEncoder.isNativeC40(ci)) ||
  25460. (!c40 && HighLevelEncoder.isNativeText(ci))) {
  25461. thirdsCount++; // native
  25462. }
  25463. else if (!MinimalEncoder.isExtendedASCII(ci, input.getFNC1Character())) {
  25464. thirdsCount += 2; // shift
  25465. }
  25466. else {
  25467. const asciiValue = ci & 0xff;
  25468. if (asciiValue >= 128 &&
  25469. ((c40 && HighLevelEncoder.isNativeC40(asciiValue - 128)) ||
  25470. (!c40 && HighLevelEncoder.isNativeText(asciiValue - 128)))) {
  25471. thirdsCount += 3; // shift, Upper shift
  25472. }
  25473. else {
  25474. thirdsCount += 4; // shift, Upper shift, shift
  25475. }
  25476. }
  25477. if (thirdsCount % 3 === 0 ||
  25478. ((thirdsCount - 2) % 3 === 0 && i + 1 === input.length())) {
  25479. characterLength[0] = i - from + 1;
  25480. return Math.ceil(thirdsCount / 3.0);
  25481. }
  25482. }
  25483. characterLength[0] = 0;
  25484. return 0;
  25485. }
  25486. static addEdges(input, edges, from, previous) {
  25487. if (input.isECI(from)) {
  25488. this.addEdge(edges, new Edge(input, Mode$3.ASCII, from, 1, previous));
  25489. return;
  25490. }
  25491. const ch = input.charAt(from);
  25492. if (previous === null || previous.getEndMode() !== Mode$3.EDF) {
  25493. // not possible to unlatch a full EDF edge to something
  25494. // else
  25495. if (HighLevelEncoder.isDigit(ch) &&
  25496. input.haveNCharacters(from, 2) &&
  25497. HighLevelEncoder.isDigit(input.charAt(from + 1))) {
  25498. // two digits ASCII encoded
  25499. this.addEdge(edges, new Edge(input, Mode$3.ASCII, from, 2, previous));
  25500. }
  25501. else {
  25502. // one ASCII encoded character or an extended character via Upper Shift
  25503. this.addEdge(edges, new Edge(input, Mode$3.ASCII, from, 1, previous));
  25504. }
  25505. const modes = [Mode$3.C40, Mode$3.TEXT];
  25506. for (const mode of modes) {
  25507. const characterLength = [];
  25508. if (MinimalEncoder.getNumberOfC40Words(input, from, mode === Mode$3.C40, characterLength) > 0) {
  25509. this.addEdge(edges, new Edge(input, mode, from, characterLength[0], previous));
  25510. }
  25511. }
  25512. if (input.haveNCharacters(from, 3) &&
  25513. HighLevelEncoder.isNativeX12(input.charAt(from)) &&
  25514. HighLevelEncoder.isNativeX12(input.charAt(from + 1)) &&
  25515. HighLevelEncoder.isNativeX12(input.charAt(from + 2))) {
  25516. this.addEdge(edges, new Edge(input, Mode$3.X12, from, 3, previous));
  25517. }
  25518. this.addEdge(edges, new Edge(input, Mode$3.B256, from, 1, previous));
  25519. }
  25520. // We create 4 EDF edges, with 1, 2 3 or 4 characters length. The fourth normally doesn't have a latch to ASCII
  25521. // unless it is 2 characters away from the end of the input.
  25522. let i;
  25523. for (i = 0; i < 3; i++) {
  25524. const pos = from + i;
  25525. if (input.haveNCharacters(pos, 1) &&
  25526. HighLevelEncoder.isNativeEDIFACT(input.charAt(pos))) {
  25527. this.addEdge(edges, new Edge(input, Mode$3.EDF, from, i + 1, previous));
  25528. }
  25529. else {
  25530. break;
  25531. }
  25532. }
  25533. if (i === 3 &&
  25534. input.haveNCharacters(from, 4) &&
  25535. HighLevelEncoder.isNativeEDIFACT(input.charAt(from + 3))) {
  25536. this.addEdge(edges, new Edge(input, Mode$3.EDF, from, 4, previous));
  25537. }
  25538. }
  25539. static encodeMinimally(input) {
  25540. /* The minimal encoding is computed by Dijkstra. The acyclic graph is modeled as follows:
  25541. * A vertex represents a combination of a position in the input and an encoding mode where position 0
  25542. * denotes the position left of the first character, 1 the position left of the second character and so on.
  25543. * Likewise the end vertices are located after the last character at position input.length().
  25544. * For any position there might be up to six vertices, one for each of the encoding types ASCII, C40, TEXT, X12,
  25545. * EDF and B256.
  25546. *
  25547. * As an example consider the input string "ABC123" then at position 0 there is only one vertex with the default
  25548. * ASCII encodation. At position 3 there might be vertices for the types ASCII, C40, X12, EDF and B256.
  25549. *
  25550. * An edge leading to such a vertex encodes one or more of the characters left of the position that the vertex
  25551. * represents. It encodes the characters in the encoding mode of the vertex that it ends on. In other words,
  25552. * all edges leading to a particular vertex encode the same characters (the length of the suffix can vary) using the same
  25553. * encoding mode.
  25554. * As an example consider the input string "ABC123" and the vertex (4,EDF). Possible edges leading to this vertex
  25555. * are:
  25556. * (0,ASCII) --EDF(ABC1)--> (4,EDF)
  25557. * (1,ASCII) --EDF(BC1)--> (4,EDF)
  25558. * (1,B256) --EDF(BC1)--> (4,EDF)
  25559. * (1,EDF) --EDF(BC1)--> (4,EDF)
  25560. * (2,ASCII) --EDF(C1)--> (4,EDF)
  25561. * (2,B256) --EDF(C1)--> (4,EDF)
  25562. * (2,EDF) --EDF(C1)--> (4,EDF)
  25563. * (3,ASCII) --EDF(1)--> (4,EDF)
  25564. * (3,B256) --EDF(1)--> (4,EDF)
  25565. * (3,EDF) --EDF(1)--> (4,EDF)
  25566. * (3,C40) --EDF(1)--> (4,EDF)
  25567. * (3,X12) --EDF(1)--> (4,EDF)
  25568. *
  25569. * The edges leading to a vertex are stored in such a way that there is a fast way to enumerate the edges ending
  25570. * on a particular vertex.
  25571. *
  25572. * The algorithm processes the vertices in order of their position thereby performing the following:
  25573. *
  25574. * For every vertex at position i the algorithm enumerates the edges ending on the vertex and removes all but the
  25575. * shortest from that list.
  25576. * Then it processes the vertices for the position i+1. If i+1 == input.length() then the algorithm ends
  25577. * and chooses the the edge with the smallest size from any of the edges leading to vertices at this position.
  25578. * Otherwise the algorithm computes all possible outgoing edges for the vertices at the position i+1
  25579. *
  25580. * Examples:
  25581. * The process is illustrated by showing the graph (edges) after each iteration from left to right over the input:
  25582. * An edge is drawn as follows "(" + fromVertex + ") -- " + encodingMode + "(" + encodedInput + ") (" +
  25583. * accumulatedSize + ") --> (" + toVertex + ")"
  25584. *
  25585. * Example 1 encoding the string "ABCDEFG":
  25586. *
  25587. *
  25588. * Situation after adding edges to the start vertex (0,ASCII)
  25589. * (0,ASCII) ASCII(A) (1) --> (1,ASCII)
  25590. * (0,ASCII) B256(A) (3) --> (1,B256)
  25591. * (0,ASCII) EDF(AB) (4) --> (2,EDF)
  25592. * (0,ASCII) C40(ABC) (3) --> (3,C40)
  25593. * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)
  25594. * (0,ASCII) X12(ABC) (3) --> (3,X12)
  25595. * (0,ASCII) EDF(ABC) (4) --> (3,EDF)
  25596. * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)
  25597. *
  25598. * Situation after adding edges to vertices at position 1
  25599. * (0,ASCII) ASCII(A) (1) --> (1,ASCII)
  25600. * (0,ASCII) B256(A) (3) --> (1,B256)
  25601. * (0,ASCII) EDF(AB) (4) --> (2,EDF)
  25602. * (0,ASCII) C40(ABC) (3) --> (3,C40)
  25603. * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)
  25604. * (0,ASCII) X12(ABC) (3) --> (3,X12)
  25605. * (0,ASCII) EDF(ABC) (4) --> (3,EDF)
  25606. * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)
  25607. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII)
  25608. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) B256(B) (4) --> (2,B256)
  25609. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BC) (5) --> (3,EDF)
  25610. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40)
  25611. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) TEXT(BCD) (6) --> (4,TEXT)
  25612. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12)
  25613. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCD) (5) --> (4,EDF)
  25614. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCDE) (5) --> (5,EDF)
  25615. * (0,ASCII) B256(A) (3) --> (1,B256) ASCII(B) (4) --> (2,ASCII)
  25616. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256)
  25617. * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BC) (6) --> (3,EDF)
  25618. * (0,ASCII) B256(A) (3) --> (1,B256) C40(BCD) (5) --> (4,C40)
  25619. * (0,ASCII) B256(A) (3) --> (1,B256) TEXT(BCD) (7) --> (4,TEXT)
  25620. * (0,ASCII) B256(A) (3) --> (1,B256) X12(BCD) (5) --> (4,X12)
  25621. * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCD) (6) --> (4,EDF)
  25622. * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCDE) (6) --> (5,EDF)
  25623. *
  25624. * Edge "(1,ASCII) ASCII(B) (2) --> (2,ASCII)" is minimal for the vertex (2,ASCII) so that edge "(1,B256) ASCII(B) (4) --> (2,ASCII)" is removed.
  25625. * Edge "(1,B256) B256(B) (3) --> (2,B256)" is minimal for the vertext (2,B256) so that the edge "(1,ASCII) B256(B) (4) --> (2,B256)" is removed.
  25626. *
  25627. * Situation after adding edges to vertices at position 2
  25628. * (0,ASCII) ASCII(A) (1) --> (1,ASCII)
  25629. * (0,ASCII) B256(A) (3) --> (1,B256)
  25630. * (0,ASCII) EDF(AB) (4) --> (2,EDF)
  25631. * (0,ASCII) C40(ABC) (3) --> (3,C40)
  25632. * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)
  25633. * (0,ASCII) X12(ABC) (3) --> (3,X12)
  25634. * (0,ASCII) EDF(ABC) (4) --> (3,EDF)
  25635. * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)
  25636. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII)
  25637. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BC) (5) --> (3,EDF)
  25638. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40)
  25639. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) TEXT(BCD) (6) --> (4,TEXT)
  25640. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12)
  25641. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCD) (5) --> (4,EDF)
  25642. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCDE) (5) --> (5,EDF)
  25643. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256)
  25644. * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BC) (6) --> (3,EDF)
  25645. * (0,ASCII) B256(A) (3) --> (1,B256) C40(BCD) (5) --> (4,C40)
  25646. * (0,ASCII) B256(A) (3) --> (1,B256) TEXT(BCD) (7) --> (4,TEXT)
  25647. * (0,ASCII) B256(A) (3) --> (1,B256) X12(BCD) (5) --> (4,X12)
  25648. * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCD) (6) --> (4,EDF)
  25649. * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCDE) (6) --> (5,EDF)
  25650. * (0,ASCII) EDF(AB) (4) --> (2,EDF) ASCII(C) (5) --> (3,ASCII)
  25651. * (0,ASCII) EDF(AB) (4) --> (2,EDF) B256(C) (6) --> (3,B256)
  25652. * (0,ASCII) EDF(AB) (4) --> (2,EDF) EDF(CD) (7) --> (4,EDF)
  25653. * (0,ASCII) EDF(AB) (4) --> (2,EDF) C40(CDE) (6) --> (5,C40)
  25654. * (0,ASCII) EDF(AB) (4) --> (2,EDF) TEXT(CDE) (8) --> (5,TEXT)
  25655. * (0,ASCII) EDF(AB) (4) --> (2,EDF) X12(CDE) (6) --> (5,X12)
  25656. * (0,ASCII) EDF(AB) (4) --> (2,EDF) EDF(CDE) (7) --> (5,EDF)
  25657. * (0,ASCII) EDF(AB) (4) --> (2,EDF) EDF(CDEF) (7) --> (6,EDF)
  25658. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII)
  25659. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) B256(C) (5) --> (3,B256)
  25660. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CD) (6) --> (4,EDF)
  25661. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) C40(CDE) (5) --> (5,C40)
  25662. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) TEXT(CDE) (7) --> (5,TEXT)
  25663. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) X12(CDE) (5) --> (5,X12)
  25664. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CDE) (6) --> (5,EDF)
  25665. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CDEF) (6) --> (6,EDF)
  25666. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) ASCII(C) (4) --> (3,ASCII)
  25667. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256)
  25668. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) EDF(CD) (6) --> (4,EDF)
  25669. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) C40(CDE) (5) --> (5,C40)
  25670. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) TEXT(CDE) (7) --> (5,TEXT)
  25671. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) X12(CDE) (5) --> (5,X12)
  25672. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) EDF(CDE) (6) --> (5,EDF)
  25673. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) EDF(CDEF) (6) --> (6,EDF)
  25674. *
  25675. * Edge "(2,ASCII) ASCII(C) (3) --> (3,ASCII)" is minimal for the vertex (3,ASCII) so that edges "(2,EDF) ASCII(C) (5) --> (3,ASCII)"
  25676. * and "(2,B256) ASCII(C) (4) --> (3,ASCII)" can be removed.
  25677. * Edge "(0,ASCII) EDF(ABC) (4) --> (3,EDF)" is minimal for the vertex (3,EDF) so that edges "(1,ASCII) EDF(BC) (5) --> (3,EDF)"
  25678. * and "(1,B256) EDF(BC) (6) --> (3,EDF)" can be removed.
  25679. * Edge "(2,B256) B256(C) (4) --> (3,B256)" is minimal for the vertex (3,B256) so that edges "(2,ASCII) B256(C) (5) --> (3,B256)"
  25680. * and "(2,EDF) B256(C) (6) --> (3,B256)" can be removed.
  25681. *
  25682. * This continues for vertices 3 thru 7
  25683. *
  25684. * Situation after adding edges to vertices at position 7
  25685. * (0,ASCII) ASCII(A) (1) --> (1,ASCII)
  25686. * (0,ASCII) B256(A) (3) --> (1,B256)
  25687. * (0,ASCII) EDF(AB) (4) --> (2,EDF)
  25688. * (0,ASCII) C40(ABC) (3) --> (3,C40)
  25689. * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)
  25690. * (0,ASCII) X12(ABC) (3) --> (3,X12)
  25691. * (0,ASCII) EDF(ABC) (4) --> (3,EDF)
  25692. * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)
  25693. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII)
  25694. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40)
  25695. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) TEXT(BCD) (6) --> (4,TEXT)
  25696. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12)
  25697. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCDE) (5) --> (5,EDF)
  25698. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256)
  25699. * (0,ASCII) C40(ABC) (3) --> (3,C40) C40(DEF) (5) --> (6,C40)
  25700. * (0,ASCII) X12(ABC) (3) --> (3,X12) X12(DEF) (5) --> (6,X12)
  25701. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII)
  25702. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) C40(CDE) (5) --> (5,C40)
  25703. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) TEXT(CDE) (7) --> (5,TEXT)
  25704. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) X12(CDE) (5) --> (5,X12)
  25705. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CDEF) (6) --> (6,EDF)
  25706. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40) C40(EFG) (6) --> (7,C40) //Solution 1
  25707. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12) X12(EFG) (6) --> (7,X12) //Solution 2
  25708. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256)
  25709. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII)
  25710. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) TEXT(DEF) (8) --> (6,TEXT)
  25711. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) EDF(DEFG) (7) --> (7,EDF)
  25712. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256)
  25713. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) ASCII(E) (5) --> (5,ASCII)
  25714. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) TEXT(EFG) (9) --> (7,TEXT)
  25715. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256) B256(E) (6) --> (5,B256)
  25716. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) ASCII(E) (5) --> (5,ASCII) ASCII(F) (6) --> (6,ASCII)
  25717. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256) B256(E) (6) --> (5,B256) B256(F) (7) --> (6,B256)
  25718. * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) ASCII(E) (5) --> (5,ASCII) ASCII(F) (6) --> (6,ASCII) ASCII(G) (7) --> (7,ASCII)
  25719. * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256) B256(E) (6) --> (5,B256) B256(F) (7) --> (6,B256) B256(G) (8) --> (7,B256)
  25720. *
  25721. * Hence a minimal encoding of "ABCDEFG" is either ASCII(A),C40(BCDEFG) or ASCII(A), X12(BCDEFG) with a size of 5 bytes.
  25722. */
  25723. const inputLength = input.length();
  25724. // Array that represents vertices. There is a vertex for every character and mode.
  25725. // The last dimension in the array below encodes the 6 modes ASCII, C40, TEXT, X12, EDF and B256
  25726. const edges = Array(inputLength + 1)
  25727. .fill(null)
  25728. .map(() => Array(6).fill(0));
  25729. this.addEdges(input, edges, 0, null);
  25730. for (let i = 1; i <= inputLength; i++) {
  25731. for (let j = 0; j < 6; j++) {
  25732. if (edges[i][j] !== null && i < inputLength) {
  25733. this.addEdges(input, edges, i, edges[i][j]);
  25734. }
  25735. }
  25736. // optimize memory by removing edges that have been passed.
  25737. for (let j = 0; j < 6; j++) {
  25738. edges[i - 1][j] = null;
  25739. }
  25740. }
  25741. let minimalJ = -1;
  25742. let minimalSize = Integer.MAX_VALUE;
  25743. for (let j = 0; j < 6; j++) {
  25744. if (edges[inputLength][j] !== null) {
  25745. const edge = edges[inputLength][j];
  25746. const size = j >= 1 && j <= 3 ? edge.cachedTotalSize + 1 : edge.cachedTotalSize; // C40, TEXT and X12 need an
  25747. // extra unlatch at the end
  25748. if (size < minimalSize) {
  25749. minimalSize = size;
  25750. minimalJ = j;
  25751. }
  25752. }
  25753. }
  25754. if (minimalJ < 0) {
  25755. throw new Error('Failed to encode "' + input + '"');
  25756. }
  25757. return new Result$1(edges[inputLength][minimalJ]);
  25758. }
  25759. }
  25760. class Result$1 {
  25761. constructor(solution) {
  25762. const input = solution.input;
  25763. let size = 0;
  25764. let bytesAL = [];
  25765. const randomizePostfixLength = [];
  25766. const randomizeLengths = [];
  25767. if ((solution.mode === Mode$3.C40 ||
  25768. solution.mode === Mode$3.TEXT ||
  25769. solution.mode === Mode$3.X12) &&
  25770. solution.getEndMode() !== Mode$3.ASCII) {
  25771. size += this.prepend(Edge.getBytes(254), bytesAL);
  25772. }
  25773. let current = solution;
  25774. while (current !== null) {
  25775. size += this.prepend(current.getDataBytes(), bytesAL);
  25776. if (current.previous === null ||
  25777. current.getPreviousStartMode() !== current.getMode()) {
  25778. if (current.getMode() === Mode$3.B256) {
  25779. if (size <= 249) {
  25780. bytesAL.unshift(size);
  25781. size++;
  25782. }
  25783. else {
  25784. bytesAL.unshift(size % 250);
  25785. bytesAL.unshift(size / 250 + 249);
  25786. size += 2;
  25787. }
  25788. randomizePostfixLength.push(bytesAL.length);
  25789. randomizeLengths.push(size);
  25790. }
  25791. this.prepend(current.getLatchBytes(), bytesAL);
  25792. size = 0;
  25793. }
  25794. current = current.previous;
  25795. }
  25796. if (input.getMacroId() === 5) {
  25797. size += this.prepend(Edge.getBytes(236), bytesAL);
  25798. }
  25799. else if (input.getMacroId() === 6) {
  25800. size += this.prepend(Edge.getBytes(237), bytesAL);
  25801. }
  25802. if (input.getFNC1Character() > 0) {
  25803. size += this.prepend(Edge.getBytes(232), bytesAL);
  25804. }
  25805. for (let i = 0; i < randomizePostfixLength.length; i++) {
  25806. this.applyRandomPattern(bytesAL, bytesAL.length - randomizePostfixLength[i], randomizeLengths[i]);
  25807. }
  25808. // add padding
  25809. const capacity = solution.getMinSymbolSize(bytesAL.length);
  25810. if (bytesAL.length < capacity) {
  25811. bytesAL.push(129);
  25812. }
  25813. while (bytesAL.length < capacity) {
  25814. bytesAL.push(this.randomize253State(bytesAL.length + 1));
  25815. }
  25816. this.bytes = new Uint8Array(bytesAL.length);
  25817. for (let i = 0; i < this.bytes.length; i++) {
  25818. this.bytes[i] = bytesAL[i];
  25819. }
  25820. }
  25821. prepend(bytes, into) {
  25822. for (let i = bytes.length - 1; i >= 0; i--) {
  25823. into.unshift(bytes[i]);
  25824. }
  25825. return bytes.length;
  25826. }
  25827. randomize253State(codewordPosition) {
  25828. const pseudoRandom = ((149 * codewordPosition) % 253) + 1;
  25829. const tempVariable = 129 + pseudoRandom;
  25830. return tempVariable <= 254 ? tempVariable : tempVariable - 254;
  25831. }
  25832. applyRandomPattern(bytesAL, startPosition, length) {
  25833. for (let i = 0; i < length; i++) {
  25834. // See "B.1 253-state algorithm
  25835. const Pad_codeword_position = startPosition + i;
  25836. const Pad_codeword_value = bytesAL[Pad_codeword_position] & 0xff;
  25837. const pseudo_random_number = ((149 * (Pad_codeword_position + 1)) % 255) + 1;
  25838. const temp_variable = Pad_codeword_value + pseudo_random_number;
  25839. bytesAL[Pad_codeword_position] =
  25840. temp_variable <= 255 ? temp_variable : temp_variable - 256;
  25841. }
  25842. }
  25843. getBytes() {
  25844. return this.bytes;
  25845. }
  25846. }
  25847. class Edge {
  25848. constructor(input, mode, fromPosition, characterLength, previous) {
  25849. this.input = input;
  25850. this.mode = mode;
  25851. this.fromPosition = fromPosition;
  25852. this.characterLength = characterLength;
  25853. this.previous = previous;
  25854. this.allCodewordCapacities = [
  25855. 3, 5, 8, 10, 12, 16, 18, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144, 174, 204,
  25856. 280, 368, 456, 576, 696, 816, 1050, 1304, 1558,
  25857. ];
  25858. this.squareCodewordCapacities = [
  25859. 3, 5, 8, 12, 18, 22, 30, 36, 44, 62, 86, 114, 144, 174, 204, 280, 368, 456,
  25860. 576, 696, 816, 1050, 1304, 1558,
  25861. ];
  25862. this.rectangularCodewordCapacities = [5, 10, 16, 33, 32, 49];
  25863. if (!(fromPosition + characterLength <= input.length())) {
  25864. throw new Error('Invalid edge');
  25865. }
  25866. let size = previous !== null ? previous.cachedTotalSize : 0;
  25867. const previousMode = this.getPreviousMode();
  25868. /*
  25869. * Switching modes
  25870. * ASCII -> C40: latch 230
  25871. * ASCII -> TEXT: latch 239
  25872. * ASCII -> X12: latch 238
  25873. * ASCII -> EDF: latch 240
  25874. * ASCII -> B256: latch 231
  25875. * C40 -> ASCII: word(c1,c2,c3), 254
  25876. * TEXT -> ASCII: word(c1,c2,c3), 254
  25877. * X12 -> ASCII: word(c1,c2,c3), 254
  25878. * EDIFACT -> ASCII: Unlatch character,0,0,0 or c1,Unlatch character,0,0 or c1,c2,Unlatch character,0 or
  25879. * c1,c2,c3,Unlatch character
  25880. * B256 -> ASCII: without latch after n bytes
  25881. */
  25882. switch (mode) {
  25883. case Mode$3.ASCII:
  25884. size++;
  25885. if (input.isECI(fromPosition) ||
  25886. MinimalEncoder.isExtendedASCII(input.charAt(fromPosition), input.getFNC1Character())) {
  25887. size++;
  25888. }
  25889. if (previousMode === Mode$3.C40 ||
  25890. previousMode === Mode$3.TEXT ||
  25891. previousMode === Mode$3.X12) {
  25892. size++; // unlatch 254 to ASCII
  25893. }
  25894. break;
  25895. case Mode$3.B256:
  25896. size++;
  25897. if (previousMode !== Mode$3.B256) {
  25898. size++; // byte count
  25899. }
  25900. else if (this.getB256Size() === 250) {
  25901. size++; // extra byte count
  25902. }
  25903. if (previousMode === Mode$3.ASCII) {
  25904. size++; // latch to B256
  25905. }
  25906. else if (previousMode === Mode$3.C40 ||
  25907. previousMode === Mode$3.TEXT ||
  25908. previousMode === Mode$3.X12) {
  25909. size += 2; // unlatch to ASCII, latch to B256
  25910. }
  25911. break;
  25912. case Mode$3.C40:
  25913. case Mode$3.TEXT:
  25914. case Mode$3.X12:
  25915. if (mode === Mode$3.X12) {
  25916. size += 2;
  25917. }
  25918. else {
  25919. let charLen = [];
  25920. size +=
  25921. MinimalEncoder.getNumberOfC40Words(input, fromPosition, mode === Mode$3.C40, charLen) * 2;
  25922. }
  25923. if (previousMode === Mode$3.ASCII || previousMode === Mode$3.B256) {
  25924. size++; // additional byte for latch from ASCII to this mode
  25925. }
  25926. else if (previousMode !== mode &&
  25927. (previousMode === Mode$3.C40 ||
  25928. previousMode === Mode$3.TEXT ||
  25929. previousMode === Mode$3.X12)) {
  25930. size += 2; // unlatch 254 to ASCII followed by latch to this mode
  25931. }
  25932. break;
  25933. case Mode$3.EDF:
  25934. size += 3;
  25935. if (previousMode === Mode$3.ASCII || previousMode === Mode$3.B256) {
  25936. size++; // additional byte for latch from ASCII to this mode
  25937. }
  25938. else if (previousMode === Mode$3.C40 ||
  25939. previousMode === Mode$3.TEXT ||
  25940. previousMode === Mode$3.X12) {
  25941. size += 2; // unlatch 254 to ASCII followed by latch to this mode
  25942. }
  25943. break;
  25944. }
  25945. this.cachedTotalSize = size;
  25946. }
  25947. // does not count beyond 250
  25948. getB256Size() {
  25949. let cnt = 0;
  25950. let current = this;
  25951. while (current !== null && current.mode === Mode$3.B256 && cnt <= 250) {
  25952. cnt++;
  25953. current = current.previous;
  25954. }
  25955. return cnt;
  25956. }
  25957. getPreviousStartMode() {
  25958. return this.previous === null ? Mode$3.ASCII : this.previous.mode;
  25959. }
  25960. getPreviousMode() {
  25961. return this.previous === null ? Mode$3.ASCII : this.previous.getEndMode();
  25962. }
  25963. /** Returns Mode.ASCII in case that:
  25964. * - Mode is EDIFACT and characterLength is less than 4 or the remaining characters can be encoded in at most 2
  25965. * ASCII bytes.
  25966. * - Mode is C40, TEXT or X12 and the remaining characters can be encoded in at most 1 ASCII byte.
  25967. * Returns mode in all other cases.
  25968. * */
  25969. getEndMode() {
  25970. if (this.mode === Mode$3.EDF) {
  25971. if (this.characterLength < 4) {
  25972. return Mode$3.ASCII;
  25973. }
  25974. const lastASCII = this.getLastASCII(); // see 5.2.8.2 EDIFACT encodation Rules
  25975. if (lastASCII > 0 &&
  25976. this.getCodewordsRemaining(this.cachedTotalSize + lastASCII) <=
  25977. 2 - lastASCII) {
  25978. return Mode$3.ASCII;
  25979. }
  25980. }
  25981. if (this.mode === Mode$3.C40 ||
  25982. this.mode === Mode$3.TEXT ||
  25983. this.mode === Mode$3.X12) {
  25984. // see 5.2.5.2 C40 encodation rules and 5.2.7.2 ANSI X12 encodation rules
  25985. if (this.fromPosition + this.characterLength >= this.input.length() &&
  25986. this.getCodewordsRemaining(this.cachedTotalSize) === 0) {
  25987. return Mode$3.ASCII;
  25988. }
  25989. const lastASCII = this.getLastASCII();
  25990. if (lastASCII === 1 &&
  25991. this.getCodewordsRemaining(this.cachedTotalSize + 1) === 0) {
  25992. return Mode$3.ASCII;
  25993. }
  25994. }
  25995. return this.mode;
  25996. }
  25997. getMode() {
  25998. return this.mode;
  25999. }
  26000. /** Peeks ahead and returns 1 if the postfix consists of exactly two digits, 2 if the postfix consists of exactly
  26001. * two consecutive digits and a non extended character or of 4 digits.
  26002. * Returns 0 in any other case
  26003. **/
  26004. getLastASCII() {
  26005. const length = this.input.length();
  26006. const from = this.fromPosition + this.characterLength;
  26007. if (length - from > 4 || from >= length) {
  26008. return 0;
  26009. }
  26010. if (length - from === 1) {
  26011. if (MinimalEncoder.isExtendedASCII(this.input.charAt(from), this.input.getFNC1Character())) {
  26012. return 0;
  26013. }
  26014. return 1;
  26015. }
  26016. if (length - from === 2) {
  26017. if (MinimalEncoder.isExtendedASCII(this.input.charAt(from), this.input.getFNC1Character()) ||
  26018. MinimalEncoder.isExtendedASCII(this.input.charAt(from + 1), this.input.getFNC1Character())) {
  26019. return 0;
  26020. }
  26021. if (HighLevelEncoder.isDigit(this.input.charAt(from)) &&
  26022. HighLevelEncoder.isDigit(this.input.charAt(from + 1))) {
  26023. return 1;
  26024. }
  26025. return 2;
  26026. }
  26027. if (length - from === 3) {
  26028. if (HighLevelEncoder.isDigit(this.input.charAt(from)) &&
  26029. HighLevelEncoder.isDigit(this.input.charAt(from + 1)) &&
  26030. !MinimalEncoder.isExtendedASCII(this.input.charAt(from + 2), this.input.getFNC1Character())) {
  26031. return 2;
  26032. }
  26033. if (HighLevelEncoder.isDigit(this.input.charAt(from + 1)) &&
  26034. HighLevelEncoder.isDigit(this.input.charAt(from + 2)) &&
  26035. !MinimalEncoder.isExtendedASCII(this.input.charAt(from), this.input.getFNC1Character())) {
  26036. return 2;
  26037. }
  26038. return 0;
  26039. }
  26040. if (HighLevelEncoder.isDigit(this.input.charAt(from)) &&
  26041. HighLevelEncoder.isDigit(this.input.charAt(from + 1)) &&
  26042. HighLevelEncoder.isDigit(this.input.charAt(from + 2)) &&
  26043. HighLevelEncoder.isDigit(this.input.charAt(from + 3))) {
  26044. return 2;
  26045. }
  26046. return 0;
  26047. }
  26048. /** Returns the capacity in codewords of the smallest symbol that has enough capacity to fit the given minimal
  26049. * number of codewords.
  26050. **/
  26051. getMinSymbolSize(minimum) {
  26052. switch (this.input.getShapeHint()) {
  26053. case 1 /* FORCE_SQUARE */:
  26054. for (const capacity of this.squareCodewordCapacities) {
  26055. if (capacity >= minimum) {
  26056. return capacity;
  26057. }
  26058. }
  26059. break;
  26060. case 2 /* FORCE_RECTANGLE */:
  26061. for (const capacity of this.rectangularCodewordCapacities) {
  26062. if (capacity >= minimum) {
  26063. return capacity;
  26064. }
  26065. }
  26066. break;
  26067. }
  26068. for (const capacity of this.allCodewordCapacities) {
  26069. if (capacity >= minimum) {
  26070. return capacity;
  26071. }
  26072. }
  26073. return this.allCodewordCapacities[this.allCodewordCapacities.length - 1];
  26074. }
  26075. /** Returns the remaining capacity in codewords of the smallest symbol that has enough capacity to fit the given
  26076. * minimal number of codewords.
  26077. **/
  26078. getCodewordsRemaining(minimum) {
  26079. return this.getMinSymbolSize(minimum) - minimum;
  26080. }
  26081. static getBytes(c1, c2) {
  26082. const result = new Uint8Array(c2 ? 2 : 1);
  26083. result[0] = c1;
  26084. if (c2) {
  26085. result[1] = c2;
  26086. }
  26087. return result;
  26088. }
  26089. setC40Word(bytes, offset, c1, c2, c3) {
  26090. const val16 = 1600 * (c1 & 0xff) + 40 * (c2 & 0xff) + (c3 & 0xff) + 1;
  26091. bytes[offset] = val16 / 256;
  26092. bytes[offset + 1] = val16 % 256;
  26093. }
  26094. getX12Value(c) {
  26095. return c === 13
  26096. ? 0
  26097. : c === 42
  26098. ? 1
  26099. : c === 62
  26100. ? 2
  26101. : c === 32
  26102. ? 3
  26103. : c >= 48 && c <= 57
  26104. ? c - 44
  26105. : c >= 65 && c <= 90
  26106. ? c - 51
  26107. : c;
  26108. }
  26109. getX12Words() {
  26110. if (!(this.characterLength % 3 === 0)) {
  26111. throw new Error('X12 words must be a multiple of 3');
  26112. }
  26113. const result = new Uint8Array((this.characterLength / 3) * 2);
  26114. for (let i = 0; i < result.length; i += 2) {
  26115. this.setC40Word(result, i, this.getX12Value(this.input.charAt(this.fromPosition + (i / 2) * 3)), this.getX12Value(this.input.charAt(this.fromPosition + (i / 2) * 3 + 1)), this.getX12Value(this.input.charAt(this.fromPosition + (i / 2) * 3 + 2)));
  26116. }
  26117. return result;
  26118. }
  26119. getShiftValue(c, c40, fnc1) {
  26120. return (c40 && MinimalEncoder.isInC40Shift1Set(c)) ||
  26121. (!c40 && MinimalEncoder.isInTextShift1Set(c))
  26122. ? 0
  26123. : (c40 && MinimalEncoder.isInC40Shift2Set(c, fnc1)) ||
  26124. (!c40 && MinimalEncoder.isInTextShift2Set(c, fnc1))
  26125. ? 1
  26126. : 2;
  26127. }
  26128. getC40Value(c40, setIndex, c, fnc1) {
  26129. if (c === fnc1) {
  26130. if (!(setIndex === 2)) {
  26131. throw new Error('FNC1 cannot be used in C40 shift 2');
  26132. }
  26133. return 27;
  26134. }
  26135. if (c40) {
  26136. return c <= 31
  26137. ? c
  26138. : c === 32
  26139. ? 3
  26140. : c <= 47
  26141. ? c - 33
  26142. : c <= 57
  26143. ? c - 44
  26144. : c <= 64
  26145. ? c - 43
  26146. : c <= 90
  26147. ? c - 51
  26148. : c <= 95
  26149. ? c - 69
  26150. : c <= 127
  26151. ? c - 96
  26152. : c;
  26153. }
  26154. else {
  26155. return c === 0
  26156. ? 0
  26157. : setIndex === 0 && c <= 3
  26158. ? c - 1 // is this a bug in the spec?
  26159. : setIndex === 1 && c <= 31
  26160. ? c
  26161. : c === 32
  26162. ? 3
  26163. : c >= 33 && c <= 47
  26164. ? c - 33
  26165. : c >= 48 && c <= 57
  26166. ? c - 44
  26167. : c >= 58 && c <= 64
  26168. ? c - 43
  26169. : c >= 65 && c <= 90
  26170. ? c - 64
  26171. : c >= 91 && c <= 95
  26172. ? c - 69
  26173. : c === 96
  26174. ? 0
  26175. : c >= 97 && c <= 122
  26176. ? c - 83
  26177. : c >= 123 && c <= 127
  26178. ? c - 96
  26179. : c;
  26180. }
  26181. }
  26182. getC40Words(c40, fnc1) {
  26183. const c40Values = [];
  26184. for (let i = 0; i < this.characterLength; i++) {
  26185. const ci = this.input.charAt(this.fromPosition + i);
  26186. if ((c40 && HighLevelEncoder.isNativeC40(ci)) ||
  26187. (!c40 && HighLevelEncoder.isNativeText(ci))) {
  26188. c40Values.push(this.getC40Value(c40, 0, ci, fnc1));
  26189. }
  26190. else if (!MinimalEncoder.isExtendedASCII(ci, fnc1)) {
  26191. const shiftValue = this.getShiftValue(ci, c40, fnc1);
  26192. c40Values.push(shiftValue); // Shift[123]
  26193. c40Values.push(this.getC40Value(c40, shiftValue, ci, fnc1));
  26194. }
  26195. else {
  26196. const asciiValue = (ci & 0xff) - 128;
  26197. if ((c40 && HighLevelEncoder.isNativeC40(asciiValue)) ||
  26198. (!c40 && HighLevelEncoder.isNativeText(asciiValue))) {
  26199. c40Values.push(1); // Shift 2
  26200. c40Values.push(30); // Upper Shift
  26201. c40Values.push(this.getC40Value(c40, 0, asciiValue, fnc1));
  26202. }
  26203. else {
  26204. c40Values.push(1); // Shift 2
  26205. c40Values.push(30); // Upper Shift
  26206. const shiftValue = this.getShiftValue(asciiValue, c40, fnc1);
  26207. c40Values.push(shiftValue); // Shift[123]
  26208. c40Values.push(this.getC40Value(c40, shiftValue, asciiValue, fnc1));
  26209. }
  26210. }
  26211. }
  26212. if (c40Values.length % 3 !== 0) {
  26213. if (!((c40Values.length - 2) % 3 === 0 &&
  26214. this.fromPosition + this.characterLength === this.input.length())) {
  26215. throw new Error('C40 words must be a multiple of 3');
  26216. }
  26217. c40Values.push(0); // pad with 0 (Shift 1)
  26218. }
  26219. const result = new Uint8Array((c40Values.length / 3) * 2);
  26220. let byteIndex = 0;
  26221. for (let i = 0; i < c40Values.length; i += 3) {
  26222. this.setC40Word(result, byteIndex, c40Values[i] & 0xff, c40Values[i + 1] & 0xff, c40Values[i + 2] & 0xff);
  26223. byteIndex += 2;
  26224. }
  26225. return result;
  26226. }
  26227. getEDFBytes() {
  26228. const numberOfThirds = Math.ceil(this.characterLength / 4.0);
  26229. const result = new Uint8Array(numberOfThirds * 3);
  26230. let pos = this.fromPosition;
  26231. const endPos = Math.min(this.fromPosition + this.characterLength - 1, this.input.length() - 1);
  26232. for (let i = 0; i < numberOfThirds; i += 3) {
  26233. const edfValues = [];
  26234. for (let j = 0; j < 4; j++) {
  26235. if (pos <= endPos) {
  26236. edfValues[j] = this.input.charAt(pos++) & 0x3f;
  26237. }
  26238. else {
  26239. edfValues[j] = pos === endPos + 1 ? 0x1f : 0;
  26240. }
  26241. }
  26242. let val24 = edfValues[0] << 18;
  26243. val24 |= edfValues[1] << 12;
  26244. val24 |= edfValues[2] << 6;
  26245. val24 |= edfValues[3];
  26246. result[i] = (val24 >> 16) & 0xff;
  26247. result[i + 1] = (val24 >> 8) & 0xff;
  26248. result[i + 2] = val24 & 0xff;
  26249. }
  26250. return result;
  26251. }
  26252. getLatchBytes() {
  26253. switch (this.getPreviousMode()) {
  26254. case Mode$3.ASCII:
  26255. case Mode$3.B256: // after B256 ends (via length) we are back to ASCII
  26256. switch (this.mode) {
  26257. case Mode$3.B256:
  26258. return Edge.getBytes(231);
  26259. case Mode$3.C40:
  26260. return Edge.getBytes(230);
  26261. case Mode$3.TEXT:
  26262. return Edge.getBytes(239);
  26263. case Mode$3.X12:
  26264. return Edge.getBytes(238);
  26265. case Mode$3.EDF:
  26266. return Edge.getBytes(240);
  26267. }
  26268. break;
  26269. case Mode$3.C40:
  26270. case Mode$3.TEXT:
  26271. case Mode$3.X12:
  26272. if (this.mode !== this.getPreviousMode()) {
  26273. switch (this.mode) {
  26274. case Mode$3.ASCII:
  26275. return Edge.getBytes(254);
  26276. case Mode$3.B256:
  26277. return Edge.getBytes(254, 231);
  26278. case Mode$3.C40:
  26279. return Edge.getBytes(254, 230);
  26280. case Mode$3.TEXT:
  26281. return Edge.getBytes(254, 239);
  26282. case Mode$3.X12:
  26283. return Edge.getBytes(254, 238);
  26284. case Mode$3.EDF:
  26285. return Edge.getBytes(254, 240);
  26286. }
  26287. }
  26288. break;
  26289. case Mode$3.EDF:
  26290. // The rightmost EDIFACT edge always contains an unlatch character
  26291. if (this.mode !== Mode$3.EDF) {
  26292. throw new Error('Cannot switch from EDF to ' + this.mode);
  26293. }
  26294. break;
  26295. }
  26296. return new Uint8Array(0);
  26297. }
  26298. // Important: The function does not return the length bytes (one or two) in case of B256 encoding
  26299. getDataBytes() {
  26300. switch (this.mode) {
  26301. case Mode$3.ASCII:
  26302. if (this.input.isECI(this.fromPosition)) {
  26303. return Edge.getBytes(241, this.input.getECIValue(this.fromPosition) + 1);
  26304. }
  26305. else if (MinimalEncoder.isExtendedASCII(this.input.charAt(this.fromPosition), this.input.getFNC1Character())) {
  26306. return Edge.getBytes(235, this.input.charAt(this.fromPosition) - 127);
  26307. }
  26308. else if (this.characterLength === 2) {
  26309. return Edge.getBytes(this.input.charAt(this.fromPosition) * 10 +
  26310. this.input.charAt(this.fromPosition + 1) +
  26311. 130);
  26312. }
  26313. else if (this.input.isFNC1(this.fromPosition)) {
  26314. return Edge.getBytes(232);
  26315. }
  26316. else {
  26317. return Edge.getBytes(this.input.charAt(this.fromPosition) + 1);
  26318. }
  26319. case Mode$3.B256:
  26320. return Edge.getBytes(this.input.charAt(this.fromPosition));
  26321. case Mode$3.C40:
  26322. return this.getC40Words(true, this.input.getFNC1Character());
  26323. case Mode$3.TEXT:
  26324. return this.getC40Words(false, this.input.getFNC1Character());
  26325. case Mode$3.X12:
  26326. return this.getX12Words();
  26327. case Mode$3.EDF:
  26328. return this.getEDFBytes();
  26329. }
  26330. }
  26331. }
  26332. class Input extends MinimalECIInput {
  26333. constructor(stringToEncode, priorityCharset, fnc1, shape, macroId) {
  26334. super(stringToEncode, priorityCharset, fnc1);
  26335. this.shape = shape;
  26336. this.macroId = macroId;
  26337. }
  26338. getMacroId() {
  26339. return this.macroId;
  26340. }
  26341. getShapeHint() {
  26342. return this.shape;
  26343. }
  26344. }
  26345. class DataMatrixWriter {
  26346. encode(contents, format, width, height, hints = null) {
  26347. if (contents.trim() === '') {
  26348. throw new Error('Found empty contents');
  26349. }
  26350. if (format !== BarcodeFormat$1.DATA_MATRIX) {
  26351. throw new Error('Can only encode DATA_MATRIX, but got ' + format);
  26352. }
  26353. if (width < 0 || height < 0) {
  26354. throw new Error('Requested dimensions can\'t be negative: ' + width + 'x' + height);
  26355. }
  26356. // Try to get force shape & min / max size
  26357. let shape = 0 /* FORCE_NONE */;
  26358. let minSize = null;
  26359. let maxSize = null;
  26360. if (hints != null) {
  26361. const requestedShape = hints.get(EncodeHintType$1.DATA_MATRIX_SHAPE);
  26362. if (requestedShape != null) {
  26363. shape = requestedShape;
  26364. }
  26365. const requestedMinSize = hints.get(EncodeHintType$1.MIN_SIZE);
  26366. if (requestedMinSize != null) {
  26367. minSize = requestedMinSize;
  26368. }
  26369. const requestedMaxSize = hints.get(EncodeHintType$1.MAX_SIZE);
  26370. if (requestedMaxSize != null) {
  26371. maxSize = requestedMaxSize;
  26372. }
  26373. }
  26374. // 1. step: Data encodation
  26375. let encoded;
  26376. const hasCompactionHint = hints != null &&
  26377. hints.has(EncodeHintType$1.DATA_MATRIX_COMPACT) &&
  26378. Boolean(hints.get(EncodeHintType$1.DATA_MATRIX_COMPACT).toString());
  26379. if (hasCompactionHint) {
  26380. const hasGS1FormatHint = hints.has(EncodeHintType$1.GS1_FORMAT) &&
  26381. Boolean(hints.get(EncodeHintType$1.GS1_FORMAT).toString());
  26382. let charset = null;
  26383. const hasEncodingHint = hints.has(EncodeHintType$1.CHARACTER_SET);
  26384. if (hasEncodingHint) {
  26385. charset = Charset.forName(hints.get(EncodeHintType$1.CHARACTER_SET).toString());
  26386. }
  26387. encoded = MinimalEncoder.encodeHighLevel(contents, charset, hasGS1FormatHint ? 0x1d : -1, shape);
  26388. }
  26389. else {
  26390. const hasForceC40Hint = hints != null &&
  26391. hints.has(EncodeHintType$1.FORCE_C40) &&
  26392. Boolean(hints.get(EncodeHintType$1.FORCE_C40).toString());
  26393. encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, hasForceC40Hint);
  26394. }
  26395. const symbolInfo = SymbolInfo.lookup(encoded.length, shape, minSize, maxSize, true);
  26396. // 2. step: ECC generation
  26397. const codewords = ErrorCorrection$1.encodeECC200(encoded, symbolInfo);
  26398. // 3. step: Module placement in Matrix
  26399. const placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight());
  26400. placement.place();
  26401. // 4. step: low-level encoding
  26402. return this.encodeLowLevel(placement, symbolInfo, width, height);
  26403. }
  26404. /**
  26405. * Encode the given symbol info to a bit matrix.
  26406. *
  26407. * @param placement The DataMatrix placement.
  26408. * @param symbolInfo The symbol info to encode.
  26409. * @return The bit matrix generated.
  26410. */
  26411. encodeLowLevel(placement, symbolInfo, width, height) {
  26412. const symbolWidth = symbolInfo.getSymbolDataWidth();
  26413. const symbolHeight = symbolInfo.getSymbolDataHeight();
  26414. const matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight());
  26415. let matrixY = 0;
  26416. for (let y = 0; y < symbolHeight; y++) {
  26417. // Fill the top edge with alternate 0 / 1
  26418. let matrixX;
  26419. if (y % symbolInfo.matrixHeight === 0) {
  26420. matrixX = 0;
  26421. for (let x = 0; x < symbolInfo.getSymbolWidth(); x++) {
  26422. matrix.setBoolean(matrixX, matrixY, x % 2 === 0);
  26423. matrixX++;
  26424. }
  26425. matrixY++;
  26426. }
  26427. matrixX = 0;
  26428. for (let x = 0; x < symbolWidth; x++) {
  26429. // Fill the right edge with full 1
  26430. if (x % symbolInfo.matrixWidth === 0) {
  26431. matrix.setBoolean(matrixX, matrixY, true);
  26432. matrixX++;
  26433. }
  26434. matrix.setBoolean(matrixX, matrixY, placement.getBit(x, y));
  26435. matrixX++;
  26436. // Fill the right edge with alternate 0 / 1
  26437. if (x % symbolInfo.matrixWidth === symbolInfo.matrixWidth - 1) {
  26438. matrix.setBoolean(matrixX, matrixY, y % 2 === 0);
  26439. matrixX++;
  26440. }
  26441. }
  26442. matrixY++;
  26443. // Fill the bottom edge with full 1
  26444. if (y % symbolInfo.matrixHeight === symbolInfo.matrixHeight - 1) {
  26445. matrixX = 0;
  26446. for (let x = 0; x < symbolInfo.getSymbolWidth(); x++) {
  26447. matrix.setBoolean(matrixX, matrixY, true);
  26448. matrixX++;
  26449. }
  26450. matrixY++;
  26451. }
  26452. }
  26453. return this.convertByteMatrixToBitMatrix(matrix, width, height);
  26454. }
  26455. /**
  26456. * Convert the ByteMatrix to BitMatrix.
  26457. *
  26458. * @param reqHeight The requested height of the image (in pixels) with the Datamatrix code
  26459. * @param reqWidth The requested width of the image (in pixels) with the Datamatrix code
  26460. * @param matrix The input matrix.
  26461. * @return The output matrix.
  26462. */
  26463. convertByteMatrixToBitMatrix(matrix, reqWidth, reqHeight) {
  26464. const matrixWidth = matrix.getWidth();
  26465. const matrixHeight = matrix.getHeight();
  26466. const outputWidth = Math.max(reqWidth, matrixWidth);
  26467. const outputHeight = Math.max(reqHeight, matrixHeight);
  26468. const multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight);
  26469. let leftPadding = (outputWidth - matrixWidth * multiple) / 2;
  26470. let topPadding = (outputHeight - matrixHeight * multiple) / 2;
  26471. let output;
  26472. // remove padding if requested width and height are too small
  26473. if (reqHeight < matrixHeight || reqWidth < matrixWidth) {
  26474. leftPadding = 0;
  26475. topPadding = 0;
  26476. output = new BitMatrix(matrixWidth, matrixHeight);
  26477. }
  26478. else {
  26479. output = new BitMatrix(reqWidth, reqHeight);
  26480. }
  26481. output.clear();
  26482. for (let inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) {
  26483. // Write the contents of this row of the bytematrix
  26484. for (let inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) {
  26485. if (matrix.get(inputX, inputY) === 1) {
  26486. output.setRegion(outputX, outputY, multiple, multiple);
  26487. }
  26488. }
  26489. }
  26490. return output;
  26491. }
  26492. }
  26493. /*
  26494. * Copyright 2013 ZXing authors
  26495. *
  26496. * Licensed under the Apache License, Version 2.0 (the "License");
  26497. * you may not use this file except in compliance with the License.
  26498. * You may obtain a copy of the License at
  26499. *
  26500. * http://www.apache.org/licenses/LICENSE-2.0
  26501. *
  26502. * Unless required by applicable law or agreed to in writing, software
  26503. * distributed under the License is distributed on an "AS IS" BASIS,
  26504. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26505. * See the License for the specific language governing permissions and
  26506. * limitations under the License.
  26507. */
  26508. /**
  26509. * Aztec 2D code representation
  26510. *
  26511. * @author Rustam Abdullaev
  26512. */
  26513. /*public final*/ class AztecCode {
  26514. /**
  26515. * @return {@code true} if compact instead of full mode
  26516. */
  26517. isCompact() {
  26518. return this.compact;
  26519. }
  26520. setCompact(compact) {
  26521. this.compact = compact;
  26522. }
  26523. /**
  26524. * @return size in pixels (width and height)
  26525. */
  26526. getSize() {
  26527. return this.size;
  26528. }
  26529. setSize(size) {
  26530. this.size = size;
  26531. }
  26532. /**
  26533. * @return number of levels
  26534. */
  26535. getLayers() {
  26536. return this.layers;
  26537. }
  26538. setLayers(layers) {
  26539. this.layers = layers;
  26540. }
  26541. /**
  26542. * @return number of data codewords
  26543. */
  26544. getCodeWords() {
  26545. return this.codeWords;
  26546. }
  26547. setCodeWords(codeWords) {
  26548. this.codeWords = codeWords;
  26549. }
  26550. /**
  26551. * @return the symbol image
  26552. */
  26553. getMatrix() {
  26554. return this.matrix;
  26555. }
  26556. setMatrix(matrix) {
  26557. this.matrix = matrix;
  26558. }
  26559. }
  26560. class Collections {
  26561. /**
  26562. * The singletonList(T) method is used to return an immutable list containing only the specified object.
  26563. */
  26564. static singletonList(item) {
  26565. return [item];
  26566. }
  26567. /**
  26568. * The min(Collection<? extends T>, Comparator<? super T>) method is used to return the minimum element of the given collection, according to the order induced by the specified comparator.
  26569. */
  26570. static min(collection, comparator) {
  26571. return collection.sort(comparator)[0];
  26572. }
  26573. }
  26574. /*
  26575. * Copyright 2013 ZXing authors
  26576. *
  26577. * Licensed under the Apache License, Version 2.0 (the "License");
  26578. * you may not use this file except in compliance with the License.
  26579. * You may obtain a copy of the License at
  26580. *
  26581. * http://www.apache.org/licenses/LICENSE-2.0
  26582. *
  26583. * Unless required by applicable law or agreed to in writing, software
  26584. * distributed under the License is distributed on an "AS IS" BASIS,
  26585. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26586. * See the License for the specific language governing permissions and
  26587. * limitations under the License.
  26588. */
  26589. class Token {
  26590. constructor(previous) {
  26591. this.previous = previous;
  26592. }
  26593. getPrevious() {
  26594. return this.previous;
  26595. }
  26596. }
  26597. /*
  26598. * Copyright 2013 ZXing authors
  26599. *
  26600. * Licensed under the Apache License, Version 2.0 (the "License");
  26601. * you may not use this file except in compliance with the License.
  26602. * You may obtain a copy of the License at
  26603. *
  26604. * http://www.apache.org/licenses/LICENSE-2.0
  26605. *
  26606. * Unless required by applicable law or agreed to in writing, software
  26607. * distributed under the License is distributed on an "AS IS" BASIS,
  26608. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26609. * See the License for the specific language governing permissions and
  26610. * limitations under the License.
  26611. */
  26612. /*final*/ class SimpleToken extends Token {
  26613. constructor(previous, value, bitCount) {
  26614. super(previous);
  26615. this.value = value;
  26616. this.bitCount = bitCount;
  26617. }
  26618. /**
  26619. * @Override
  26620. */
  26621. appendTo(bitArray, text) {
  26622. bitArray.appendBits(this.value, this.bitCount);
  26623. }
  26624. add(value, bitCount) {
  26625. return new SimpleToken(this, value, bitCount);
  26626. }
  26627. addBinaryShift(start, byteCount) {
  26628. // no-op can't binary shift a simple token
  26629. console.warn('addBinaryShift on SimpleToken, this simply returns a copy of this token');
  26630. return new SimpleToken(this, start, byteCount);
  26631. }
  26632. /**
  26633. * @Override
  26634. */
  26635. toString() {
  26636. let value = this.value & ((1 << this.bitCount) - 1);
  26637. value |= 1 << this.bitCount;
  26638. return '<' + Integer.toBinaryString(value | (1 << this.bitCount)).substring(1) + '>';
  26639. }
  26640. }
  26641. /*
  26642. * Copyright 2013 ZXing authors
  26643. *
  26644. * Licensed under the Apache License, Version 2.0 (the "License");
  26645. * you may not use this file except in compliance with the License.
  26646. * You may obtain a copy of the License at
  26647. *
  26648. * http://www.apache.org/licenses/LICENSE-2.0
  26649. *
  26650. * Unless required by applicable law or agreed to in writing, software
  26651. * distributed under the License is distributed on an "AS IS" BASIS,
  26652. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26653. * See the License for the specific language governing permissions and
  26654. * limitations under the License.
  26655. */
  26656. /*final*/ class BinaryShiftToken extends SimpleToken {
  26657. constructor(previous, binaryShiftStart, binaryShiftByteCount) {
  26658. super(previous, 0, 0);
  26659. this.binaryShiftStart = binaryShiftStart;
  26660. this.binaryShiftByteCount = binaryShiftByteCount;
  26661. }
  26662. /**
  26663. * @Override
  26664. */
  26665. appendTo(bitArray, text) {
  26666. for (let i = 0; i < this.binaryShiftByteCount; i++) {
  26667. if (i === 0 || (i === 31 && this.binaryShiftByteCount <= 62)) {
  26668. // We need a header before the first character, and before
  26669. // character 31 when the total byte code is <= 62
  26670. bitArray.appendBits(31, 5); // BINARY_SHIFT
  26671. if (this.binaryShiftByteCount > 62) {
  26672. bitArray.appendBits(this.binaryShiftByteCount - 31, 16);
  26673. }
  26674. else if (i === 0) {
  26675. // 1 <= binaryShiftByteCode <= 62
  26676. bitArray.appendBits(Math.min(this.binaryShiftByteCount, 31), 5);
  26677. }
  26678. else {
  26679. // 32 <= binaryShiftCount <= 62 and i == 31
  26680. bitArray.appendBits(this.binaryShiftByteCount - 31, 5);
  26681. }
  26682. }
  26683. bitArray.appendBits(text[this.binaryShiftStart + i], 8);
  26684. }
  26685. }
  26686. addBinaryShift(start, byteCount) {
  26687. // int bitCount = (byteCount * 8) + (byteCount <= 31 ? 10 : byteCount <= 62 ? 20 : 21);
  26688. return new BinaryShiftToken(this, start, byteCount);
  26689. }
  26690. /**
  26691. * @Override
  26692. */
  26693. toString() {
  26694. return '<' + this.binaryShiftStart + '::' + (this.binaryShiftStart + this.binaryShiftByteCount - 1) + '>';
  26695. }
  26696. }
  26697. function addBinaryShift(token, start, byteCount) {
  26698. // int bitCount = (byteCount * 8) + (byteCount <= 31 ? 10 : byteCount <= 62 ? 20 : 21);
  26699. return new BinaryShiftToken(token, start, byteCount);
  26700. }
  26701. function add(token, value, bitCount) {
  26702. return new SimpleToken(token, value, bitCount);
  26703. }
  26704. const /*final*/ MODE_NAMES = [
  26705. 'UPPER',
  26706. 'LOWER',
  26707. 'DIGIT',
  26708. 'MIXED',
  26709. 'PUNCT'
  26710. ];
  26711. const /*final*/ MODE_UPPER = 0; // 5 bits
  26712. const /*final*/ MODE_LOWER = 1; // 5 bits
  26713. const /*final*/ MODE_DIGIT = 2; // 4 bits
  26714. const /*final*/ MODE_MIXED = 3; // 5 bits
  26715. const /*final*/ MODE_PUNCT = 4; // 5 bits
  26716. const EMPTY_TOKEN = new SimpleToken(null, 0, 0);
  26717. // The Latch Table shows, for each pair of Modes, the optimal method for
  26718. // getting from one mode to another. In the worst possible case, this can
  26719. // be up to 14 bits. In the best possible case, we are already there!
  26720. // The high half-word of each entry gives the number of bits.
  26721. // The low half-word of each entry are the actual bits necessary to change
  26722. const LATCH_TABLE = [
  26723. Int32Array.from([
  26724. 0,
  26725. (5 << 16) + 28,
  26726. (5 << 16) + 30,
  26727. (5 << 16) + 29,
  26728. (10 << 16) + (29 << 5) + 30 // UPPER -> MIXED -> PUNCT
  26729. ]),
  26730. Int32Array.from([
  26731. (9 << 16) + (30 << 4) + 14,
  26732. 0,
  26733. (5 << 16) + 30,
  26734. (5 << 16) + 29,
  26735. (10 << 16) + (29 << 5) + 30 // LOWER -> MIXED -> PUNCT
  26736. ]),
  26737. Int32Array.from([
  26738. (4 << 16) + 14,
  26739. (9 << 16) + (14 << 5) + 28,
  26740. 0,
  26741. (9 << 16) + (14 << 5) + 29,
  26742. (14 << 16) + (14 << 10) + (29 << 5) + 30
  26743. // DIGIT -> UPPER -> MIXED -> PUNCT
  26744. ]),
  26745. Int32Array.from([
  26746. (5 << 16) + 29,
  26747. (5 << 16) + 28,
  26748. (10 << 16) + (29 << 5) + 30,
  26749. 0,
  26750. (5 << 16) + 30 // MIXED -> PUNCT
  26751. ]),
  26752. Int32Array.from([
  26753. (5 << 16) + 31,
  26754. (10 << 16) + (31 << 5) + 28,
  26755. (10 << 16) + (31 << 5) + 30,
  26756. (10 << 16) + (31 << 5) + 29,
  26757. 0
  26758. ])
  26759. ];
  26760. function static_SHIFT_TABLE(SHIFT_TABLE) {
  26761. for (let table /*Int32Array*/ of SHIFT_TABLE) {
  26762. Arrays.fill(table, -1);
  26763. }
  26764. SHIFT_TABLE[MODE_UPPER][MODE_PUNCT] = 0;
  26765. SHIFT_TABLE[MODE_LOWER][MODE_PUNCT] = 0;
  26766. SHIFT_TABLE[MODE_LOWER][MODE_UPPER] = 28;
  26767. SHIFT_TABLE[MODE_MIXED][MODE_PUNCT] = 0;
  26768. SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT] = 0;
  26769. SHIFT_TABLE[MODE_DIGIT][MODE_UPPER] = 15;
  26770. return SHIFT_TABLE;
  26771. }
  26772. const /*final*/ SHIFT_TABLE = static_SHIFT_TABLE(Arrays.createInt32Array(6, 6)); // mode shift codes, per table
  26773. /*
  26774. * Copyright 2013 ZXing authors
  26775. *
  26776. * Licensed under the Apache License, Version 2.0 (the "License");
  26777. * you may not use this file except in compliance with the License.
  26778. * You may obtain a copy of the License at
  26779. *
  26780. * http://www.apache.org/licenses/LICENSE-2.0
  26781. *
  26782. * Unless required by applicable law or agreed to in writing, software
  26783. * distributed under the License is distributed on an "AS IS" BASIS,
  26784. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26785. * See the License for the specific language governing permissions and
  26786. * limitations under the License.
  26787. */
  26788. /**
  26789. * State represents all information about a sequence necessary to generate the current output.
  26790. * Note that a state is immutable.
  26791. */
  26792. /*final*/ class State {
  26793. constructor(token, mode, binaryBytes, bitCount) {
  26794. this.token = token;
  26795. this.mode = mode;
  26796. this.binaryShiftByteCount = binaryBytes;
  26797. this.bitCount = bitCount;
  26798. // Make sure we match the token
  26799. // int binaryShiftBitCount = (binaryShiftByteCount * 8) +
  26800. // (binaryShiftByteCount === 0 ? 0 :
  26801. // binaryShiftByteCount <= 31 ? 10 :
  26802. // binaryShiftByteCount <= 62 ? 20 : 21);
  26803. // assert this.bitCount === token.getTotalBitCount() + binaryShiftBitCount;
  26804. }
  26805. getMode() {
  26806. return this.mode;
  26807. }
  26808. getToken() {
  26809. return this.token;
  26810. }
  26811. getBinaryShiftByteCount() {
  26812. return this.binaryShiftByteCount;
  26813. }
  26814. getBitCount() {
  26815. return this.bitCount;
  26816. }
  26817. // Create a new state representing this state with a latch to a (not
  26818. // necessary different) mode, and then a code.
  26819. latchAndAppend(mode, value) {
  26820. // assert binaryShiftByteCount === 0;
  26821. let bitCount = this.bitCount;
  26822. let token = this.token;
  26823. if (mode !== this.mode) {
  26824. let latch = LATCH_TABLE[this.mode][mode];
  26825. token = add(token, latch & 0xffff, latch >> 16);
  26826. bitCount += latch >> 16;
  26827. }
  26828. let latchModeBitCount = mode === MODE_DIGIT ? 4 : 5;
  26829. token = add(token, value, latchModeBitCount);
  26830. return new State(token, mode, 0, bitCount + latchModeBitCount);
  26831. }
  26832. // Create a new state representing this state, with a temporary shift
  26833. // to a different mode to output a single value.
  26834. shiftAndAppend(mode, value) {
  26835. // assert binaryShiftByteCount === 0 && this.mode !== mode;
  26836. let token = this.token;
  26837. let thisModeBitCount = this.mode === MODE_DIGIT ? 4 : 5;
  26838. // Shifts exist only to UPPER and PUNCT, both with tokens size 5.
  26839. token = add(token, SHIFT_TABLE[this.mode][mode], thisModeBitCount);
  26840. token = add(token, value, 5);
  26841. return new State(token, this.mode, 0, this.bitCount + thisModeBitCount + 5);
  26842. }
  26843. // Create a new state representing this state, but an additional character
  26844. // output in Binary Shift mode.
  26845. addBinaryShiftChar(index) {
  26846. let token = this.token;
  26847. let mode = this.mode;
  26848. let bitCount = this.bitCount;
  26849. if (this.mode === MODE_PUNCT || this.mode === MODE_DIGIT) {
  26850. // assert binaryShiftByteCount === 0;
  26851. let latch = LATCH_TABLE[mode][MODE_UPPER];
  26852. token = add(token, latch & 0xffff, latch >> 16);
  26853. bitCount += latch >> 16;
  26854. mode = MODE_UPPER;
  26855. }
  26856. let deltaBitCount = this.binaryShiftByteCount === 0 || this.binaryShiftByteCount === 31
  26857. ? 18
  26858. : this.binaryShiftByteCount === 62
  26859. ? 9
  26860. : 8;
  26861. let result = new State(token, mode, this.binaryShiftByteCount + 1, bitCount + deltaBitCount);
  26862. if (result.binaryShiftByteCount === 2047 + 31) {
  26863. // The string is as long as it's allowed to be. We should end it.
  26864. result = result.endBinaryShift(index + 1);
  26865. }
  26866. return result;
  26867. }
  26868. // Create the state identical to this one, but we are no longer in
  26869. // Binary Shift mode.
  26870. endBinaryShift(index) {
  26871. if (this.binaryShiftByteCount === 0) {
  26872. return this;
  26873. }
  26874. let token = this.token;
  26875. token = addBinaryShift(token, index - this.binaryShiftByteCount, this.binaryShiftByteCount);
  26876. // assert token.getTotalBitCount() === this.bitCount;
  26877. return new State(token, this.mode, 0, this.bitCount);
  26878. }
  26879. // Returns true if "this" state is better (equal: or) to be in than "that"
  26880. // state under all possible circumstances.
  26881. isBetterThanOrEqualTo(other) {
  26882. let newModeBitCount = this.bitCount + (LATCH_TABLE[this.mode][other.mode] >> 16);
  26883. if (this.binaryShiftByteCount < other.binaryShiftByteCount) {
  26884. // add additional B/S encoding cost of other, if any
  26885. newModeBitCount +=
  26886. State.calculateBinaryShiftCost(other) -
  26887. State.calculateBinaryShiftCost(this);
  26888. }
  26889. else if (this.binaryShiftByteCount > other.binaryShiftByteCount &&
  26890. other.binaryShiftByteCount > 0) {
  26891. // maximum possible additional cost (it: h)
  26892. newModeBitCount += 10;
  26893. }
  26894. return newModeBitCount <= other.bitCount;
  26895. }
  26896. toBitArray(text) {
  26897. // Reverse the tokens, so that they are in the order that they should
  26898. // be output
  26899. let symbols = [];
  26900. for (let token = this.endBinaryShift(text.length).token; token !== null; token = token.getPrevious()) {
  26901. symbols.unshift(token);
  26902. }
  26903. let bitArray = new BitArray();
  26904. // Add each token to the result.
  26905. for (const symbol of symbols) {
  26906. symbol.appendTo(bitArray, text);
  26907. }
  26908. // assert bitArray.getSize() === this.bitCount;
  26909. return bitArray;
  26910. }
  26911. /**
  26912. * @Override
  26913. */
  26914. toString() {
  26915. return StringUtils.format('%s bits=%d bytes=%d', MODE_NAMES[this.mode], this.bitCount, this.binaryShiftByteCount);
  26916. }
  26917. static calculateBinaryShiftCost(state) {
  26918. if (state.binaryShiftByteCount > 62) {
  26919. return 21; // B/S with extended length
  26920. }
  26921. if (state.binaryShiftByteCount > 31) {
  26922. return 20; // two B/S
  26923. }
  26924. if (state.binaryShiftByteCount > 0) {
  26925. return 10; // one B/S
  26926. }
  26927. return 0;
  26928. }
  26929. }
  26930. State.INITIAL_STATE = new State(EMPTY_TOKEN, MODE_UPPER, 0, 0);
  26931. function static_CHAR_MAP(CHAR_MAP) {
  26932. const spaceCharCode = StringUtils.getCharCode(' ');
  26933. const pointCharCode = StringUtils.getCharCode('.');
  26934. const commaCharCode = StringUtils.getCharCode(',');
  26935. CHAR_MAP[MODE_UPPER][spaceCharCode] = 1;
  26936. const zUpperCharCode = StringUtils.getCharCode('Z');
  26937. const aUpperCharCode = StringUtils.getCharCode('A');
  26938. for (let c = aUpperCharCode; c <= zUpperCharCode; c++) {
  26939. CHAR_MAP[MODE_UPPER][c] = c - aUpperCharCode + 2;
  26940. }
  26941. CHAR_MAP[MODE_LOWER][spaceCharCode] = 1;
  26942. const zLowerCharCode = StringUtils.getCharCode('z');
  26943. const aLowerCharCode = StringUtils.getCharCode('a');
  26944. for (let c = aLowerCharCode; c <= zLowerCharCode; c++) {
  26945. CHAR_MAP[MODE_LOWER][c] = c - aLowerCharCode + 2;
  26946. }
  26947. CHAR_MAP[MODE_DIGIT][spaceCharCode] = 1;
  26948. const nineCharCode = StringUtils.getCharCode('9');
  26949. const zeroCharCode = StringUtils.getCharCode('0');
  26950. for (let c = zeroCharCode; c <= nineCharCode; c++) {
  26951. CHAR_MAP[MODE_DIGIT][c] = c - zeroCharCode + 2;
  26952. }
  26953. CHAR_MAP[MODE_DIGIT][commaCharCode] = 12;
  26954. CHAR_MAP[MODE_DIGIT][pointCharCode] = 13;
  26955. const mixedTable = [
  26956. '\x00',
  26957. ' ',
  26958. '\x01',
  26959. '\x02',
  26960. '\x03',
  26961. '\x04',
  26962. '\x05',
  26963. '\x06',
  26964. '\x07',
  26965. '\b',
  26966. '\t',
  26967. '\n',
  26968. '\x0b',
  26969. '\f',
  26970. '\r',
  26971. '\x1b',
  26972. '\x1c',
  26973. '\x1d',
  26974. '\x1e',
  26975. '\x1f',
  26976. '@',
  26977. '\\',
  26978. '^',
  26979. '_',
  26980. '`',
  26981. '|',
  26982. '~',
  26983. '\x7f'
  26984. ];
  26985. for (let i = 0; i < mixedTable.length; i++) {
  26986. CHAR_MAP[MODE_MIXED][StringUtils.getCharCode(mixedTable[i])] = i;
  26987. }
  26988. const punctTable = [
  26989. '\x00',
  26990. '\r',
  26991. '\x00',
  26992. '\x00',
  26993. '\x00',
  26994. '\x00',
  26995. '!',
  26996. '\'',
  26997. '#',
  26998. '$',
  26999. '%',
  27000. '&',
  27001. '\'',
  27002. '(',
  27003. ')',
  27004. '*',
  27005. '+',
  27006. ',',
  27007. '-',
  27008. '.',
  27009. '/',
  27010. ':',
  27011. ';',
  27012. '<',
  27013. '=',
  27014. '>',
  27015. '?',
  27016. '[',
  27017. ']',
  27018. '{',
  27019. '}'
  27020. ];
  27021. for (let i = 0; i < punctTable.length; i++) {
  27022. if (StringUtils.getCharCode(punctTable[i]) > 0) {
  27023. CHAR_MAP[MODE_PUNCT][StringUtils.getCharCode(punctTable[i])] = i;
  27024. }
  27025. }
  27026. return CHAR_MAP;
  27027. }
  27028. const CHAR_MAP = static_CHAR_MAP(Arrays.createInt32Array(5, 256));
  27029. /*
  27030. * Copyright 2013 ZXing authors
  27031. *
  27032. * Licensed under the Apache License, Version 2.0 (the "License");
  27033. * you may not use this file except in compliance with the License.
  27034. * You may obtain a copy of the License at
  27035. *
  27036. * http://www.apache.org/licenses/LICENSE-2.0
  27037. *
  27038. * Unless required by applicable law or agreed to in writing, software
  27039. * distributed under the License is distributed on an "AS IS" BASIS,
  27040. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27041. * See the License for the specific language governing permissions and
  27042. * limitations under the License.
  27043. */
  27044. /**
  27045. * This produces nearly optimal encodings of text into the first-level of
  27046. * encoding used by Aztec code.
  27047. *
  27048. * It uses a dynamic algorithm. For each prefix of the string, it determines
  27049. * a set of encodings that could lead to this prefix. We repeatedly add a
  27050. * character and generate a new set of optimal encodings until we have read
  27051. * through the entire input.
  27052. *
  27053. * @author Frank Yellin
  27054. * @author Rustam Abdullaev
  27055. */
  27056. /*public final*/ class HighLevelEncoder$1 {
  27057. constructor(text) {
  27058. this.text = text;
  27059. }
  27060. /**
  27061. * @return text represented by this encoder encoded as a {@link BitArray}
  27062. */
  27063. encode() {
  27064. const spaceCharCode = StringUtils.getCharCode(' ');
  27065. const lineBreakCharCode = StringUtils.getCharCode('\n');
  27066. let states = Collections.singletonList(State.INITIAL_STATE);
  27067. for (let index = 0; index < this.text.length; index++) {
  27068. let pairCode;
  27069. let nextChar = index + 1 < this.text.length ? this.text[index + 1] : 0;
  27070. switch (this.text[index]) {
  27071. case StringUtils.getCharCode('\r'):
  27072. pairCode = nextChar === lineBreakCharCode ? 2 : 0;
  27073. break;
  27074. case StringUtils.getCharCode('.'):
  27075. pairCode = nextChar === spaceCharCode ? 3 : 0;
  27076. break;
  27077. case StringUtils.getCharCode(','):
  27078. pairCode = nextChar === spaceCharCode ? 4 : 0;
  27079. break;
  27080. case StringUtils.getCharCode(':'):
  27081. pairCode = nextChar === spaceCharCode ? 5 : 0;
  27082. break;
  27083. default:
  27084. pairCode = 0;
  27085. }
  27086. if (pairCode > 0) {
  27087. // We have one of the four special PUNCT pairs. Treat them specially.
  27088. // Get a new set of states for the two new characters.
  27089. states = HighLevelEncoder$1.updateStateListForPair(states, index, pairCode);
  27090. index++;
  27091. }
  27092. else {
  27093. // Get a new set of states for the new character.
  27094. states = this.updateStateListForChar(states, index);
  27095. }
  27096. }
  27097. // We are left with a set of states. Find the shortest one.
  27098. const minState = Collections.min(states, (a, b) => {
  27099. return a.getBitCount() - b.getBitCount();
  27100. });
  27101. // Convert it to a bit array, and return.
  27102. return minState.toBitArray(this.text);
  27103. }
  27104. // We update a set of states for a new character by updating each state
  27105. // for the new character, merging the results, and then removing the
  27106. // non-optimal states.
  27107. updateStateListForChar(states, index) {
  27108. const result = [];
  27109. for (let state /*State*/ of states) {
  27110. this.updateStateForChar(state, index, result);
  27111. }
  27112. return HighLevelEncoder$1.simplifyStates(result);
  27113. }
  27114. // Return a set of states that represent the possible ways of updating this
  27115. // state for the next character. The resulting set of states are added to
  27116. // the "result" list.
  27117. updateStateForChar(state, index, result) {
  27118. let ch = (this.text[index] & 0xff);
  27119. let charInCurrentTable = CHAR_MAP[state.getMode()][ch] > 0;
  27120. let stateNoBinary = null;
  27121. for (let mode /*int*/ = 0; mode <= MODE_PUNCT; mode++) {
  27122. let charInMode = CHAR_MAP[mode][ch];
  27123. if (charInMode > 0) {
  27124. if (stateNoBinary == null) {
  27125. // Only create stateNoBinary the first time it's required.
  27126. stateNoBinary = state.endBinaryShift(index);
  27127. }
  27128. // Try generating the character by latching to its mode
  27129. if (!charInCurrentTable ||
  27130. mode === state.getMode() ||
  27131. mode === MODE_DIGIT) {
  27132. // If the character is in the current table, we don't want to latch to
  27133. // any other mode except possibly digit (which uses only 4 bits). Any
  27134. // other latch would be equally successful *after* this character, and
  27135. // so wouldn't save any bits.
  27136. const latchState = stateNoBinary.latchAndAppend(mode, charInMode);
  27137. result.push(latchState);
  27138. }
  27139. // Try generating the character by switching to its mode.
  27140. if (!charInCurrentTable &&
  27141. SHIFT_TABLE[state.getMode()][mode] >= 0) {
  27142. // It never makes sense to temporarily shift to another mode if the
  27143. // character exists in the current mode. That can never save bits.
  27144. const shiftState = stateNoBinary.shiftAndAppend(mode, charInMode);
  27145. result.push(shiftState);
  27146. }
  27147. }
  27148. }
  27149. if (state.getBinaryShiftByteCount() > 0 ||
  27150. CHAR_MAP[state.getMode()][ch] === 0) {
  27151. // It's never worthwhile to go into binary shift mode if you're not already
  27152. // in binary shift mode, and the character exists in your current mode.
  27153. // That can never save bits over just outputting the char in the current mode.
  27154. let binaryState = state.addBinaryShiftChar(index);
  27155. result.push(binaryState);
  27156. }
  27157. }
  27158. static updateStateListForPair(states, index, pairCode) {
  27159. const result = [];
  27160. for (let state /*State*/ of states) {
  27161. this.updateStateForPair(state, index, pairCode, result);
  27162. }
  27163. return this.simplifyStates(result);
  27164. }
  27165. static updateStateForPair(state, index, pairCode, result) {
  27166. let stateNoBinary = state.endBinaryShift(index);
  27167. // Possibility 1. Latch to C.MODE_PUNCT, and then append this code
  27168. result.push(stateNoBinary.latchAndAppend(MODE_PUNCT, pairCode));
  27169. if (state.getMode() !== MODE_PUNCT) {
  27170. // Possibility 2. Shift to C.MODE_PUNCT, and then append this code.
  27171. // Every state except C.MODE_PUNCT (handled above) can shift
  27172. result.push(stateNoBinary.shiftAndAppend(MODE_PUNCT, pairCode));
  27173. }
  27174. if (pairCode === 3 || pairCode === 4) {
  27175. // both characters are in DIGITS. Sometimes better to just add two digits
  27176. let digitState = stateNoBinary
  27177. .latchAndAppend(MODE_DIGIT, 16 - pairCode) // period or comma in DIGIT
  27178. .latchAndAppend(MODE_DIGIT, 1); // space in DIGIT
  27179. result.push(digitState);
  27180. }
  27181. if (state.getBinaryShiftByteCount() > 0) {
  27182. // It only makes sense to do the characters as binary if we're already
  27183. // in binary mode.
  27184. let binaryState = state
  27185. .addBinaryShiftChar(index)
  27186. .addBinaryShiftChar(index + 1);
  27187. result.push(binaryState);
  27188. }
  27189. }
  27190. static simplifyStates(states) {
  27191. let result = [];
  27192. for (const newState of states) {
  27193. let add = true;
  27194. for (const oldState of result) {
  27195. if (oldState.isBetterThanOrEqualTo(newState)) {
  27196. add = false;
  27197. break;
  27198. }
  27199. if (newState.isBetterThanOrEqualTo(oldState)) {
  27200. // iterator.remove();
  27201. result = result.filter(x => x !== oldState); // remove old state
  27202. }
  27203. }
  27204. if (add) {
  27205. result.push(newState);
  27206. }
  27207. }
  27208. return result;
  27209. }
  27210. }
  27211. /*
  27212. * Copyright 2013 ZXing authors
  27213. *
  27214. * Licensed under the Apache License, Version 2.0 (the "License");
  27215. * you may not use this file except in compliance with the License.
  27216. * You may obtain a copy of the License at
  27217. *
  27218. * http://www.apache.org/licenses/LICENSE-2.0
  27219. *
  27220. * Unless required by applicable law or agreed to in writing, software
  27221. * distributed under the License is distributed on an "AS IS" BASIS,
  27222. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27223. * See the License for the specific language governing permissions and
  27224. * limitations under the License.
  27225. */
  27226. // package com.google.zxing.aztec.encoder;
  27227. // import com.google.zxing.common.BitArray;
  27228. // import com.google.zxing.common.BitMatrix;
  27229. // import com.google.zxing.common.reedsolomon.GenericGF;
  27230. // import com.google.zxing.common.reedsolomon.ReedSolomonEncoder;
  27231. /**
  27232. * Generates Aztec 2D barcodes.
  27233. *
  27234. * @author Rustam Abdullaev
  27235. */
  27236. /*public final*/ class Encoder$1 {
  27237. constructor() {
  27238. }
  27239. /**
  27240. * Encodes the given binary content as an Aztec symbol
  27241. *
  27242. * @param data input data string
  27243. * @return Aztec symbol matrix with metadata
  27244. */
  27245. static encodeBytes(data) {
  27246. return Encoder$1.encode(data, Encoder$1.DEFAULT_EC_PERCENT, Encoder$1.DEFAULT_AZTEC_LAYERS);
  27247. }
  27248. /**
  27249. * Encodes the given binary content as an Aztec symbol
  27250. *
  27251. * @param data input data string
  27252. * @param minECCPercent minimal percentage of error check words (According to ISO/IEC 24778:2008,
  27253. * a minimum of 23% + 3 words is recommended)
  27254. * @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers
  27255. * @return Aztec symbol matrix with metadata
  27256. */
  27257. static encode(data, minECCPercent, userSpecifiedLayers) {
  27258. // High-level encode
  27259. let bits = new HighLevelEncoder$1(data).encode();
  27260. // stuff bits and choose symbol size
  27261. let eccBits = Integer.truncDivision((bits.getSize() * minECCPercent), 100) + 11;
  27262. let totalSizeBits = bits.getSize() + eccBits;
  27263. let compact;
  27264. let layers;
  27265. let totalBitsInLayer;
  27266. let wordSize;
  27267. let stuffedBits;
  27268. if (userSpecifiedLayers !== Encoder$1.DEFAULT_AZTEC_LAYERS) {
  27269. compact = userSpecifiedLayers < 0;
  27270. layers = Math.abs(userSpecifiedLayers);
  27271. if (layers > (compact ? Encoder$1.MAX_NB_BITS_COMPACT : Encoder$1.MAX_NB_BITS)) {
  27272. throw new IllegalArgumentException(StringUtils.format('Illegal value %s for layers', userSpecifiedLayers));
  27273. }
  27274. totalBitsInLayer = Encoder$1.totalBitsInLayer(layers, compact);
  27275. wordSize = Encoder$1.WORD_SIZE[layers];
  27276. let usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize);
  27277. stuffedBits = Encoder$1.stuffBits(bits, wordSize);
  27278. if (stuffedBits.getSize() + eccBits > usableBitsInLayers) {
  27279. throw new IllegalArgumentException('Data to large for user specified layer');
  27280. }
  27281. if (compact && stuffedBits.getSize() > wordSize * 64) {
  27282. // Compact format only allows 64 data words, though C4 can hold more words than that
  27283. throw new IllegalArgumentException('Data to large for user specified layer');
  27284. }
  27285. }
  27286. else {
  27287. wordSize = 0;
  27288. stuffedBits = null;
  27289. // We look at the possible table sizes in the order Compact1, Compact2, Compact3,
  27290. // Compact4, Normal4,... Normal(i) for i < 4 isn't typically used since Compact(i+1)
  27291. // is the same size, but has more data.
  27292. for (let i /*int*/ = 0;; i++) {
  27293. if (i > Encoder$1.MAX_NB_BITS) {
  27294. throw new IllegalArgumentException('Data too large for an Aztec code');
  27295. }
  27296. compact = i <= 3;
  27297. layers = compact ? i + 1 : i;
  27298. totalBitsInLayer = Encoder$1.totalBitsInLayer(layers, compact);
  27299. if (totalSizeBits > totalBitsInLayer) {
  27300. continue;
  27301. }
  27302. // [Re]stuff the bits if this is the first opportunity, or if the
  27303. // wordSize has changed
  27304. if (stuffedBits == null || wordSize !== Encoder$1.WORD_SIZE[layers]) {
  27305. wordSize = Encoder$1.WORD_SIZE[layers];
  27306. stuffedBits = Encoder$1.stuffBits(bits, wordSize);
  27307. }
  27308. let usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize);
  27309. if (compact && stuffedBits.getSize() > wordSize * 64) {
  27310. // Compact format only allows 64 data words, though C4 can hold more words than that
  27311. continue;
  27312. }
  27313. if (stuffedBits.getSize() + eccBits <= usableBitsInLayers) {
  27314. break;
  27315. }
  27316. }
  27317. }
  27318. let messageBits = Encoder$1.generateCheckWords(stuffedBits, totalBitsInLayer, wordSize);
  27319. // generate mode message
  27320. let messageSizeInWords = stuffedBits.getSize() / wordSize;
  27321. let modeMessage = Encoder$1.generateModeMessage(compact, layers, messageSizeInWords);
  27322. // allocate symbol
  27323. let baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines
  27324. let alignmentMap = new Int32Array(baseMatrixSize);
  27325. let matrixSize;
  27326. if (compact) {
  27327. // no alignment marks in compact mode, alignmentMap is a no-op
  27328. matrixSize = baseMatrixSize;
  27329. for (let i /*int*/ = 0; i < alignmentMap.length; i++) {
  27330. alignmentMap[i] = i;
  27331. }
  27332. }
  27333. else {
  27334. matrixSize = baseMatrixSize + 1 + 2 * Integer.truncDivision((Integer.truncDivision(baseMatrixSize, 2) - 1), 15);
  27335. let origCenter = Integer.truncDivision(baseMatrixSize, 2);
  27336. let center = Integer.truncDivision(matrixSize, 2);
  27337. for (let i /*int*/ = 0; i < origCenter; i++) {
  27338. let newOffset = i + Integer.truncDivision(i, 15);
  27339. alignmentMap[origCenter - i - 1] = center - newOffset - 1;
  27340. alignmentMap[origCenter + i] = center + newOffset + 1;
  27341. }
  27342. }
  27343. let matrix = new BitMatrix(matrixSize);
  27344. // draw data bits
  27345. for (let i /*int*/ = 0, rowOffset = 0; i < layers; i++) {
  27346. let rowSize = (layers - i) * 4 + (compact ? 9 : 12);
  27347. for (let j /*int*/ = 0; j < rowSize; j++) {
  27348. let columnOffset = j * 2;
  27349. for (let k /*int*/ = 0; k < 2; k++) {
  27350. if (messageBits.get(rowOffset + columnOffset + k)) {
  27351. matrix.set(alignmentMap[i * 2 + k], alignmentMap[i * 2 + j]);
  27352. }
  27353. if (messageBits.get(rowOffset + rowSize * 2 + columnOffset + k)) {
  27354. matrix.set(alignmentMap[i * 2 + j], alignmentMap[baseMatrixSize - 1 - i * 2 - k]);
  27355. }
  27356. if (messageBits.get(rowOffset + rowSize * 4 + columnOffset + k)) {
  27357. matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - k], alignmentMap[baseMatrixSize - 1 - i * 2 - j]);
  27358. }
  27359. if (messageBits.get(rowOffset + rowSize * 6 + columnOffset + k)) {
  27360. matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - j], alignmentMap[i * 2 + k]);
  27361. }
  27362. }
  27363. }
  27364. rowOffset += rowSize * 8;
  27365. }
  27366. // draw mode message
  27367. Encoder$1.drawModeMessage(matrix, compact, matrixSize, modeMessage);
  27368. // draw alignment marks
  27369. if (compact) {
  27370. Encoder$1.drawBullsEye(matrix, Integer.truncDivision(matrixSize, 2), 5);
  27371. }
  27372. else {
  27373. Encoder$1.drawBullsEye(matrix, Integer.truncDivision(matrixSize, 2), 7);
  27374. for (let i /*int*/ = 0, j = 0; i < Integer.truncDivision(baseMatrixSize, 2) - 1; i += 15, j += 16) {
  27375. for (let k /*int*/ = Integer.truncDivision(matrixSize, 2) & 1; k < matrixSize; k += 2) {
  27376. matrix.set(Integer.truncDivision(matrixSize, 2) - j, k);
  27377. matrix.set(Integer.truncDivision(matrixSize, 2) + j, k);
  27378. matrix.set(k, Integer.truncDivision(matrixSize, 2) - j);
  27379. matrix.set(k, Integer.truncDivision(matrixSize, 2) + j);
  27380. }
  27381. }
  27382. }
  27383. let aztec = new AztecCode();
  27384. aztec.setCompact(compact);
  27385. aztec.setSize(matrixSize);
  27386. aztec.setLayers(layers);
  27387. aztec.setCodeWords(messageSizeInWords);
  27388. aztec.setMatrix(matrix);
  27389. return aztec;
  27390. }
  27391. static drawBullsEye(matrix, center, size) {
  27392. for (let i /*int*/ = 0; i < size; i += 2) {
  27393. for (let j /*int*/ = center - i; j <= center + i; j++) {
  27394. matrix.set(j, center - i);
  27395. matrix.set(j, center + i);
  27396. matrix.set(center - i, j);
  27397. matrix.set(center + i, j);
  27398. }
  27399. }
  27400. matrix.set(center - size, center - size);
  27401. matrix.set(center - size + 1, center - size);
  27402. matrix.set(center - size, center - size + 1);
  27403. matrix.set(center + size, center - size);
  27404. matrix.set(center + size, center - size + 1);
  27405. matrix.set(center + size, center + size - 1);
  27406. }
  27407. static generateModeMessage(compact, layers, messageSizeInWords) {
  27408. let modeMessage = new BitArray();
  27409. if (compact) {
  27410. modeMessage.appendBits(layers - 1, 2);
  27411. modeMessage.appendBits(messageSizeInWords - 1, 6);
  27412. modeMessage = Encoder$1.generateCheckWords(modeMessage, 28, 4);
  27413. }
  27414. else {
  27415. modeMessage.appendBits(layers - 1, 5);
  27416. modeMessage.appendBits(messageSizeInWords - 1, 11);
  27417. modeMessage = Encoder$1.generateCheckWords(modeMessage, 40, 4);
  27418. }
  27419. return modeMessage;
  27420. }
  27421. static drawModeMessage(matrix, compact, matrixSize, modeMessage) {
  27422. let center = Integer.truncDivision(matrixSize, 2);
  27423. if (compact) {
  27424. for (let i /*int*/ = 0; i < 7; i++) {
  27425. let offset = center - 3 + i;
  27426. if (modeMessage.get(i)) {
  27427. matrix.set(offset, center - 5);
  27428. }
  27429. if (modeMessage.get(i + 7)) {
  27430. matrix.set(center + 5, offset);
  27431. }
  27432. if (modeMessage.get(20 - i)) {
  27433. matrix.set(offset, center + 5);
  27434. }
  27435. if (modeMessage.get(27 - i)) {
  27436. matrix.set(center - 5, offset);
  27437. }
  27438. }
  27439. }
  27440. else {
  27441. for (let i /*int*/ = 0; i < 10; i++) {
  27442. let offset = center - 5 + i + Integer.truncDivision(i, 5);
  27443. if (modeMessage.get(i)) {
  27444. matrix.set(offset, center - 7);
  27445. }
  27446. if (modeMessage.get(i + 10)) {
  27447. matrix.set(center + 7, offset);
  27448. }
  27449. if (modeMessage.get(29 - i)) {
  27450. matrix.set(offset, center + 7);
  27451. }
  27452. if (modeMessage.get(39 - i)) {
  27453. matrix.set(center - 7, offset);
  27454. }
  27455. }
  27456. }
  27457. }
  27458. static generateCheckWords(bitArray, totalBits, wordSize) {
  27459. // bitArray is guaranteed to be a multiple of the wordSize, so no padding needed
  27460. let messageSizeInWords = bitArray.getSize() / wordSize;
  27461. let rs = new ReedSolomonEncoder(Encoder$1.getGF(wordSize));
  27462. let totalWords = Integer.truncDivision(totalBits, wordSize);
  27463. let messageWords = Encoder$1.bitsToWords(bitArray, wordSize, totalWords);
  27464. rs.encode(messageWords, totalWords - messageSizeInWords);
  27465. let startPad = totalBits % wordSize;
  27466. let messageBits = new BitArray();
  27467. messageBits.appendBits(0, startPad);
  27468. for (const messageWord /*: int*/ of Array.from(messageWords)) {
  27469. messageBits.appendBits(messageWord, wordSize);
  27470. }
  27471. return messageBits;
  27472. }
  27473. static bitsToWords(stuffedBits, wordSize, totalWords) {
  27474. let message = new Int32Array(totalWords);
  27475. let i;
  27476. let n;
  27477. for (i = 0, n = stuffedBits.getSize() / wordSize; i < n; i++) {
  27478. let value = 0;
  27479. for (let j /*int*/ = 0; j < wordSize; j++) {
  27480. value |= stuffedBits.get(i * wordSize + j) ? (1 << wordSize - j - 1) : 0;
  27481. }
  27482. message[i] = value;
  27483. }
  27484. return message;
  27485. }
  27486. static getGF(wordSize) {
  27487. switch (wordSize) {
  27488. case 4:
  27489. return GenericGF.AZTEC_PARAM;
  27490. case 6:
  27491. return GenericGF.AZTEC_DATA_6;
  27492. case 8:
  27493. return GenericGF.AZTEC_DATA_8;
  27494. case 10:
  27495. return GenericGF.AZTEC_DATA_10;
  27496. case 12:
  27497. return GenericGF.AZTEC_DATA_12;
  27498. default:
  27499. throw new IllegalArgumentException('Unsupported word size ' + wordSize);
  27500. }
  27501. }
  27502. static stuffBits(bits, wordSize) {
  27503. let out = new BitArray();
  27504. let n = bits.getSize();
  27505. let mask = (1 << wordSize) - 2;
  27506. for (let i /*int*/ = 0; i < n; i += wordSize) {
  27507. let word = 0;
  27508. for (let j /*int*/ = 0; j < wordSize; j++) {
  27509. if (i + j >= n || bits.get(i + j)) {
  27510. word |= 1 << (wordSize - 1 - j);
  27511. }
  27512. }
  27513. if ((word & mask) === mask) {
  27514. out.appendBits(word & mask, wordSize);
  27515. i--;
  27516. }
  27517. else if ((word & mask) === 0) {
  27518. out.appendBits(word | 1, wordSize);
  27519. i--;
  27520. }
  27521. else {
  27522. out.appendBits(word, wordSize);
  27523. }
  27524. }
  27525. return out;
  27526. }
  27527. static totalBitsInLayer(layers, compact) {
  27528. return ((compact ? 88 : 112) + 16 * layers) * layers;
  27529. }
  27530. }
  27531. Encoder$1.DEFAULT_EC_PERCENT = 33; // default minimal percentage of error check words
  27532. Encoder$1.DEFAULT_AZTEC_LAYERS = 0;
  27533. Encoder$1.MAX_NB_BITS = 32;
  27534. Encoder$1.MAX_NB_BITS_COMPACT = 4;
  27535. Encoder$1.WORD_SIZE = Int32Array.from([
  27536. 4, 6, 6, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
  27537. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12
  27538. ]);
  27539. /*
  27540. * Copyright 2013 ZXing authors
  27541. *
  27542. * Licensed under the Apache License, Version 2.0 (the "License");
  27543. * you may not use this file except in compliance with the License.
  27544. * You may obtain a copy of the License at
  27545. *
  27546. * http://www.apache.org/licenses/LICENSE-2.0
  27547. *
  27548. * Unless required by applicable law or agreed to in writing, software
  27549. * distributed under the License is distributed on an "AS IS" BASIS,
  27550. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27551. * See the License for the specific language governing permissions and
  27552. * limitations under the License.
  27553. */
  27554. /**
  27555. * Renders an Aztec code as a {@link BitMatrix}.
  27556. */
  27557. /*public final*/ class AztecWriter {
  27558. // @Override
  27559. encode(contents, format, width, height) {
  27560. return this.encodeWithHints(contents, format, width, height, null);
  27561. }
  27562. // @Override
  27563. encodeWithHints(contents, format, width, height, hints) {
  27564. let charset = StandardCharsets.ISO_8859_1;
  27565. let eccPercent = Encoder$1.DEFAULT_EC_PERCENT;
  27566. let layers = Encoder$1.DEFAULT_AZTEC_LAYERS;
  27567. if (hints != null) {
  27568. if (hints.has(EncodeHintType$1.CHARACTER_SET)) {
  27569. charset = Charset.forName(hints.get(EncodeHintType$1.CHARACTER_SET).toString());
  27570. }
  27571. if (hints.has(EncodeHintType$1.ERROR_CORRECTION)) {
  27572. eccPercent = Integer.parseInt(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());
  27573. }
  27574. if (hints.has(EncodeHintType$1.AZTEC_LAYERS)) {
  27575. layers = Integer.parseInt(hints.get(EncodeHintType$1.AZTEC_LAYERS).toString());
  27576. }
  27577. }
  27578. return AztecWriter.encodeLayers(contents, format, width, height, charset, eccPercent, layers);
  27579. }
  27580. static encodeLayers(contents, format, width, height, charset, eccPercent, layers) {
  27581. if (format !== BarcodeFormat$1.AZTEC) {
  27582. throw new IllegalArgumentException('Can only encode AZTEC, but got ' + format);
  27583. }
  27584. let aztec = Encoder$1.encode(StringUtils.getBytes(contents, charset), eccPercent, layers);
  27585. return AztecWriter.renderResult(aztec, width, height);
  27586. }
  27587. static renderResult(code, width, height) {
  27588. let input = code.getMatrix();
  27589. if (input == null) {
  27590. throw new IllegalStateException();
  27591. }
  27592. let inputWidth = input.getWidth();
  27593. let inputHeight = input.getHeight();
  27594. let outputWidth = Math.max(width, inputWidth);
  27595. let outputHeight = Math.max(height, inputHeight);
  27596. let multiple = Math.min(outputWidth / inputWidth, outputHeight / inputHeight);
  27597. let leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
  27598. let topPadding = (outputHeight - (inputHeight * multiple)) / 2;
  27599. let output = new BitMatrix(outputWidth, outputHeight);
  27600. for (let inputY /*int*/ = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
  27601. // Write the contents of this row of the barcode
  27602. for (let inputX /*int*/ = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
  27603. if (input.get(inputX, inputY)) {
  27604. output.setRegion(outputX, outputY, multiple, multiple);
  27605. }
  27606. }
  27607. }
  27608. return output;
  27609. }
  27610. }
  27611. exports.AbstractExpandedDecoder = AbstractExpandedDecoder;
  27612. exports.ArgumentException = ArgumentException;
  27613. exports.ArithmeticException = ArithmeticException;
  27614. exports.AztecCode = AztecCode;
  27615. exports.AztecCodeReader = AztecReader;
  27616. exports.AztecCodeWriter = AztecWriter;
  27617. exports.AztecDecoder = Decoder;
  27618. exports.AztecDetector = Detector;
  27619. exports.AztecDetectorResult = AztecDetectorResult;
  27620. exports.AztecEncoder = Encoder$1;
  27621. exports.AztecHighLevelEncoder = HighLevelEncoder$1;
  27622. exports.AztecPoint = Point;
  27623. exports.BarcodeFormat = BarcodeFormat$1;
  27624. exports.Binarizer = Binarizer;
  27625. exports.BinaryBitmap = BinaryBitmap;
  27626. exports.BitArray = BitArray;
  27627. exports.BitMatrix = BitMatrix;
  27628. exports.BitSource = BitSource;
  27629. exports.BrowserAztecCodeReader = BrowserAztecCodeReader;
  27630. exports.BrowserBarcodeReader = BrowserBarcodeReader;
  27631. exports.BrowserCodeReader = BrowserCodeReader;
  27632. exports.BrowserDatamatrixCodeReader = BrowserDatamatrixCodeReader;
  27633. exports.BrowserMultiFormatReader = BrowserMultiFormatReader;
  27634. exports.BrowserPDF417Reader = BrowserPDF417Reader;
  27635. exports.BrowserQRCodeReader = BrowserQRCodeReader;
  27636. exports.BrowserQRCodeSvgWriter = BrowserQRCodeSvgWriter;
  27637. exports.CharacterSetECI = CharacterSetECI;
  27638. exports.ChecksumException = ChecksumException;
  27639. exports.CodaBarReader = CodaBarReader;
  27640. exports.Code128Reader = Code128Reader;
  27641. exports.Code39Reader = Code39Reader;
  27642. exports.Code93Reader = Code93Reader;
  27643. exports.DataMatrixDecodedBitStreamParser = DecodedBitStreamParser;
  27644. exports.DataMatrixDefaultPlacement = DefaultPlacement;
  27645. exports.DataMatrixErrorCorrection = ErrorCorrection$1;
  27646. exports.DataMatrixHighLevelEncoder = HighLevelEncoder;
  27647. exports.DataMatrixReader = DataMatrixReader;
  27648. exports.DataMatrixSymbolInfo = SymbolInfo;
  27649. exports.DataMatrixWriter = DataMatrixWriter;
  27650. exports.DecodeHintType = DecodeHintType$1;
  27651. exports.DecoderResult = DecoderResult;
  27652. exports.DefaultGridSampler = DefaultGridSampler;
  27653. exports.DetectorResult = DetectorResult;
  27654. exports.EAN13Reader = EAN13Reader;
  27655. exports.EncodeHintType = EncodeHintType$1;
  27656. exports.Exception = Exception;
  27657. exports.FormatException = FormatException;
  27658. exports.GenericGF = GenericGF;
  27659. exports.GenericGFPoly = GenericGFPoly;
  27660. exports.GlobalHistogramBinarizer = GlobalHistogramBinarizer;
  27661. exports.GridSampler = GridSampler;
  27662. exports.GridSamplerInstance = GridSamplerInstance;
  27663. exports.HTMLCanvasElementLuminanceSource = HTMLCanvasElementLuminanceSource;
  27664. exports.HybridBinarizer = HybridBinarizer;
  27665. exports.ITFReader = ITFReader;
  27666. exports.IllegalArgumentException = IllegalArgumentException;
  27667. exports.IllegalStateException = IllegalStateException;
  27668. exports.InvertedLuminanceSource = InvertedLuminanceSource;
  27669. exports.LuminanceSource = LuminanceSource;
  27670. exports.MathUtils = MathUtils;
  27671. exports.MultiFormatOneDReader = MultiFormatOneDReader;
  27672. exports.MultiFormatReader = MultiFormatReader;
  27673. exports.MultiFormatWriter = MultiFormatWriter;
  27674. exports.NotFoundException = NotFoundException;
  27675. exports.OneDReader = OneDReader;
  27676. exports.PDF417DecodedBitStreamParser = DecodedBitStreamParser$2;
  27677. exports.PDF417DecoderErrorCorrection = ErrorCorrection;
  27678. exports.PDF417Reader = PDF417Reader;
  27679. exports.PDF417ResultMetadata = PDF417ResultMetadata;
  27680. exports.PerspectiveTransform = PerspectiveTransform;
  27681. exports.PlanarYUVLuminanceSource = PlanarYUVLuminanceSource;
  27682. exports.QRCodeByteMatrix = ByteMatrix;
  27683. exports.QRCodeDataMask = DataMask;
  27684. exports.QRCodeDecodedBitStreamParser = DecodedBitStreamParser$1;
  27685. exports.QRCodeDecoderErrorCorrectionLevel = ErrorCorrectionLevel;
  27686. exports.QRCodeDecoderFormatInformation = FormatInformation;
  27687. exports.QRCodeEncoder = Encoder;
  27688. exports.QRCodeEncoderQRCode = QRCode;
  27689. exports.QRCodeMaskUtil = MaskUtil;
  27690. exports.QRCodeMatrixUtil = MatrixUtil;
  27691. exports.QRCodeMode = Mode$1;
  27692. exports.QRCodeReader = QRCodeReader;
  27693. exports.QRCodeVersion = Version$1;
  27694. exports.QRCodeWriter = QRCodeWriter;
  27695. exports.RGBLuminanceSource = RGBLuminanceSource;
  27696. exports.RSS14Reader = RSS14Reader;
  27697. exports.RSSExpandedReader = RSSExpandedReader;
  27698. exports.ReaderException = ReaderException;
  27699. exports.ReedSolomonDecoder = ReedSolomonDecoder;
  27700. exports.ReedSolomonEncoder = ReedSolomonEncoder;
  27701. exports.ReedSolomonException = ReedSolomonException;
  27702. exports.Result = Result;
  27703. exports.ResultMetadataType = ResultMetadataType$1;
  27704. exports.ResultPoint = ResultPoint;
  27705. exports.StringUtils = StringUtils;
  27706. exports.UnsupportedOperationException = UnsupportedOperationException;
  27707. exports.VideoInputDevice = VideoInputDevice;
  27708. exports.WhiteRectangleDetector = WhiteRectangleDetector;
  27709. exports.WriterException = WriterException;
  27710. exports.ZXingArrays = Arrays;
  27711. exports.ZXingCharset = Charset;
  27712. exports.ZXingInteger = Integer;
  27713. exports.ZXingStandardCharsets = StandardCharsets;
  27714. exports.ZXingStringBuilder = StringBuilder;
  27715. exports.ZXingStringEncoding = StringEncoding;
  27716. exports.ZXingSystem = System;
  27717. exports.createAbstractExpandedDecoder = createDecoder;
  27718. Object.defineProperty(exports, '__esModule', { value: true });
  27719. })));
  27720. //# sourceMappingURL=index.js.map