lodepng.cpp 252 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389
  1. /*
  2. LodePNG version 20191219
  3. Copyright (c) 2005-2019 Lode Vandevenne
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. */
  19. /*
  20. The manual and changelog are in the header file "lodepng.h"
  21. Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
  22. */
  23. #include "lodepng.h"
  24. #ifdef LODEPNG_COMPILE_DISK
  25. #include <limits.h> /* LONG_MAX */
  26. #include <stdio.h> /* file handling */
  27. #endif /* LODEPNG_COMPILE_DISK */
  28. #ifdef LODEPNG_COMPILE_ALLOCATORS
  29. #include <stdlib.h> /* allocations */
  30. #endif /* LODEPNG_COMPILE_ALLOCATORS */
  31. #if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
  32. #pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
  33. #pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
  34. #endif /*_MSC_VER */
  35. const char* LODEPNG_VERSION_STRING = "20191219";
  36. /*
  37. This source file is built up in the following large parts. The code sections
  38. with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
  39. -Tools for C and common code for PNG and Zlib
  40. -C Code for Zlib (huffman, deflate, ...)
  41. -C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
  42. -The C++ wrapper around all of the above
  43. */
  44. /* ////////////////////////////////////////////////////////////////////////// */
  45. /* ////////////////////////////////////////////////////////////////////////// */
  46. /* // Tools for C, and common code for PNG and Zlib. // */
  47. /* ////////////////////////////////////////////////////////////////////////// */
  48. /* ////////////////////////////////////////////////////////////////////////// */
  49. /*The malloc, realloc and free functions defined here with "lodepng_" in front
  50. of the name, so that you can easily change them to others related to your
  51. platform if needed. Everything else in the code calls these. Pass
  52. -DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
  53. #define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
  54. define them in your own project's source files without needing to change
  55. lodepng source code. Don't forget to remove "static" if you copypaste them
  56. from here.*/
  57. #ifdef LODEPNG_COMPILE_ALLOCATORS
  58. static void* lodepng_malloc(size_t size) {
  59. #ifdef LODEPNG_MAX_ALLOC
  60. if(size > LODEPNG_MAX_ALLOC) return 0;
  61. #endif
  62. return malloc(size);
  63. }
  64. static void* lodepng_realloc(void* ptr, size_t new_size) {
  65. #ifdef LODEPNG_MAX_ALLOC
  66. if(new_size > LODEPNG_MAX_ALLOC) return 0;
  67. #endif
  68. return realloc(ptr, new_size);
  69. }
  70. static void lodepng_free(void* ptr) {
  71. free(ptr);
  72. }
  73. #else /*LODEPNG_COMPILE_ALLOCATORS*/
  74. /* TODO: support giving additional void* payload to the custom allocators */
  75. void* lodepng_malloc(size_t size);
  76. void* lodepng_realloc(void* ptr, size_t new_size);
  77. void lodepng_free(void* ptr);
  78. #endif /*LODEPNG_COMPILE_ALLOCATORS*/
  79. /* convince the compiler to inline a function, for use when this measurably improves performance */
  80. /* inline is not available in C90, but use it when supported by the compiler */
  81. #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L))
  82. #define LODEPNG_INLINE inline
  83. #else
  84. #define LODEPNG_INLINE /* not available */
  85. #endif
  86. /* restrict is not available in C90, but use it when supported by the compiler */
  87. #if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\
  88. (defined(_MSC_VER) && (_MSC_VER >= 1400)) || \
  89. (defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus))
  90. #define LODEPNG_RESTRICT __restrict
  91. #else
  92. #define LODEPNG_RESTRICT /* not available */
  93. #endif
  94. /* Replacements for C library functions memcpy and strlen, to support those platforms
  95. where a full C library is not available. The compiler can recognize them and compile
  96. to something as fast. */
  97. static void lodepng_memcpy(void* LODEPNG_RESTRICT dst,
  98. const void* LODEPNG_RESTRICT src, size_t size) {
  99. size_t i;
  100. for(i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i];
  101. }
  102. /* does not check memory out of bounds, do not use on untrusted data */
  103. static size_t lodepng_strlen(const char* a) {
  104. const char* orig = a;
  105. /* avoid warning about unused function in case of disabled COMPILE... macros */
  106. (void)lodepng_strlen;
  107. while(*a) a++;
  108. return (size_t)(a - orig);
  109. }
  110. #define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))
  111. #define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))
  112. #define LODEPNG_ABS(x) ((x) < 0 ? -(x) : (x))
  113. #ifdef LODEPNG_COMPILE_DECODER
  114. /* Safely check if multiplying two integers will overflow (no undefined
  115. behavior, compiler removing the code, etc...) and output result. */
  116. static int lodepng_mulofl(size_t a, size_t b, size_t* result) {
  117. *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */
  118. return (a != 0 && *result / a != b);
  119. }
  120. /* Safely check if adding two integers will overflow (no undefined
  121. behavior, compiler removing the code, etc...) and output result. */
  122. static int lodepng_addofl(size_t a, size_t b, size_t* result) {
  123. *result = a + b; /* Unsigned addition is well defined and safe in C90 */
  124. return *result < a;
  125. }
  126. #ifdef LODEPNG_COMPILE_ZLIB
  127. /* Safely check if a + b > c, even if overflow could happen. */
  128. static int lodepng_gtofl(size_t a, size_t b, size_t c) {
  129. size_t d;
  130. if(lodepng_addofl(a, b, &d)) return 1;
  131. return d > c;
  132. }
  133. #endif /*LODEPNG_COMPILE_ZLIB*/
  134. #endif /*LODEPNG_COMPILE_DECODER*/
  135. /*
  136. Often in case of an error a value is assigned to a variable and then it breaks
  137. out of a loop (to go to the cleanup phase of a function). This macro does that.
  138. It makes the error handling code shorter and more readable.
  139. Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
  140. */
  141. #define CERROR_BREAK(errorvar, code){\
  142. errorvar = code;\
  143. break;\
  144. }
  145. /*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
  146. #define ERROR_BREAK(code) CERROR_BREAK(error, code)
  147. /*Set error var to the error code, and return it.*/
  148. #define CERROR_RETURN_ERROR(errorvar, code){\
  149. errorvar = code;\
  150. return code;\
  151. }
  152. /*Try the code, if it returns error, also return the error.*/
  153. #define CERROR_TRY_RETURN(call){\
  154. unsigned error = call;\
  155. if(error) return error;\
  156. }
  157. /*Set error var to the error code, and return from the void function.*/
  158. #define CERROR_RETURN(errorvar, code){\
  159. errorvar = code;\
  160. return;\
  161. }
  162. /*
  163. About uivector, ucvector and string:
  164. -All of them wrap dynamic arrays or text strings in a similar way.
  165. -LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
  166. -The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
  167. -They're not used in the interface, only internally in this file as static functions.
  168. -As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
  169. */
  170. #ifdef LODEPNG_COMPILE_ZLIB
  171. #ifdef LODEPNG_COMPILE_ENCODER
  172. /*dynamic vector of unsigned ints*/
  173. typedef struct uivector {
  174. unsigned* data;
  175. size_t size; /*size in number of unsigned longs*/
  176. size_t allocsize; /*allocated size in bytes*/
  177. } uivector;
  178. static void uivector_cleanup(void* p) {
  179. ((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
  180. lodepng_free(((uivector*)p)->data);
  181. ((uivector*)p)->data = NULL;
  182. }
  183. /*returns 1 if success, 0 if failure ==> nothing done*/
  184. static unsigned uivector_reserve(uivector* p, size_t allocsize) {
  185. if(allocsize > p->allocsize) {
  186. size_t newsize = (allocsize > p->allocsize * 2u) ? allocsize : ((allocsize * 3u) >> 1u);
  187. void* data = lodepng_realloc(p->data, newsize);
  188. if(data) {
  189. p->allocsize = newsize;
  190. p->data = (unsigned*)data;
  191. }
  192. else return 0; /*error: not enough memory*/
  193. }
  194. return 1;
  195. }
  196. /*returns 1 if success, 0 if failure ==> nothing done*/
  197. static unsigned uivector_resize(uivector* p, size_t size) {
  198. if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
  199. p->size = size;
  200. return 1; /*success*/
  201. }
  202. /*resize and give all new elements the value*/
  203. static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) {
  204. size_t oldsize = p->size, i;
  205. if(!uivector_resize(p, size)) return 0;
  206. for(i = oldsize; i < size; ++i) p->data[i] = value;
  207. return 1;
  208. }
  209. static void uivector_init(uivector* p) {
  210. p->data = NULL;
  211. p->size = p->allocsize = 0;
  212. }
  213. /*returns 1 if success, 0 if failure ==> nothing done*/
  214. static unsigned uivector_push_back(uivector* p, unsigned c) {
  215. if(!uivector_resize(p, p->size + 1)) return 0;
  216. p->data[p->size - 1] = c;
  217. return 1;
  218. }
  219. #endif /*LODEPNG_COMPILE_ENCODER*/
  220. #endif /*LODEPNG_COMPILE_ZLIB*/
  221. /* /////////////////////////////////////////////////////////////////////////// */
  222. /*dynamic vector of unsigned chars*/
  223. typedef struct ucvector {
  224. unsigned char* data;
  225. size_t size; /*used size*/
  226. size_t allocsize; /*allocated size*/
  227. } ucvector;
  228. /*returns 1 if success, 0 if failure ==> nothing done*/
  229. static unsigned ucvector_reserve(ucvector* p, size_t allocsize) {
  230. if(allocsize > p->allocsize) {
  231. size_t newsize = (allocsize > p->allocsize * 2u) ? allocsize : ((allocsize * 3u) >> 1u);
  232. void* data = lodepng_realloc(p->data, newsize);
  233. if(data) {
  234. p->allocsize = newsize;
  235. p->data = (unsigned char*)data;
  236. }
  237. else return 0; /*error: not enough memory*/
  238. }
  239. return 1;
  240. }
  241. /*returns 1 if success, 0 if failure ==> nothing done*/
  242. static unsigned ucvector_resize(ucvector* p, size_t size) {
  243. if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0;
  244. p->size = size;
  245. return 1; /*success*/
  246. }
  247. #ifdef LODEPNG_COMPILE_PNG
  248. static void ucvector_cleanup(void* p) {
  249. ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
  250. lodepng_free(((ucvector*)p)->data);
  251. ((ucvector*)p)->data = NULL;
  252. }
  253. static void ucvector_init(ucvector* p) {
  254. p->data = NULL;
  255. p->size = p->allocsize = 0;
  256. }
  257. #endif /*LODEPNG_COMPILE_PNG*/
  258. #ifdef LODEPNG_COMPILE_ZLIB
  259. /*you can both convert from vector to buffer&size and vice versa. If you use
  260. init_buffer to take over a buffer and size, it is not needed to use cleanup*/
  261. static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) {
  262. p->data = buffer;
  263. p->allocsize = p->size = size;
  264. }
  265. #endif /*LODEPNG_COMPILE_ZLIB*/
  266. #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
  267. /*returns 1 if success, 0 if failure ==> nothing done*/
  268. static unsigned ucvector_push_back(ucvector* p, unsigned char c) {
  269. if(!ucvector_resize(p, p->size + 1)) return 0;
  270. p->data[p->size - 1] = c;
  271. return 1;
  272. }
  273. #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
  274. /* ////////////////////////////////////////////////////////////////////////// */
  275. #ifdef LODEPNG_COMPILE_PNG
  276. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  277. /*free string pointer and set it to NULL*/
  278. static void string_cleanup(char** out) {
  279. lodepng_free(*out);
  280. *out = NULL;
  281. }
  282. /* dynamically allocates a new string with a copy of the null terminated input text */
  283. static char* alloc_string(const char* in) {
  284. size_t insize = lodepng_strlen(in);
  285. char* out = (char*)lodepng_malloc(insize + 1);
  286. if(out) {
  287. size_t i;
  288. for(i = 0; i != insize; ++i) {
  289. out[i] = in[i];
  290. }
  291. out[i] = 0;
  292. }
  293. return out;
  294. }
  295. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  296. #endif /*LODEPNG_COMPILE_PNG*/
  297. /* ////////////////////////////////////////////////////////////////////////// */
  298. #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)
  299. static unsigned lodepng_read32bitInt(const unsigned char* buffer) {
  300. return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) |
  301. ((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]);
  302. }
  303. #endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/
  304. #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
  305. /*buffer must have at least 4 allocated bytes available*/
  306. static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) {
  307. buffer[0] = (unsigned char)((value >> 24) & 0xff);
  308. buffer[1] = (unsigned char)((value >> 16) & 0xff);
  309. buffer[2] = (unsigned char)((value >> 8) & 0xff);
  310. buffer[3] = (unsigned char)((value ) & 0xff);
  311. }
  312. #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
  313. /* ////////////////////////////////////////////////////////////////////////// */
  314. /* / File IO / */
  315. /* ////////////////////////////////////////////////////////////////////////// */
  316. #ifdef LODEPNG_COMPILE_DISK
  317. /* returns negative value on error. This should be pure C compatible, so no fstat. */
  318. static long lodepng_filesize(const char* filename) {
  319. FILE* file;
  320. long size;
  321. file = fopen(filename, "rb");
  322. if(!file) return -1;
  323. if(fseek(file, 0, SEEK_END) != 0) {
  324. fclose(file);
  325. return -1;
  326. }
  327. size = ftell(file);
  328. /* It may give LONG_MAX as directory size, this is invalid for us. */
  329. if(size == LONG_MAX) size = -1;
  330. fclose(file);
  331. return size;
  332. }
  333. /* load file into buffer that already has the correct allocated size. Returns error code.*/
  334. static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) {
  335. FILE* file;
  336. size_t readsize;
  337. file = fopen(filename, "rb");
  338. if(!file) return 78;
  339. readsize = fread(out, 1, size, file);
  340. fclose(file);
  341. if (readsize != size) return 78;
  342. return 0;
  343. }
  344. unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) {
  345. long size = lodepng_filesize(filename);
  346. if (size < 0) return 78;
  347. *outsize = (size_t)size;
  348. *out = (unsigned char*)lodepng_malloc((size_t)size);
  349. if(!(*out) && size > 0) return 83; /*the above malloc failed*/
  350. return lodepng_buffer_file(*out, (size_t)size, filename);
  351. }
  352. /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
  353. unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) {
  354. FILE* file;
  355. file = fopen(filename, "wb" );
  356. if(!file) return 79;
  357. fwrite(buffer, 1, buffersize, file);
  358. fclose(file);
  359. return 0;
  360. }
  361. #endif /*LODEPNG_COMPILE_DISK*/
  362. /* ////////////////////////////////////////////////////////////////////////// */
  363. /* ////////////////////////////////////////////////////////////////////////// */
  364. /* // End of common code and tools. Begin of Zlib related code. // */
  365. /* ////////////////////////////////////////////////////////////////////////// */
  366. /* ////////////////////////////////////////////////////////////////////////// */
  367. #ifdef LODEPNG_COMPILE_ZLIB
  368. #ifdef LODEPNG_COMPILE_ENCODER
  369. typedef struct {
  370. ucvector* data;
  371. size_t bp;
  372. } LodePNGBitWriter;
  373. void LodePNGBitWriter_init(LodePNGBitWriter* writer, ucvector* data) {
  374. writer->data = data;
  375. writer->bp = 0;
  376. }
  377. /*TODO: this ignores potential out of memory errors*/
  378. #define WRITEBIT(/*size_t**/ writer, /*unsigned char*/ bit){\
  379. /* append new byte */\
  380. if(((writer->bp) & 7u) == 0) ucvector_push_back(writer->data, (unsigned char)0);\
  381. (writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\
  382. ++writer->bp;\
  383. }
  384. /* LSB of value is written first, and LSB of bytes is used first */
  385. static void writeBits(LodePNGBitWriter* writer, unsigned value, size_t nbits) {
  386. if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */
  387. WRITEBIT(writer, value);
  388. } else {
  389. /* TODO: increase output size nly once here rather than in each WRITEBIT */
  390. size_t i;
  391. for(i = 0; i != nbits; ++i) {
  392. WRITEBIT(writer, (unsigned char)((value >> i) & 1));
  393. }
  394. }
  395. }
  396. /* This one is to use for adding huffman symbol, the value bits are written MSB first */
  397. static void writeBitsReversed(LodePNGBitWriter* writer, unsigned value, size_t nbits) {
  398. size_t i;
  399. for(i = 0; i != nbits; ++i) {
  400. /* TODO: increase output size only once here rather than in each WRITEBIT */
  401. WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u));
  402. }
  403. }
  404. #endif /*LODEPNG_COMPILE_ENCODER*/
  405. #ifdef LODEPNG_COMPILE_DECODER
  406. typedef struct {
  407. const unsigned char* data;
  408. size_t size; /*size of data in bytes*/
  409. size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/
  410. size_t bp;
  411. unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/
  412. } LodePNGBitReader;
  413. /* data size argument is in bytes. Returns error if size too large causing overflow */
  414. static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size) {
  415. size_t temp;
  416. reader->data = data;
  417. reader->size = size;
  418. /* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB) */
  419. if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105;
  420. /*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and
  421. trying to ensure 32 more bits*/
  422. if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105;
  423. reader->bp = 0;
  424. reader->buffer = 0;
  425. return 0; /*ok*/
  426. }
  427. /*
  428. ensureBits functions:
  429. Ensures the reader can at least read nbits bits in one or more readBits calls,
  430. safely even if not enough bits are available.
  431. Returns 1 if there are enough bits available, 0 if not.
  432. */
  433. /*See ensureBits documentation above. This one ensures exactly 1 bit */
  434. /*static unsigned ensureBits1(LodePNGBitReader* reader) {
  435. if(reader->bp >= reader->bitsize) return 0;
  436. reader->buffer = (unsigned)reader->data[reader->bp >> 3u] >> (reader->bp & 7u);
  437. return 1;
  438. }*/
  439. /*See ensureBits documentation above. This one ensures up to 9 bits */
  440. static unsigned ensureBits9(LodePNGBitReader* reader, size_t nbits) {
  441. size_t start = reader->bp >> 3u;
  442. size_t size = reader->size;
  443. if(start + 1u < size) {
  444. reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u);
  445. reader->buffer >>= (reader->bp & 7u);
  446. return 1;
  447. } else {
  448. reader->buffer = 0;
  449. if(start + 0u < size) reader->buffer |= reader->data[start + 0];
  450. reader->buffer >>= (reader->bp & 7u);
  451. return reader->bp + nbits <= reader->bitsize;
  452. }
  453. }
  454. /*See ensureBits documentation above. This one ensures up to 17 bits */
  455. static unsigned ensureBits17(LodePNGBitReader* reader, size_t nbits) {
  456. size_t start = reader->bp >> 3u;
  457. size_t size = reader->size;
  458. if(start + 2u < size) {
  459. reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
  460. ((unsigned)reader->data[start + 2] << 16u);
  461. reader->buffer >>= (reader->bp & 7u);
  462. return 1;
  463. } else {
  464. reader->buffer = 0;
  465. if(start + 0u < size) reader->buffer |= reader->data[start + 0];
  466. if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
  467. reader->buffer >>= (reader->bp & 7u);
  468. return reader->bp + nbits <= reader->bitsize;
  469. }
  470. }
  471. /*See ensureBits documentation above. This one ensures up to 25 bits */
  472. static LODEPNG_INLINE unsigned ensureBits25(LodePNGBitReader* reader, size_t nbits) {
  473. size_t start = reader->bp >> 3u;
  474. size_t size = reader->size;
  475. if(start + 3u < size) {
  476. reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
  477. ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
  478. reader->buffer >>= (reader->bp & 7u);
  479. return 1;
  480. } else {
  481. reader->buffer = 0;
  482. if(start + 0u < size) reader->buffer |= reader->data[start + 0];
  483. if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
  484. if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
  485. reader->buffer >>= (reader->bp & 7u);
  486. return reader->bp + nbits <= reader->bitsize;
  487. }
  488. }
  489. /*See ensureBits documentation above. This one ensures up to 32 bits */
  490. static LODEPNG_INLINE unsigned ensureBits32(LodePNGBitReader* reader, size_t nbits) {
  491. size_t start = reader->bp >> 3u;
  492. size_t size = reader->size;
  493. if(start + 4u < size) {
  494. reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) |
  495. ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u);
  496. reader->buffer >>= (reader->bp & 7u);
  497. reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u)));
  498. return 1;
  499. } else {
  500. reader->buffer = 0;
  501. if(start + 0u < size) reader->buffer |= reader->data[start + 0];
  502. if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u);
  503. if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u);
  504. if(start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u);
  505. reader->buffer >>= (reader->bp & 7u);
  506. return reader->bp + nbits <= reader->bitsize;
  507. }
  508. }
  509. /* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */
  510. static unsigned peekBits(LodePNGBitReader* reader, size_t nbits) {
  511. /* The shift allows nbits to be only up to 31. */
  512. return reader->buffer & ((1u << nbits) - 1u);
  513. }
  514. /* Must have enough bits available with ensureBits */
  515. static void advanceBits(LodePNGBitReader* reader, size_t nbits) {
  516. reader->buffer >>= nbits;
  517. reader->bp += nbits;
  518. }
  519. /* Must have enough bits available with ensureBits */
  520. static unsigned readBits(LodePNGBitReader* reader, size_t nbits) {
  521. unsigned result = peekBits(reader, nbits);
  522. advanceBits(reader, nbits);
  523. return result;
  524. }
  525. /* Public for testing only. steps and result must have numsteps values. */
  526. unsigned lode_png_test_bitreader(const unsigned char* data, size_t size,
  527. size_t numsteps, const size_t* steps, unsigned* result) {
  528. size_t i;
  529. LodePNGBitReader reader;
  530. LodePNGBitReader_init(&reader, data, size);
  531. for(i = 0; i < numsteps; i++) {
  532. size_t step = steps[i];
  533. unsigned ok;
  534. if(step > 25) ok = ensureBits32(&reader, step);
  535. else if(step > 17) ok = ensureBits25(&reader, step);
  536. else if(step > 9) ok = ensureBits17(&reader, step);
  537. else ok = ensureBits9(&reader, step);
  538. if(!ok) return 0;
  539. result[i] = readBits(&reader, step);
  540. }
  541. return 1;
  542. }
  543. #endif /*LODEPNG_COMPILE_DECODER*/
  544. static unsigned reverseBits(unsigned bits, unsigned num) {
  545. /*TODO: implement faster lookup table based version when needed*/
  546. unsigned i, result = 0;
  547. for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i;
  548. return result;
  549. }
  550. /* ////////////////////////////////////////////////////////////////////////// */
  551. /* / Deflate - Huffman / */
  552. /* ////////////////////////////////////////////////////////////////////////// */
  553. #define FIRST_LENGTH_CODE_INDEX 257
  554. #define LAST_LENGTH_CODE_INDEX 285
  555. /*256 literals, the end code, some length codes, and 2 unused codes*/
  556. #define NUM_DEFLATE_CODE_SYMBOLS 288
  557. /*the distance codes have their own symbols, 30 used, 2 unused*/
  558. #define NUM_DISTANCE_SYMBOLS 32
  559. /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
  560. #define NUM_CODE_LENGTH_CODES 19
  561. /*the base lengths represented by codes 257-285*/
  562. static const unsigned LENGTHBASE[29]
  563. = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
  564. 67, 83, 99, 115, 131, 163, 195, 227, 258};
  565. /*the extra bits used by codes 257-285 (added to base length)*/
  566. static const unsigned LENGTHEXTRA[29]
  567. = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
  568. 4, 4, 4, 4, 5, 5, 5, 5, 0};
  569. /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
  570. static const unsigned DISTANCEBASE[30]
  571. = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
  572. 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
  573. /*the extra bits of backwards distances (added to base)*/
  574. static const unsigned DISTANCEEXTRA[30]
  575. = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
  576. 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
  577. /*the order in which "code length alphabet code lengths" are stored, out of this
  578. the huffman tree of the dynamic huffman tree lengths is generated*/
  579. static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
  580. = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  581. /* ////////////////////////////////////////////////////////////////////////// */
  582. /*
  583. Huffman tree struct, containing multiple representations of the tree
  584. */
  585. typedef struct HuffmanTree {
  586. unsigned* codes; /*the huffman codes (bit patterns representing the symbols)*/
  587. unsigned* lengths; /*the lengths of the huffman codes*/
  588. unsigned maxbitlen; /*maximum number of bits a single code can get*/
  589. unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
  590. /* for reading only */
  591. unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/
  592. unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/
  593. } HuffmanTree;
  594. static void HuffmanTree_init(HuffmanTree* tree) {
  595. tree->codes = 0;
  596. tree->lengths = 0;
  597. tree->table_len = 0;
  598. tree->table_value = 0;
  599. }
  600. static void HuffmanTree_cleanup(HuffmanTree* tree) {
  601. lodepng_free(tree->codes);
  602. lodepng_free(tree->lengths);
  603. lodepng_free(tree->table_len);
  604. lodepng_free(tree->table_value);
  605. }
  606. /* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/
  607. /* values 8u and 9u work the fastest */
  608. #define FIRSTBITS 9u
  609. /* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination,
  610. which is possible in case of only 0 or 1 present symbols. */
  611. #define INVALIDSYMBOL 65535u
  612. /* make table for huffman decoding */
  613. static unsigned HuffmanTree_makeTable(HuffmanTree* tree) {
  614. static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/
  615. static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u;
  616. size_t i, numpresent, pointer, size; /*total table size*/
  617. unsigned* maxlens = (unsigned*)lodepng_malloc(headsize * sizeof(unsigned));
  618. if(!maxlens) return 83; /*alloc fail*/
  619. /* compute maxlens: max total bit length of symbols sharing prefix in the first table*/
  620. for(i = 0; i < headsize; ++i) maxlens[i] = 0;
  621. for(i = 0; i < tree->numcodes; i++) {
  622. unsigned symbol = tree->codes[i];
  623. unsigned l = tree->lengths[i];
  624. unsigned index;
  625. if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/
  626. /*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/
  627. index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS);
  628. maxlens[index] = LODEPNG_MAX(maxlens[index], l);
  629. }
  630. /* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */
  631. size = headsize;
  632. for(i = 0; i < headsize; ++i) {
  633. unsigned l = maxlens[i];
  634. if(l > FIRSTBITS) size += (1u << (l - FIRSTBITS));
  635. }
  636. tree->table_len = (unsigned char*)lodepng_malloc(size * sizeof(*tree->table_len));
  637. tree->table_value = (unsigned short*)lodepng_malloc(size * sizeof(*tree->table_value));
  638. if(!tree->table_len || !tree->table_value) {
  639. lodepng_free(maxlens);
  640. /* freeing tree->table values is done at a higher scope */
  641. return 83; /*alloc fail*/
  642. }
  643. /*initialize with an invalid length to indicate unused entries*/
  644. for(i = 0; i < size; ++i) tree->table_len[i] = 16;
  645. /*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/
  646. pointer = headsize;
  647. for(i = 0; i < headsize; ++i) {
  648. unsigned l = maxlens[i];
  649. if(l <= FIRSTBITS) continue;
  650. tree->table_len[i] = l;
  651. tree->table_value[i] = pointer;
  652. pointer += (1u << (l - FIRSTBITS));
  653. }
  654. lodepng_free(maxlens);
  655. /*fill in the first table for short symbols, or secondary table for long symbols*/
  656. numpresent = 0;
  657. for(i = 0; i < tree->numcodes; ++i) {
  658. unsigned l = tree->lengths[i];
  659. unsigned symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/
  660. /*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/
  661. unsigned reverse = reverseBits(symbol, l);
  662. if(l == 0) continue;
  663. numpresent++;
  664. if(l <= FIRSTBITS) {
  665. /*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/
  666. unsigned num = 1u << (FIRSTBITS - l);
  667. unsigned j;
  668. for(j = 0; j < num; ++j) {
  669. /*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/
  670. unsigned index = reverse | (j << l);
  671. if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
  672. tree->table_len[index] = l;
  673. tree->table_value[index] = i;
  674. }
  675. } else {
  676. /*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/
  677. /*the FIRSTBITS MSBs of the symbol are the first table index*/
  678. unsigned index = reverse & mask;
  679. unsigned maxlen = tree->table_len[index];
  680. /*log2 of secondary table length, should be >= l - FIRSTBITS*/
  681. unsigned tablelen = maxlen - FIRSTBITS;
  682. unsigned start = tree->table_value[index]; /*starting index in secondary table*/
  683. unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/
  684. unsigned j;
  685. if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/
  686. for(j = 0; j < num; ++j) {
  687. unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */
  688. unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS)));
  689. tree->table_len[index2] = l;
  690. tree->table_value[index2] = i;
  691. }
  692. }
  693. }
  694. if(numpresent < 2) {
  695. /* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits,
  696. but deflate uses 1 bit instead. In case of 0 symbols, no symbols can
  697. appear at all, but such huffman tree could still exist (e.g. if distance
  698. codes are never used). In both cases, not all symbols of the table will be
  699. filled in. Fill them in with an invalid symbol value so returning them from
  700. huffmanDecodeSymbol will cause error. */
  701. for(i = 0; i < size; ++i) {
  702. if(tree->table_len[i] == 16) {
  703. /* As length, use a value smaller than FIRSTBITS for the head table,
  704. and a value larger than FIRSTBITS for the secondary table, to ensure
  705. valid behavior for advanceBits when reading this symbol. */
  706. tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1);
  707. tree->table_value[i] = INVALIDSYMBOL;
  708. }
  709. }
  710. } else {
  711. /* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
  712. If that is not the case (due to too long length codes), the table will not
  713. have been fully used, and this is an error (not all bit combinations can be
  714. decoded): an oversubscribed huffman tree, indicated by error 55. */
  715. for(i = 0; i < size; ++i) {
  716. if(tree->table_len[i] == 16) return 55;
  717. }
  718. }
  719. return 0;
  720. }
  721. /*
  722. Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
  723. numcodes, lengths and maxbitlen must already be filled in correctly. return
  724. value is error.
  725. */
  726. static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) {
  727. unsigned* blcount;
  728. unsigned* nextcode;
  729. unsigned error = 0;
  730. unsigned bits, n;
  731. tree->codes = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
  732. blcount = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
  733. nextcode = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned));
  734. if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/
  735. if(!error) {
  736. for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0;
  737. /*step 1: count number of instances of each code length*/
  738. for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]];
  739. /*step 2: generate the nextcode values*/
  740. for(bits = 1; bits <= tree->maxbitlen; ++bits) {
  741. nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u;
  742. }
  743. /*step 3: generate all the codes*/
  744. for(n = 0; n != tree->numcodes; ++n) {
  745. if(tree->lengths[n] != 0) {
  746. tree->codes[n] = nextcode[tree->lengths[n]]++;
  747. /*remove superfluous bits from the code*/
  748. tree->codes[n] &= ((1u << tree->lengths[n]) - 1u);
  749. }
  750. }
  751. }
  752. lodepng_free(blcount);
  753. lodepng_free(nextcode);
  754. if(!error) error = HuffmanTree_makeTable(tree);
  755. return error;
  756. }
  757. /*
  758. given the code lengths (as stored in the PNG file), generate the tree as defined
  759. by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
  760. return value is error.
  761. */
  762. static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
  763. size_t numcodes, unsigned maxbitlen) {
  764. unsigned i;
  765. tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
  766. if(!tree->lengths) return 83; /*alloc fail*/
  767. for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
  768. tree->numcodes = (unsigned)numcodes; /*number of symbols*/
  769. tree->maxbitlen = maxbitlen;
  770. return HuffmanTree_makeFromLengths2(tree);
  771. }
  772. #ifdef LODEPNG_COMPILE_ENCODER
  773. /*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
  774. Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
  775. /*chain node for boundary package merge*/
  776. typedef struct BPMNode {
  777. int weight; /*the sum of all weights in this chain*/
  778. unsigned index; /*index of this leaf node (called "count" in the paper)*/
  779. struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
  780. int in_use;
  781. } BPMNode;
  782. /*lists of chains*/
  783. typedef struct BPMLists {
  784. /*memory pool*/
  785. unsigned memsize;
  786. BPMNode* memory;
  787. unsigned numfree;
  788. unsigned nextfree;
  789. BPMNode** freelist;
  790. /*two heads of lookahead chains per list*/
  791. unsigned listsize;
  792. BPMNode** chains0;
  793. BPMNode** chains1;
  794. } BPMLists;
  795. /*creates a new chain node with the given parameters, from the memory in the lists */
  796. static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) {
  797. unsigned i;
  798. BPMNode* result;
  799. /*memory full, so garbage collect*/
  800. if(lists->nextfree >= lists->numfree) {
  801. /*mark only those that are in use*/
  802. for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
  803. for(i = 0; i != lists->listsize; ++i) {
  804. BPMNode* node;
  805. for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
  806. for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
  807. }
  808. /*collect those that are free*/
  809. lists->numfree = 0;
  810. for(i = 0; i != lists->memsize; ++i) {
  811. if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
  812. }
  813. lists->nextfree = 0;
  814. }
  815. result = lists->freelist[lists->nextfree++];
  816. result->weight = weight;
  817. result->index = index;
  818. result->tail = tail;
  819. return result;
  820. }
  821. /*sort the leaves with stable mergesort*/
  822. static void bpmnode_sort(BPMNode* leaves, size_t num) {
  823. BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num);
  824. size_t width, counter = 0;
  825. for(width = 1; width < num; width *= 2) {
  826. BPMNode* a = (counter & 1) ? mem : leaves;
  827. BPMNode* b = (counter & 1) ? leaves : mem;
  828. size_t p;
  829. for(p = 0; p < num; p += 2 * width) {
  830. size_t q = (p + width > num) ? num : (p + width);
  831. size_t r = (p + 2 * width > num) ? num : (p + 2 * width);
  832. size_t i = p, j = q, k;
  833. for(k = p; k < r; k++) {
  834. if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];
  835. else b[k] = a[j++];
  836. }
  837. }
  838. counter++;
  839. }
  840. if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num);
  841. lodepng_free(mem);
  842. }
  843. /*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
  844. static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) {
  845. unsigned lastindex = lists->chains1[c]->index;
  846. if(c == 0) {
  847. if(lastindex >= numpresent) return;
  848. lists->chains0[c] = lists->chains1[c];
  849. lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
  850. } else {
  851. /*sum of the weights of the head nodes of the previous lookahead chains.*/
  852. int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
  853. lists->chains0[c] = lists->chains1[c];
  854. if(lastindex < numpresent && sum > leaves[lastindex].weight) {
  855. lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
  856. return;
  857. }
  858. lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
  859. /*in the end we are only interested in the chain of the last list, so no
  860. need to recurse if we're at the last one (this gives measurable speedup)*/
  861. if(num + 1 < (int)(2 * numpresent - 2)) {
  862. boundaryPM(lists, leaves, numpresent, c - 1, num);
  863. boundaryPM(lists, leaves, numpresent, c - 1, num);
  864. }
  865. }
  866. }
  867. unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
  868. size_t numcodes, unsigned maxbitlen) {
  869. unsigned error = 0;
  870. unsigned i;
  871. size_t numpresent = 0; /*number of symbols with non-zero frequency*/
  872. BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
  873. if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
  874. if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/
  875. leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
  876. if(!leaves) return 83; /*alloc fail*/
  877. for(i = 0; i != numcodes; ++i) {
  878. if(frequencies[i] > 0) {
  879. leaves[numpresent].weight = (int)frequencies[i];
  880. leaves[numpresent].index = i;
  881. ++numpresent;
  882. }
  883. }
  884. for(i = 0; i != numcodes; ++i) lengths[i] = 0;
  885. /*ensure at least two present symbols. There should be at least one symbol
  886. according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
  887. make these work as well ensure there are at least two symbols. The
  888. Package-Merge code below also doesn't work correctly if there's only one
  889. symbol, it'd give it the theoretical 0 bits but in practice zlib wants 1 bit*/
  890. if(numpresent == 0) {
  891. lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
  892. } else if(numpresent == 1) {
  893. lengths[leaves[0].index] = 1;
  894. lengths[leaves[0].index == 0 ? 1 : 0] = 1;
  895. } else {
  896. BPMLists lists;
  897. BPMNode* node;
  898. bpmnode_sort(leaves, numpresent);
  899. lists.listsize = maxbitlen;
  900. lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
  901. lists.nextfree = 0;
  902. lists.numfree = lists.memsize;
  903. lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
  904. lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
  905. lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
  906. lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
  907. if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
  908. if(!error) {
  909. for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
  910. bpmnode_create(&lists, leaves[0].weight, 1, 0);
  911. bpmnode_create(&lists, leaves[1].weight, 2, 0);
  912. for(i = 0; i != lists.listsize; ++i) {
  913. lists.chains0[i] = &lists.memory[0];
  914. lists.chains1[i] = &lists.memory[1];
  915. }
  916. /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
  917. for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
  918. for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) {
  919. for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
  920. }
  921. }
  922. lodepng_free(lists.memory);
  923. lodepng_free(lists.freelist);
  924. lodepng_free(lists.chains0);
  925. lodepng_free(lists.chains1);
  926. }
  927. lodepng_free(leaves);
  928. return error;
  929. }
  930. /*Create the Huffman tree given the symbol frequencies*/
  931. static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
  932. size_t mincodes, size_t numcodes, unsigned maxbitlen) {
  933. size_t i;
  934. unsigned error = 0;
  935. while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
  936. tree->maxbitlen = maxbitlen;
  937. tree->numcodes = (unsigned)numcodes; /*number of symbols*/
  938. tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
  939. if(!tree->lengths) return 83; /*alloc fail*/
  940. /*initialize all lengths to 0*/
  941. for(i = 0; i < numcodes; i++) tree->lengths[i] = 0;
  942. error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
  943. if(!error) error = HuffmanTree_makeFromLengths2(tree);
  944. return error;
  945. }
  946. static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) {
  947. return tree->codes[index];
  948. }
  949. static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) {
  950. return tree->lengths[index];
  951. }
  952. #endif /*LODEPNG_COMPILE_ENCODER*/
  953. /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
  954. static unsigned generateFixedLitLenTree(HuffmanTree* tree) {
  955. unsigned i, error = 0;
  956. unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
  957. if(!bitlen) return 83; /*alloc fail*/
  958. /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
  959. for(i = 0; i <= 143; ++i) bitlen[i] = 8;
  960. for(i = 144; i <= 255; ++i) bitlen[i] = 9;
  961. for(i = 256; i <= 279; ++i) bitlen[i] = 7;
  962. for(i = 280; i <= 287; ++i) bitlen[i] = 8;
  963. error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
  964. lodepng_free(bitlen);
  965. return error;
  966. }
  967. /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
  968. static unsigned generateFixedDistanceTree(HuffmanTree* tree) {
  969. unsigned i, error = 0;
  970. unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
  971. if(!bitlen) return 83; /*alloc fail*/
  972. /*there are 32 distance codes, but 30-31 are unused*/
  973. for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
  974. error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
  975. lodepng_free(bitlen);
  976. return error;
  977. }
  978. #ifdef LODEPNG_COMPILE_DECODER
  979. /*
  980. returns the code. The bit reader must already have been ensured at least 15 bits
  981. */
  982. static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree) {
  983. unsigned short code = peekBits(reader, FIRSTBITS);
  984. unsigned short l = codetree->table_len[code];
  985. unsigned short value = codetree->table_value[code];
  986. if(l <= FIRSTBITS) {
  987. advanceBits(reader, l);
  988. return value;
  989. } else {
  990. unsigned index2;
  991. advanceBits(reader, FIRSTBITS);
  992. index2 = value + peekBits(reader, l - FIRSTBITS);
  993. advanceBits(reader, codetree->table_len[index2] - FIRSTBITS);
  994. return codetree->table_value[index2];
  995. }
  996. }
  997. #endif /*LODEPNG_COMPILE_DECODER*/
  998. #ifdef LODEPNG_COMPILE_DECODER
  999. /* ////////////////////////////////////////////////////////////////////////// */
  1000. /* / Inflator (Decompressor) / */
  1001. /* ////////////////////////////////////////////////////////////////////////// */
  1002. /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
  1003. static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) {
  1004. /*TODO: check for out of memory errors*/
  1005. generateFixedLitLenTree(tree_ll);
  1006. generateFixedDistanceTree(tree_d);
  1007. }
  1008. /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
  1009. static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
  1010. LodePNGBitReader* reader) {
  1011. /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
  1012. unsigned error = 0;
  1013. unsigned n, HLIT, HDIST, HCLEN, i;
  1014. /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
  1015. unsigned* bitlen_ll = 0; /*lit,len code lengths*/
  1016. unsigned* bitlen_d = 0; /*dist code lengths*/
  1017. /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
  1018. unsigned* bitlen_cl = 0;
  1019. HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
  1020. if(!ensureBits17(reader, 14)) return 49; /*error: the bit pointer is or will go past the memory*/
  1021. /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
  1022. HLIT = readBits(reader, 5) + 257;
  1023. /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
  1024. HDIST = readBits(reader, 5) + 1;
  1025. /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
  1026. HCLEN = readBits(reader, 4) + 4;
  1027. bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
  1028. if(!bitlen_cl) return 83 /*alloc fail*/;
  1029. HuffmanTree_init(&tree_cl);
  1030. while(!error) {
  1031. /*read the code length codes out of 3 * (amount of code length codes) bits*/
  1032. if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) {
  1033. ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/
  1034. }
  1035. for(i = 0; i != HCLEN; ++i) {
  1036. ensureBits9(reader, 3); /*out of bounds already checked above */
  1037. bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3);
  1038. }
  1039. for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) {
  1040. bitlen_cl[CLCL_ORDER[i]] = 0;
  1041. }
  1042. error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
  1043. if(error) break;
  1044. /*now we can use this tree to read the lengths for the tree that this function will return*/
  1045. bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
  1046. bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
  1047. if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
  1048. for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
  1049. for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
  1050. /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
  1051. i = 0;
  1052. while(i < HLIT + HDIST) {
  1053. unsigned code;
  1054. ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/
  1055. code = huffmanDecodeSymbol(reader, &tree_cl);
  1056. if(code <= 15) /*a length code*/ {
  1057. if(i < HLIT) bitlen_ll[i] = code;
  1058. else bitlen_d[i - HLIT] = code;
  1059. ++i;
  1060. } else if(code == 16) /*repeat previous*/ {
  1061. unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
  1062. unsigned value; /*set value to the previous code*/
  1063. if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
  1064. replength += readBits(reader, 2);
  1065. if(i < HLIT + 1) value = bitlen_ll[i - 1];
  1066. else value = bitlen_d[i - HLIT - 1];
  1067. /*repeat this value in the next lengths*/
  1068. for(n = 0; n < replength; ++n) {
  1069. if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
  1070. if(i < HLIT) bitlen_ll[i] = value;
  1071. else bitlen_d[i - HLIT] = value;
  1072. ++i;
  1073. }
  1074. } else if(code == 17) /*repeat "0" 3-10 times*/ {
  1075. unsigned replength = 3; /*read in the bits that indicate repeat length*/
  1076. replength += readBits(reader, 3);
  1077. /*repeat this value in the next lengths*/
  1078. for(n = 0; n < replength; ++n) {
  1079. if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
  1080. if(i < HLIT) bitlen_ll[i] = 0;
  1081. else bitlen_d[i - HLIT] = 0;
  1082. ++i;
  1083. }
  1084. } else if(code == 18) /*repeat "0" 11-138 times*/ {
  1085. unsigned replength = 11; /*read in the bits that indicate repeat length*/
  1086. replength += readBits(reader, 7);
  1087. /*repeat this value in the next lengths*/
  1088. for(n = 0; n < replength; ++n) {
  1089. if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
  1090. if(i < HLIT) bitlen_ll[i] = 0;
  1091. else bitlen_d[i - HLIT] = 0;
  1092. ++i;
  1093. }
  1094. } else /*if(code == INVALIDSYMBOL)*/ {
  1095. ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
  1096. }
  1097. /*check if any of the ensureBits above went out of bounds*/
  1098. if(reader->bp > reader->bitsize) {
  1099. /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
  1100. (10=no endcode, 11=wrong jump outside of tree)*/
  1101. /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
  1102. ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
  1103. }
  1104. }
  1105. if(error) break;
  1106. if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
  1107. /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
  1108. error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
  1109. if(error) break;
  1110. error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
  1111. break; /*end of error-while*/
  1112. }
  1113. lodepng_free(bitlen_cl);
  1114. lodepng_free(bitlen_ll);
  1115. lodepng_free(bitlen_d);
  1116. HuffmanTree_cleanup(&tree_cl);
  1117. return error;
  1118. }
  1119. /*inflate a block with dynamic of fixed Huffman tree. btype must be 1 or 2.*/
  1120. static unsigned inflateHuffmanBlock(ucvector* out, size_t* pos, LodePNGBitReader* reader,
  1121. unsigned btype) {
  1122. unsigned error = 0;
  1123. HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
  1124. HuffmanTree tree_d; /*the huffman tree for distance codes*/
  1125. HuffmanTree_init(&tree_ll);
  1126. HuffmanTree_init(&tree_d);
  1127. if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
  1128. else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader);
  1129. while(!error) /*decode all symbols until end reached, breaks at end code*/ {
  1130. /*code_ll is literal, length or end code*/
  1131. unsigned code_ll;
  1132. ensureBits25(reader, 20); /* up to 15 for the huffman symbol, up to 5 for the length extra bits */
  1133. code_ll = huffmanDecodeSymbol(reader, &tree_ll);
  1134. if(code_ll <= 255) /*literal symbol*/ {
  1135. /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/
  1136. if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/);
  1137. out->data[*pos] = (unsigned char)code_ll;
  1138. ++(*pos);
  1139. } else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ {
  1140. unsigned code_d, distance;
  1141. unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
  1142. size_t start, backward, length;
  1143. /*part 1: get length base*/
  1144. length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
  1145. /*part 2: get extra bits and add the value of that to length*/
  1146. numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
  1147. if(numextrabits_l != 0) {
  1148. /* bits already ensured above */
  1149. length += readBits(reader, numextrabits_l);
  1150. }
  1151. /*part 3: get distance code*/
  1152. ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */
  1153. code_d = huffmanDecodeSymbol(reader, &tree_d);
  1154. if(code_d > 29) {
  1155. if(code_d <= 31) {
  1156. ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/
  1157. } else /* if(code_d == INVALIDSYMBOL) */{
  1158. ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
  1159. }
  1160. }
  1161. distance = DISTANCEBASE[code_d];
  1162. /*part 4: get extra bits from distance*/
  1163. numextrabits_d = DISTANCEEXTRA[code_d];
  1164. if(numextrabits_d != 0) {
  1165. /* bits already ensured above */
  1166. distance += readBits(reader, numextrabits_d);
  1167. }
  1168. /*part 5: fill in all the out[n] values based on the length and dist*/
  1169. start = (*pos);
  1170. if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
  1171. backward = start - distance;
  1172. if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
  1173. if (distance < length) {
  1174. size_t forward;
  1175. lodepng_memcpy(out->data + *pos, out->data + backward, distance);
  1176. *pos += distance;
  1177. for(forward = distance; forward < length; ++forward) {
  1178. out->data[(*pos)++] = out->data[backward++];
  1179. }
  1180. } else {
  1181. lodepng_memcpy(out->data + *pos, out->data + backward, length);
  1182. *pos += length;
  1183. }
  1184. } else if(code_ll == 256) {
  1185. break; /*end code, break the loop*/
  1186. } else /*if(code_ll == INVALIDSYMBOL)*/ {
  1187. ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/
  1188. }
  1189. /*check if any of the ensureBits above went out of bounds*/
  1190. if(reader->bp > reader->bitsize) {
  1191. /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
  1192. (10=no endcode, 11=wrong jump outside of tree)*/
  1193. /* TODO: revise error codes 10,11,50: the above comment is no longer valid */
  1194. ERROR_BREAK(51); /*error, bit pointer jumps past memory*/
  1195. }
  1196. }
  1197. HuffmanTree_cleanup(&tree_ll);
  1198. HuffmanTree_cleanup(&tree_d);
  1199. return error;
  1200. }
  1201. static unsigned inflateNoCompression(ucvector* out, size_t* pos,
  1202. LodePNGBitReader* reader, const LodePNGDecompressSettings* settings) {
  1203. size_t bytepos;
  1204. size_t size = reader->size;
  1205. unsigned LEN, NLEN, error = 0;
  1206. /*go to first boundary of byte*/
  1207. bytepos = (reader->bp + 7u) >> 3u;
  1208. /*read LEN (2 bytes) and NLEN (2 bytes)*/
  1209. if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/
  1210. LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;
  1211. NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2;
  1212. /*check if 16-bit NLEN is really the one's complement of LEN*/
  1213. if(!settings->ignore_nlen && LEN + NLEN != 65535) {
  1214. return 21; /*error: NLEN is not one's complement of LEN*/
  1215. }
  1216. if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
  1217. /*read the literal data: LEN bytes are now stored in the out buffer*/
  1218. if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/
  1219. lodepng_memcpy(out->data + *pos, reader->data + bytepos, LEN);
  1220. *pos += LEN;
  1221. bytepos += LEN;
  1222. reader->bp = bytepos << 3u;
  1223. return error;
  1224. }
  1225. static unsigned lodepng_inflatev(ucvector* out,
  1226. const unsigned char* in, size_t insize,
  1227. const LodePNGDecompressSettings* settings) {
  1228. unsigned BFINAL = 0;
  1229. size_t pos = 0; /*byte position in the out buffer*/
  1230. LodePNGBitReader reader;
  1231. unsigned error = LodePNGBitReader_init(&reader, in, insize);
  1232. if(error) return error;
  1233. while(!BFINAL) {
  1234. unsigned BTYPE;
  1235. if(!ensureBits9(&reader, 3)) return 52; /*error, bit pointer will jump past memory*/
  1236. BFINAL = readBits(&reader, 1);
  1237. BTYPE = readBits(&reader, 2);
  1238. if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
  1239. else if(BTYPE == 0) error = inflateNoCompression(out, &pos, &reader, settings); /*no compression*/
  1240. else error = inflateHuffmanBlock(out, &pos, &reader, BTYPE); /*compression, BTYPE 01 or 10*/
  1241. if(error) return error;
  1242. }
  1243. return error;
  1244. }
  1245. unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
  1246. const unsigned char* in, size_t insize,
  1247. const LodePNGDecompressSettings* settings) {
  1248. unsigned error;
  1249. ucvector v;
  1250. ucvector_init_buffer(&v, *out, *outsize);
  1251. error = lodepng_inflatev(&v, in, insize, settings);
  1252. *out = v.data;
  1253. *outsize = v.size;
  1254. return error;
  1255. }
  1256. static unsigned inflate(unsigned char** out, size_t* outsize,
  1257. const unsigned char* in, size_t insize,
  1258. const LodePNGDecompressSettings* settings) {
  1259. if(settings->custom_inflate) {
  1260. return settings->custom_inflate(out, outsize, in, insize, settings);
  1261. } else {
  1262. return lodepng_inflate(out, outsize, in, insize, settings);
  1263. }
  1264. }
  1265. #endif /*LODEPNG_COMPILE_DECODER*/
  1266. #ifdef LODEPNG_COMPILE_ENCODER
  1267. /* ////////////////////////////////////////////////////////////////////////// */
  1268. /* / Deflator (Compressor) / */
  1269. /* ////////////////////////////////////////////////////////////////////////// */
  1270. static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
  1271. /*search the index in the array, that has the largest value smaller than or equal to the given value,
  1272. given array must be sorted (if no value is smaller, it returns the size of the given array)*/
  1273. static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) {
  1274. /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/
  1275. size_t left = 1;
  1276. size_t right = array_size - 1;
  1277. while(left <= right) {
  1278. size_t mid = (left + right) >> 1;
  1279. if (array[mid] >= value) right = mid - 1;
  1280. else left = mid + 1;
  1281. }
  1282. if(left >= array_size || array[left] > value) left--;
  1283. return left;
  1284. }
  1285. static void addLengthDistance(uivector* values, size_t length, size_t distance) {
  1286. /*values in encoded vector are those used by deflate:
  1287. 0-255: literal bytes
  1288. 256: end
  1289. 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
  1290. 286-287: invalid*/
  1291. unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
  1292. unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
  1293. unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
  1294. unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
  1295. uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
  1296. uivector_push_back(values, extra_length);
  1297. uivector_push_back(values, dist_code);
  1298. uivector_push_back(values, extra_distance);
  1299. }
  1300. /*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
  1301. bytes as input because 3 is the minimum match length for deflate*/
  1302. static const unsigned HASH_NUM_VALUES = 65536;
  1303. static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
  1304. typedef struct Hash {
  1305. int* head; /*hash value to head circular pos - can be outdated if went around window*/
  1306. /*circular pos to prev circular pos*/
  1307. unsigned short* chain;
  1308. int* val; /*circular pos to hash value*/
  1309. /*TODO: do this not only for zeros but for any repeated byte. However for PNG
  1310. it's always going to be the zeros that dominate, so not important for PNG*/
  1311. int* headz; /*similar to head, but for chainz*/
  1312. unsigned short* chainz; /*those with same amount of zeros*/
  1313. unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
  1314. } Hash;
  1315. static unsigned hash_init(Hash* hash, unsigned windowsize) {
  1316. unsigned i;
  1317. hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
  1318. hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);
  1319. hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
  1320. hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
  1321. hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
  1322. hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
  1323. if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) {
  1324. return 83; /*alloc fail*/
  1325. }
  1326. /*initialize hash table*/
  1327. for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
  1328. for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
  1329. for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
  1330. for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
  1331. for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
  1332. return 0;
  1333. }
  1334. static void hash_cleanup(Hash* hash) {
  1335. lodepng_free(hash->head);
  1336. lodepng_free(hash->val);
  1337. lodepng_free(hash->chain);
  1338. lodepng_free(hash->zeros);
  1339. lodepng_free(hash->headz);
  1340. lodepng_free(hash->chainz);
  1341. }
  1342. static unsigned getHash(const unsigned char* data, size_t size, size_t pos) {
  1343. unsigned result = 0;
  1344. if(pos + 2 < size) {
  1345. /*A simple shift and xor hash is used. Since the data of PNGs is dominated
  1346. by zeroes due to the filters, a better hash does not have a significant
  1347. effect on speed in traversing the chain, and causes more time spend on
  1348. calculating the hash.*/
  1349. result ^= ((unsigned)data[pos + 0] << 0u);
  1350. result ^= ((unsigned)data[pos + 1] << 4u);
  1351. result ^= ((unsigned)data[pos + 2] << 8u);
  1352. } else {
  1353. size_t amount, i;
  1354. if(pos >= size) return 0;
  1355. amount = size - pos;
  1356. for(i = 0; i != amount; ++i) result ^= ((unsigned)data[pos + i] << (i * 8u));
  1357. }
  1358. return result & HASH_BIT_MASK;
  1359. }
  1360. static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) {
  1361. const unsigned char* start = data + pos;
  1362. const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
  1363. if(end > data + size) end = data + size;
  1364. data = start;
  1365. while(data != end && *data == 0) ++data;
  1366. /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
  1367. return (unsigned)(data - start);
  1368. }
  1369. /*wpos = pos & (windowsize - 1)*/
  1370. static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) {
  1371. hash->val[wpos] = (int)hashval;
  1372. if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
  1373. hash->head[hashval] = (int)wpos;
  1374. hash->zeros[wpos] = numzeros;
  1375. if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
  1376. hash->headz[numzeros] = (int)wpos;
  1377. }
  1378. /*
  1379. LZ77-encode the data. Return value is error code. The input are raw bytes, the output
  1380. is in the form of unsigned integers with codes representing for example literal bytes, or
  1381. length/distance pairs.
  1382. It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
  1383. sliding window (of windowsize) is used, and all past bytes in that window can be used as
  1384. the "dictionary". A brute force search through all possible distances would be slow, and
  1385. this hash technique is one out of several ways to speed this up.
  1386. */
  1387. static unsigned encodeLZ77(uivector* out, Hash* hash,
  1388. const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
  1389. unsigned minmatch, unsigned nicematch, unsigned lazymatching) {
  1390. size_t pos;
  1391. unsigned i, error = 0;
  1392. /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
  1393. unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8u;
  1394. unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
  1395. unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
  1396. unsigned numzeros = 0;
  1397. unsigned offset; /*the offset represents the distance in LZ77 terminology*/
  1398. unsigned length;
  1399. unsigned lazy = 0;
  1400. unsigned lazylength = 0, lazyoffset = 0;
  1401. unsigned hashval;
  1402. unsigned current_offset, current_length;
  1403. unsigned prev_offset;
  1404. const unsigned char *lastptr, *foreptr, *backptr;
  1405. unsigned hashpos;
  1406. if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
  1407. if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
  1408. if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
  1409. for(pos = inpos; pos < insize; ++pos) {
  1410. size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
  1411. unsigned chainlength = 0;
  1412. hashval = getHash(in, insize, pos);
  1413. if(usezeros && hashval == 0) {
  1414. if(numzeros == 0) numzeros = countZeros(in, insize, pos);
  1415. else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
  1416. } else {
  1417. numzeros = 0;
  1418. }
  1419. updateHashChain(hash, wpos, hashval, numzeros);
  1420. /*the length and offset found for the current position*/
  1421. length = 0;
  1422. offset = 0;
  1423. hashpos = hash->chain[wpos];
  1424. lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
  1425. /*search for the longest string*/
  1426. prev_offset = 0;
  1427. for(;;) {
  1428. if(chainlength++ >= maxchainlength) break;
  1429. current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize);
  1430. if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
  1431. prev_offset = current_offset;
  1432. if(current_offset > 0) {
  1433. /*test the next characters*/
  1434. foreptr = &in[pos];
  1435. backptr = &in[pos - current_offset];
  1436. /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
  1437. if(numzeros >= 3) {
  1438. unsigned skip = hash->zeros[hashpos];
  1439. if(skip > numzeros) skip = numzeros;
  1440. backptr += skip;
  1441. foreptr += skip;
  1442. }
  1443. while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ {
  1444. ++backptr;
  1445. ++foreptr;
  1446. }
  1447. current_length = (unsigned)(foreptr - &in[pos]);
  1448. if(current_length > length) {
  1449. length = current_length; /*the longest length*/
  1450. offset = current_offset; /*the offset that is related to this longest length*/
  1451. /*jump out once a length of max length is found (speed gain). This also jumps
  1452. out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
  1453. if(current_length >= nicematch) break;
  1454. }
  1455. }
  1456. if(hashpos == hash->chain[hashpos]) break;
  1457. if(numzeros >= 3 && length > numzeros) {
  1458. hashpos = hash->chainz[hashpos];
  1459. if(hash->zeros[hashpos] != numzeros) break;
  1460. } else {
  1461. hashpos = hash->chain[hashpos];
  1462. /*outdated hash value, happens if particular value was not encountered in whole last window*/
  1463. if(hash->val[hashpos] != (int)hashval) break;
  1464. }
  1465. }
  1466. if(lazymatching) {
  1467. if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) {
  1468. lazy = 1;
  1469. lazylength = length;
  1470. lazyoffset = offset;
  1471. continue; /*try the next byte*/
  1472. }
  1473. if(lazy) {
  1474. lazy = 0;
  1475. if(pos == 0) ERROR_BREAK(81);
  1476. if(length > lazylength + 1) {
  1477. /*push the previous character as literal*/
  1478. if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
  1479. } else {
  1480. length = lazylength;
  1481. offset = lazyoffset;
  1482. hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
  1483. hash->headz[numzeros] = -1; /*idem*/
  1484. --pos;
  1485. }
  1486. }
  1487. }
  1488. if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
  1489. /*encode it as length/distance pair or literal value*/
  1490. if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ {
  1491. if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
  1492. } else if(length < minmatch || (length == 3 && offset > 4096)) {
  1493. /*compensate for the fact that longer offsets have more extra bits, a
  1494. length of only 3 may be not worth it then*/
  1495. if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
  1496. } else {
  1497. addLengthDistance(out, length, offset);
  1498. for(i = 1; i < length; ++i) {
  1499. ++pos;
  1500. wpos = pos & (windowsize - 1);
  1501. hashval = getHash(in, insize, pos);
  1502. if(usezeros && hashval == 0) {
  1503. if(numzeros == 0) numzeros = countZeros(in, insize, pos);
  1504. else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
  1505. } else {
  1506. numzeros = 0;
  1507. }
  1508. updateHashChain(hash, wpos, hashval, numzeros);
  1509. }
  1510. }
  1511. } /*end of the loop through each character of input*/
  1512. return error;
  1513. }
  1514. /* /////////////////////////////////////////////////////////////////////////// */
  1515. static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) {
  1516. /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
  1517. 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
  1518. size_t i, j, numdeflateblocks = (datasize + 65534u) / 65535u;
  1519. unsigned datapos = 0;
  1520. for(i = 0; i != numdeflateblocks; ++i) {
  1521. unsigned BFINAL, BTYPE, LEN, NLEN;
  1522. unsigned char firstbyte;
  1523. BFINAL = (i == numdeflateblocks - 1);
  1524. BTYPE = 0;
  1525. firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1u) << 1u) + ((BTYPE & 2u) << 1u));
  1526. ucvector_push_back(out, firstbyte);
  1527. LEN = 65535;
  1528. if(datasize - datapos < 65535u) LEN = (unsigned)datasize - datapos;
  1529. NLEN = 65535 - LEN;
  1530. ucvector_push_back(out, (unsigned char)(LEN & 255));
  1531. ucvector_push_back(out, (unsigned char)(LEN >> 8u));
  1532. ucvector_push_back(out, (unsigned char)(NLEN & 255));
  1533. ucvector_push_back(out, (unsigned char)(NLEN >> 8u));
  1534. /*Decompressed data*/
  1535. for(j = 0; j < 65535 && datapos < datasize; ++j) {
  1536. ucvector_push_back(out, data[datapos++]);
  1537. }
  1538. }
  1539. return 0;
  1540. }
  1541. /*
  1542. write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
  1543. tree_ll: the tree for lit and len codes.
  1544. tree_d: the tree for distance codes.
  1545. */
  1546. static void writeLZ77data(LodePNGBitWriter* writer, const uivector* lz77_encoded,
  1547. const HuffmanTree* tree_ll, const HuffmanTree* tree_d) {
  1548. size_t i = 0;
  1549. for(i = 0; i != lz77_encoded->size; ++i) {
  1550. unsigned val = lz77_encoded->data[i];
  1551. writeBitsReversed(writer, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
  1552. if(val > 256) /*for a length code, 3 more things have to be added*/ {
  1553. unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
  1554. unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
  1555. unsigned length_extra_bits = lz77_encoded->data[++i];
  1556. unsigned distance_code = lz77_encoded->data[++i];
  1557. unsigned distance_index = distance_code;
  1558. unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
  1559. unsigned distance_extra_bits = lz77_encoded->data[++i];
  1560. writeBits(writer, length_extra_bits, n_length_extra_bits);
  1561. writeBitsReversed(writer, HuffmanTree_getCode(tree_d, distance_code),
  1562. HuffmanTree_getLength(tree_d, distance_code));
  1563. writeBits(writer, distance_extra_bits, n_distance_extra_bits);
  1564. }
  1565. }
  1566. }
  1567. /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
  1568. static unsigned deflateDynamic(LodePNGBitWriter* writer, Hash* hash,
  1569. const unsigned char* data, size_t datapos, size_t dataend,
  1570. const LodePNGCompressSettings* settings, unsigned final) {
  1571. unsigned error = 0;
  1572. /*
  1573. A block is compressed as follows: The PNG data is lz77 encoded, resulting in
  1574. literal bytes and length/distance pairs. This is then huffman compressed with
  1575. two huffman trees. One huffman tree is used for the lit and len values ("ll"),
  1576. another huffman tree is used for the dist values ("d"). These two trees are
  1577. stored using their code lengths, and to compress even more these code lengths
  1578. are also run-length encoded and huffman compressed. This gives a huffman tree
  1579. of code lengths "cl". The code lengths used to describe this third tree are
  1580. the code length code lengths ("clcl").
  1581. */
  1582. /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
  1583. uivector lz77_encoded;
  1584. HuffmanTree tree_ll; /*tree for lit,len values*/
  1585. HuffmanTree tree_d; /*tree for distance codes*/
  1586. HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
  1587. uivector frequencies_ll; /*frequency of lit,len codes*/
  1588. uivector frequencies_d; /*frequency of dist codes*/
  1589. uivector frequencies_cl; /*frequency of code length codes*/
  1590. uivector bitlen_lld; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/
  1591. uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/
  1592. /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
  1593. (these are written as is in the file, it would be crazy to compress these using yet another huffman
  1594. tree that needs to be represented by yet another set of code lengths)*/
  1595. uivector bitlen_cl;
  1596. size_t datasize = dataend - datapos;
  1597. /*
  1598. Due to the huffman compression of huffman tree representations ("two levels"), there are some analogies:
  1599. bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
  1600. bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
  1601. bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
  1602. */
  1603. unsigned BFINAL = final;
  1604. size_t numcodes_ll, numcodes_d, i;
  1605. unsigned HLIT, HDIST, HCLEN;
  1606. uivector_init(&lz77_encoded);
  1607. HuffmanTree_init(&tree_ll);
  1608. HuffmanTree_init(&tree_d);
  1609. HuffmanTree_init(&tree_cl);
  1610. uivector_init(&frequencies_ll);
  1611. uivector_init(&frequencies_d);
  1612. uivector_init(&frequencies_cl);
  1613. uivector_init(&bitlen_lld);
  1614. uivector_init(&bitlen_lld_e);
  1615. uivector_init(&bitlen_cl);
  1616. /*This while loop never loops due to a break at the end, it is here to
  1617. allow breaking out of it to the cleanup phase on error conditions.*/
  1618. while(!error) {
  1619. if(settings->use_lz77) {
  1620. error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
  1621. settings->minmatch, settings->nicematch, settings->lazymatching);
  1622. if(error) break;
  1623. } else {
  1624. if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
  1625. for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/
  1626. }
  1627. if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
  1628. if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
  1629. /*Count the frequencies of lit, len and dist codes*/
  1630. for(i = 0; i != lz77_encoded.size; ++i) {
  1631. unsigned symbol = lz77_encoded.data[i];
  1632. ++frequencies_ll.data[symbol];
  1633. if(symbol > 256) {
  1634. unsigned dist = lz77_encoded.data[i + 2];
  1635. ++frequencies_d.data[dist];
  1636. i += 3;
  1637. }
  1638. }
  1639. frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
  1640. /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
  1641. error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
  1642. if(error) break;
  1643. /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
  1644. error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
  1645. if(error) break;
  1646. numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
  1647. numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
  1648. /*store the code lengths of both generated trees in bitlen_lld*/
  1649. for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
  1650. for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
  1651. /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
  1652. 17 (3-10 zeroes), 18 (11-138 zeroes)*/
  1653. for(i = 0; i != (unsigned)bitlen_lld.size; ++i) {
  1654. unsigned j = 0; /*amount of repetitions*/
  1655. while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j;
  1656. if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ {
  1657. ++j; /*include the first zero*/
  1658. if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ {
  1659. uivector_push_back(&bitlen_lld_e, 17);
  1660. uivector_push_back(&bitlen_lld_e, j - 3);
  1661. } else /*repeat code 18 supports max 138 zeroes*/ {
  1662. if(j > 138) j = 138;
  1663. uivector_push_back(&bitlen_lld_e, 18);
  1664. uivector_push_back(&bitlen_lld_e, j - 11);
  1665. }
  1666. i += (j - 1);
  1667. } else if(j >= 3) /*repeat code for value other than zero*/ {
  1668. size_t k;
  1669. unsigned num = j / 6u, rest = j % 6u;
  1670. uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
  1671. for(k = 0; k < num; ++k) {
  1672. uivector_push_back(&bitlen_lld_e, 16);
  1673. uivector_push_back(&bitlen_lld_e, 6 - 3);
  1674. }
  1675. if(rest >= 3) {
  1676. uivector_push_back(&bitlen_lld_e, 16);
  1677. uivector_push_back(&bitlen_lld_e, rest - 3);
  1678. }
  1679. else j -= rest;
  1680. i += j;
  1681. } else /*too short to benefit from repeat code*/ {
  1682. uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
  1683. }
  1684. }
  1685. /*generate tree_cl, the huffmantree of huffmantrees*/
  1686. if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
  1687. for(i = 0; i != bitlen_lld_e.size; ++i) {
  1688. ++frequencies_cl.data[bitlen_lld_e.data[i]];
  1689. /*after a repeat code come the bits that specify the number of repetitions,
  1690. those don't need to be in the frequencies_cl calculation*/
  1691. if(bitlen_lld_e.data[i] >= 16) ++i;
  1692. }
  1693. error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
  1694. frequencies_cl.size, frequencies_cl.size, 7);
  1695. if(error) break;
  1696. if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
  1697. for(i = 0; i != tree_cl.numcodes; ++i) {
  1698. /*lengths of code length tree is in the order as specified by deflate*/
  1699. bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
  1700. }
  1701. while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) {
  1702. /*remove zeros at the end, but minimum size must be 4*/
  1703. if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
  1704. }
  1705. if(error) break;
  1706. /*
  1707. Write everything into the output
  1708. After the BFINAL and BTYPE, the dynamic block consists out of the following:
  1709. - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
  1710. - (HCLEN+4)*3 bits code lengths of code length alphabet
  1711. - HLIT + 257 code lengths of lit/length alphabet (encoded using the code length
  1712. alphabet, + possible repetition codes 16, 17, 18)
  1713. - HDIST + 1 code lengths of distance alphabet (encoded using the code length
  1714. alphabet, + possible repetition codes 16, 17, 18)
  1715. - compressed data
  1716. - 256 (end code)
  1717. */
  1718. /*Write block type*/
  1719. writeBits(writer, BFINAL, 1);
  1720. writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/
  1721. writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/
  1722. /*write the HLIT, HDIST and HCLEN values*/
  1723. HLIT = (unsigned)(numcodes_ll - 257);
  1724. HDIST = (unsigned)(numcodes_d - 1);
  1725. HCLEN = (unsigned)bitlen_cl.size - 4;
  1726. /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
  1727. while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN;
  1728. writeBits(writer, HLIT, 5);
  1729. writeBits(writer, HDIST, 5);
  1730. writeBits(writer, HCLEN, 4);
  1731. /*write the code lengths of the code length alphabet*/
  1732. for(i = 0; i != HCLEN + 4; ++i) writeBits(writer, bitlen_cl.data[i], 3);
  1733. /*write the lengths of the lit/len AND the dist alphabet*/
  1734. for(i = 0; i != bitlen_lld_e.size; ++i) {
  1735. writeBitsReversed(writer, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
  1736. HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
  1737. /*extra bits of repeat codes*/
  1738. if(bitlen_lld_e.data[i] == 16) writeBits(writer, bitlen_lld_e.data[++i], 2);
  1739. else if(bitlen_lld_e.data[i] == 17) writeBits(writer, bitlen_lld_e.data[++i], 3);
  1740. else if(bitlen_lld_e.data[i] == 18) writeBits(writer, bitlen_lld_e.data[++i], 7);
  1741. }
  1742. /*write the compressed data symbols*/
  1743. writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
  1744. /*error: the length of the end code 256 must be larger than 0*/
  1745. if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
  1746. /*write the end code*/
  1747. writeBitsReversed(writer, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
  1748. break; /*end of error-while*/
  1749. }
  1750. /*cleanup*/
  1751. uivector_cleanup(&lz77_encoded);
  1752. HuffmanTree_cleanup(&tree_ll);
  1753. HuffmanTree_cleanup(&tree_d);
  1754. HuffmanTree_cleanup(&tree_cl);
  1755. uivector_cleanup(&frequencies_ll);
  1756. uivector_cleanup(&frequencies_d);
  1757. uivector_cleanup(&frequencies_cl);
  1758. uivector_cleanup(&bitlen_lld_e);
  1759. uivector_cleanup(&bitlen_lld);
  1760. uivector_cleanup(&bitlen_cl);
  1761. return error;
  1762. }
  1763. static unsigned deflateFixed(LodePNGBitWriter* writer, Hash* hash,
  1764. const unsigned char* data,
  1765. size_t datapos, size_t dataend,
  1766. const LodePNGCompressSettings* settings, unsigned final) {
  1767. HuffmanTree tree_ll; /*tree for literal values and length codes*/
  1768. HuffmanTree tree_d; /*tree for distance codes*/
  1769. unsigned BFINAL = final;
  1770. unsigned error = 0;
  1771. size_t i;
  1772. HuffmanTree_init(&tree_ll);
  1773. HuffmanTree_init(&tree_d);
  1774. generateFixedLitLenTree(&tree_ll);
  1775. generateFixedDistanceTree(&tree_d);
  1776. writeBits(writer, BFINAL, 1);
  1777. writeBits(writer, 1, 1); /*first bit of BTYPE*/
  1778. writeBits(writer, 0, 1); /*second bit of BTYPE*/
  1779. if(settings->use_lz77) /*LZ77 encoded*/ {
  1780. uivector lz77_encoded;
  1781. uivector_init(&lz77_encoded);
  1782. error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
  1783. settings->minmatch, settings->nicematch, settings->lazymatching);
  1784. if(!error) writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d);
  1785. uivector_cleanup(&lz77_encoded);
  1786. } else /*no LZ77, but still will be Huffman compressed*/ {
  1787. for(i = datapos; i < dataend; ++i) {
  1788. writeBitsReversed(writer, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
  1789. }
  1790. }
  1791. /*add END code*/
  1792. if(!error) writeBitsReversed(writer, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
  1793. /*cleanup*/
  1794. HuffmanTree_cleanup(&tree_ll);
  1795. HuffmanTree_cleanup(&tree_d);
  1796. return error;
  1797. }
  1798. static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
  1799. const LodePNGCompressSettings* settings) {
  1800. unsigned error = 0;
  1801. size_t i, blocksize, numdeflateblocks;
  1802. Hash hash;
  1803. LodePNGBitWriter writer;
  1804. LodePNGBitWriter_init(&writer, out);
  1805. if(settings->btype > 2) return 61;
  1806. else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
  1807. else if(settings->btype == 1) blocksize = insize;
  1808. else /*if(settings->btype == 2)*/ {
  1809. /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
  1810. blocksize = insize / 8u + 8;
  1811. if(blocksize < 65536) blocksize = 65536;
  1812. if(blocksize > 262144) blocksize = 262144;
  1813. }
  1814. numdeflateblocks = (insize + blocksize - 1) / blocksize;
  1815. if(numdeflateblocks == 0) numdeflateblocks = 1;
  1816. error = hash_init(&hash, settings->windowsize);
  1817. if(error) return error;
  1818. for(i = 0; i != numdeflateblocks && !error; ++i) {
  1819. unsigned final = (i == numdeflateblocks - 1);
  1820. size_t start = i * blocksize;
  1821. size_t end = start + blocksize;
  1822. if(end > insize) end = insize;
  1823. if(settings->btype == 1) error = deflateFixed(&writer, &hash, in, start, end, settings, final);
  1824. else if(settings->btype == 2) error = deflateDynamic(&writer, &hash, in, start, end, settings, final);
  1825. }
  1826. hash_cleanup(&hash);
  1827. return error;
  1828. }
  1829. unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
  1830. const unsigned char* in, size_t insize,
  1831. const LodePNGCompressSettings* settings) {
  1832. unsigned error;
  1833. ucvector v;
  1834. ucvector_init_buffer(&v, *out, *outsize);
  1835. error = lodepng_deflatev(&v, in, insize, settings);
  1836. *out = v.data;
  1837. *outsize = v.size;
  1838. return error;
  1839. }
  1840. static unsigned deflate(unsigned char** out, size_t* outsize,
  1841. const unsigned char* in, size_t insize,
  1842. const LodePNGCompressSettings* settings) {
  1843. if(settings->custom_deflate) {
  1844. return settings->custom_deflate(out, outsize, in, insize, settings);
  1845. } else {
  1846. return lodepng_deflate(out, outsize, in, insize, settings);
  1847. }
  1848. }
  1849. #endif /*LODEPNG_COMPILE_DECODER*/
  1850. /* ////////////////////////////////////////////////////////////////////////// */
  1851. /* / Adler32 / */
  1852. /* ////////////////////////////////////////////////////////////////////////// */
  1853. static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) {
  1854. unsigned s1 = adler & 0xffffu;
  1855. unsigned s2 = (adler >> 16u) & 0xffffu;
  1856. while(len != 0u) {
  1857. unsigned i;
  1858. /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/
  1859. unsigned amount = len > 5552u ? 5552u : len;
  1860. len -= amount;
  1861. for(i = 0; i != amount; ++i) {
  1862. s1 += (*data++);
  1863. s2 += s1;
  1864. }
  1865. s1 %= 65521u;
  1866. s2 %= 65521u;
  1867. }
  1868. return (s2 << 16u) | s1;
  1869. }
  1870. /*Return the adler32 of the bytes data[0..len-1]*/
  1871. static unsigned adler32(const unsigned char* data, unsigned len) {
  1872. return update_adler32(1u, data, len);
  1873. }
  1874. /* ////////////////////////////////////////////////////////////////////////// */
  1875. /* / Zlib / */
  1876. /* ////////////////////////////////////////////////////////////////////////// */
  1877. #ifdef LODEPNG_COMPILE_DECODER
  1878. unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1879. size_t insize, const LodePNGDecompressSettings* settings) {
  1880. unsigned error = 0;
  1881. unsigned CM, CINFO, FDICT;
  1882. if(insize < 2) return 53; /*error, size of zlib data too small*/
  1883. /*read information from zlib header*/
  1884. if((in[0] * 256 + in[1]) % 31 != 0) {
  1885. /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
  1886. return 24;
  1887. }
  1888. CM = in[0] & 15;
  1889. CINFO = (in[0] >> 4) & 15;
  1890. /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
  1891. FDICT = (in[1] >> 5) & 1;
  1892. /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
  1893. if(CM != 8 || CINFO > 7) {
  1894. /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
  1895. return 25;
  1896. }
  1897. if(FDICT != 0) {
  1898. /*error: the specification of PNG says about the zlib stream:
  1899. "The additional flags shall not specify a preset dictionary."*/
  1900. return 26;
  1901. }
  1902. error = inflate(out, outsize, in + 2, insize - 2, settings);
  1903. if(error) return error;
  1904. if(!settings->ignore_adler32) {
  1905. unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
  1906. unsigned checksum = adler32(*out, (unsigned)(*outsize));
  1907. if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
  1908. }
  1909. return 0; /*no error*/
  1910. }
  1911. static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1912. size_t insize, const LodePNGDecompressSettings* settings) {
  1913. if(settings->custom_zlib) {
  1914. return settings->custom_zlib(out, outsize, in, insize, settings);
  1915. } else {
  1916. return lodepng_zlib_decompress(out, outsize, in, insize, settings);
  1917. }
  1918. }
  1919. #endif /*LODEPNG_COMPILE_DECODER*/
  1920. #ifdef LODEPNG_COMPILE_ENCODER
  1921. unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1922. size_t insize, const LodePNGCompressSettings* settings) {
  1923. size_t i;
  1924. unsigned error;
  1925. unsigned char* deflatedata = 0;
  1926. size_t deflatesize = 0;
  1927. error = deflate(&deflatedata, &deflatesize, in, insize, settings);
  1928. *out = NULL;
  1929. *outsize = 0;
  1930. if(!error) {
  1931. *outsize = deflatesize + 6;
  1932. *out = (unsigned char*)lodepng_malloc(*outsize);
  1933. if(!*out) error = 83; /*alloc fail*/
  1934. }
  1935. if(!error) {
  1936. unsigned ADLER32 = adler32(in, (unsigned)insize);
  1937. /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
  1938. unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
  1939. unsigned FLEVEL = 0;
  1940. unsigned FDICT = 0;
  1941. unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
  1942. unsigned FCHECK = 31 - CMFFLG % 31;
  1943. CMFFLG += FCHECK;
  1944. (*out)[0] = (unsigned char)(CMFFLG >> 8);
  1945. (*out)[1] = (unsigned char)(CMFFLG & 255);
  1946. for(i = 0; i != deflatesize; ++i) (*out)[i + 2] = deflatedata[i];
  1947. lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32);
  1948. }
  1949. lodepng_free(deflatedata);
  1950. return error;
  1951. }
  1952. /* compress using the default or custom zlib function */
  1953. static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1954. size_t insize, const LodePNGCompressSettings* settings) {
  1955. if(settings->custom_zlib) {
  1956. return settings->custom_zlib(out, outsize, in, insize, settings);
  1957. } else {
  1958. return lodepng_zlib_compress(out, outsize, in, insize, settings);
  1959. }
  1960. }
  1961. #endif /*LODEPNG_COMPILE_ENCODER*/
  1962. #else /*no LODEPNG_COMPILE_ZLIB*/
  1963. #ifdef LODEPNG_COMPILE_DECODER
  1964. static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1965. size_t insize, const LodePNGDecompressSettings* settings) {
  1966. if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
  1967. return settings->custom_zlib(out, outsize, in, insize, settings);
  1968. }
  1969. #endif /*LODEPNG_COMPILE_DECODER*/
  1970. #ifdef LODEPNG_COMPILE_ENCODER
  1971. static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
  1972. size_t insize, const LodePNGCompressSettings* settings) {
  1973. if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
  1974. return settings->custom_zlib(out, outsize, in, insize, settings);
  1975. }
  1976. #endif /*LODEPNG_COMPILE_ENCODER*/
  1977. #endif /*LODEPNG_COMPILE_ZLIB*/
  1978. /* ////////////////////////////////////////////////////////////////////////// */
  1979. #ifdef LODEPNG_COMPILE_ENCODER
  1980. /*this is a good tradeoff between speed and compression ratio*/
  1981. #define DEFAULT_WINDOWSIZE 2048
  1982. void lodepng_compress_settings_init(LodePNGCompressSettings* settings) {
  1983. /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
  1984. settings->btype = 2;
  1985. settings->use_lz77 = 1;
  1986. settings->windowsize = DEFAULT_WINDOWSIZE;
  1987. settings->minmatch = 3;
  1988. settings->nicematch = 128;
  1989. settings->lazymatching = 1;
  1990. settings->custom_zlib = 0;
  1991. settings->custom_deflate = 0;
  1992. settings->custom_context = 0;
  1993. }
  1994. const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
  1995. #endif /*LODEPNG_COMPILE_ENCODER*/
  1996. #ifdef LODEPNG_COMPILE_DECODER
  1997. void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) {
  1998. settings->ignore_adler32 = 0;
  1999. settings->ignore_nlen = 0;
  2000. settings->custom_zlib = 0;
  2001. settings->custom_inflate = 0;
  2002. settings->custom_context = 0;
  2003. }
  2004. const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0};
  2005. #endif /*LODEPNG_COMPILE_DECODER*/
  2006. /* ////////////////////////////////////////////////////////////////////////// */
  2007. /* ////////////////////////////////////////////////////////////////////////// */
  2008. /* // End of Zlib related code. Begin of PNG related code. // */
  2009. /* ////////////////////////////////////////////////////////////////////////// */
  2010. /* ////////////////////////////////////////////////////////////////////////// */
  2011. #ifdef LODEPNG_COMPILE_PNG
  2012. /* ////////////////////////////////////////////////////////////////////////// */
  2013. /* / CRC32 / */
  2014. /* ////////////////////////////////////////////////////////////////////////// */
  2015. #ifndef LODEPNG_NO_COMPILE_CRC
  2016. /* CRC polynomial: 0xedb88320 */
  2017. static unsigned lodepng_crc32_table[256] = {
  2018. 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
  2019. 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
  2020. 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
  2021. 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
  2022. 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
  2023. 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
  2024. 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
  2025. 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
  2026. 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
  2027. 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
  2028. 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
  2029. 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
  2030. 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
  2031. 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
  2032. 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
  2033. 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
  2034. 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
  2035. 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
  2036. 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
  2037. 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
  2038. 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
  2039. 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
  2040. 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
  2041. 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
  2042. 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
  2043. 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
  2044. 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
  2045. 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
  2046. 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
  2047. 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
  2048. 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
  2049. 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
  2050. };
  2051. /*Return the CRC of the bytes buf[0..len-1].*/
  2052. unsigned lodepng_crc32(const unsigned char* data, size_t length) {
  2053. unsigned r = 0xffffffffu;
  2054. size_t i;
  2055. for(i = 0; i < length; ++i) {
  2056. r = lodepng_crc32_table[(r ^ data[i]) & 0xffu] ^ (r >> 8u);
  2057. }
  2058. return r ^ 0xffffffffu;
  2059. }
  2060. #else /* !LODEPNG_NO_COMPILE_CRC */
  2061. unsigned lodepng_crc32(const unsigned char* data, size_t length);
  2062. #endif /* !LODEPNG_NO_COMPILE_CRC */
  2063. /* ////////////////////////////////////////////////////////////////////////// */
  2064. /* / Reading and writing PNG color channel bits / */
  2065. /* ////////////////////////////////////////////////////////////////////////// */
  2066. /* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first,
  2067. so LodePNGBitWriter and LodePNGBitReader can't be used for those. */
  2068. static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) {
  2069. unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
  2070. ++(*bitpointer);
  2071. return result;
  2072. }
  2073. /* TODO: make this faster */
  2074. static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) {
  2075. unsigned result = 0;
  2076. size_t i;
  2077. for(i = 0 ; i < nbits; ++i) {
  2078. result <<= 1u;
  2079. result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream);
  2080. }
  2081. return result;
  2082. }
  2083. static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) {
  2084. /*the current bit in bitstream may be 0 or 1 for this to work*/
  2085. if(bit == 0) bitstream[(*bitpointer) >> 3u] &= (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u))));
  2086. else bitstream[(*bitpointer) >> 3u] |= (1u << (7u - ((*bitpointer) & 7u)));
  2087. ++(*bitpointer);
  2088. }
  2089. /* ////////////////////////////////////////////////////////////////////////// */
  2090. /* / PNG chunks / */
  2091. /* ////////////////////////////////////////////////////////////////////////// */
  2092. unsigned lodepng_chunk_length(const unsigned char* chunk) {
  2093. return lodepng_read32bitInt(&chunk[0]);
  2094. }
  2095. void lodepng_chunk_type(char type[5], const unsigned char* chunk) {
  2096. unsigned i;
  2097. for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
  2098. type[4] = 0; /*null termination char*/
  2099. }
  2100. unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) {
  2101. if(lodepng_strlen(type) != 4) return 0;
  2102. return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
  2103. }
  2104. unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) {
  2105. return((chunk[4] & 32) != 0);
  2106. }
  2107. unsigned char lodepng_chunk_private(const unsigned char* chunk) {
  2108. return((chunk[6] & 32) != 0);
  2109. }
  2110. unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) {
  2111. return((chunk[7] & 32) != 0);
  2112. }
  2113. unsigned char* lodepng_chunk_data(unsigned char* chunk) {
  2114. return &chunk[8];
  2115. }
  2116. const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) {
  2117. return &chunk[8];
  2118. }
  2119. unsigned lodepng_chunk_check_crc(const unsigned char* chunk) {
  2120. unsigned length = lodepng_chunk_length(chunk);
  2121. unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
  2122. /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
  2123. unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
  2124. if(CRC != checksum) return 1;
  2125. else return 0;
  2126. }
  2127. void lodepng_chunk_generate_crc(unsigned char* chunk) {
  2128. unsigned length = lodepng_chunk_length(chunk);
  2129. unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
  2130. lodepng_set32bitInt(chunk + 8 + length, CRC);
  2131. }
  2132. unsigned char* lodepng_chunk_next(unsigned char* chunk) {
  2133. if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
  2134. && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
  2135. /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
  2136. return chunk + 8;
  2137. } else {
  2138. unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
  2139. return chunk + total_chunk_length;
  2140. }
  2141. }
  2142. const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) {
  2143. if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
  2144. && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
  2145. /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
  2146. return chunk + 8;
  2147. } else {
  2148. unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
  2149. return chunk + total_chunk_length;
  2150. }
  2151. }
  2152. unsigned char* lodepng_chunk_find(unsigned char* chunk, const unsigned char* end, const char type[5]) {
  2153. for(;;) {
  2154. if(chunk + 12 >= end) return 0;
  2155. if(lodepng_chunk_type_equals(chunk, type)) return chunk;
  2156. chunk = lodepng_chunk_next(chunk);
  2157. }
  2158. }
  2159. const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) {
  2160. for(;;) {
  2161. if(chunk + 12 >= end) return 0;
  2162. if(lodepng_chunk_type_equals(chunk, type)) return chunk;
  2163. chunk = lodepng_chunk_next_const(chunk);
  2164. }
  2165. }
  2166. unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) {
  2167. unsigned i;
  2168. unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
  2169. unsigned char *chunk_start, *new_buffer;
  2170. size_t new_length = (*outlength) + total_chunk_length;
  2171. if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
  2172. new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
  2173. if(!new_buffer) return 83; /*alloc fail*/
  2174. (*out) = new_buffer;
  2175. (*outlength) = new_length;
  2176. chunk_start = &(*out)[new_length - total_chunk_length];
  2177. for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
  2178. return 0;
  2179. }
  2180. unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
  2181. const char* type, const unsigned char* data) {
  2182. unsigned i;
  2183. unsigned char *chunk, *new_buffer;
  2184. size_t new_length = (*outlength) + length + 12;
  2185. if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
  2186. new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
  2187. if(!new_buffer) return 83; /*alloc fail*/
  2188. (*out) = new_buffer;
  2189. (*outlength) = new_length;
  2190. chunk = &(*out)[(*outlength) - length - 12];
  2191. /*1: length*/
  2192. lodepng_set32bitInt(chunk, (unsigned)length);
  2193. /*2: chunk name (4 letters)*/
  2194. chunk[4] = (unsigned char)type[0];
  2195. chunk[5] = (unsigned char)type[1];
  2196. chunk[6] = (unsigned char)type[2];
  2197. chunk[7] = (unsigned char)type[3];
  2198. /*3: the data*/
  2199. for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
  2200. /*4: CRC (of the chunkname characters and the data)*/
  2201. lodepng_chunk_generate_crc(chunk);
  2202. return 0;
  2203. }
  2204. /* ////////////////////////////////////////////////////////////////////////// */
  2205. /* / Color types, channels, bits / */
  2206. /* ////////////////////////////////////////////////////////////////////////// */
  2207. /*checks if the colortype is valid and the bitdepth bd is allowed for this colortype.
  2208. Return value is a LodePNG error code.*/
  2209. static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) {
  2210. switch(colortype) {
  2211. case LCT_GREY: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break;
  2212. case LCT_RGB: if(!( bd == 8 || bd == 16)) return 37; break;
  2213. case LCT_PALETTE: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break;
  2214. case LCT_GREY_ALPHA: if(!( bd == 8 || bd == 16)) return 37; break;
  2215. case LCT_RGBA: if(!( bd == 8 || bd == 16)) return 37; break;
  2216. default: return 31; /* invalid color type */
  2217. }
  2218. return 0; /*allowed color type / bits combination*/
  2219. }
  2220. static unsigned getNumColorChannels(LodePNGColorType colortype) {
  2221. switch(colortype) {
  2222. case LCT_GREY: return 1;
  2223. case LCT_RGB: return 3;
  2224. case LCT_PALETTE: return 1;
  2225. case LCT_GREY_ALPHA: return 2;
  2226. case LCT_RGBA: return 4;
  2227. default: return 0; /*invalid color type*/
  2228. }
  2229. }
  2230. static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) {
  2231. /*bits per pixel is amount of channels * bits per channel*/
  2232. return getNumColorChannels(colortype) * bitdepth;
  2233. }
  2234. /* ////////////////////////////////////////////////////////////////////////// */
  2235. void lodepng_color_mode_init(LodePNGColorMode* info) {
  2236. info->key_defined = 0;
  2237. info->key_r = info->key_g = info->key_b = 0;
  2238. info->colortype = LCT_RGBA;
  2239. info->bitdepth = 8;
  2240. info->palette = 0;
  2241. info->palettesize = 0;
  2242. }
  2243. void lodepng_color_mode_alloc_palette(LodePNGColorMode* info) {
  2244. size_t i;
  2245. /*room for 256 colors with 4 bytes each. Using realloc to avoid leak if it is being overwritten*/
  2246. info->palette = (unsigned char*)lodepng_realloc(info->palette, 1024);
  2247. if(!info->palette) return; /*alloc fail*/
  2248. for(i = 0; i != 256; ++i) {
  2249. /*Initialize all unused colors with black, the value used for invalid palette indices.
  2250. This is an error according to the PNG spec, but common PNG decoders make it black instead.
  2251. That makes color conversion slightly faster due to no error handling needed.*/
  2252. info->palette[i * 4 + 0] = 0;
  2253. info->palette[i * 4 + 1] = 0;
  2254. info->palette[i * 4 + 2] = 0;
  2255. info->palette[i * 4 + 3] = 255;
  2256. }
  2257. }
  2258. void lodepng_color_mode_cleanup(LodePNGColorMode* info) {
  2259. lodepng_palette_clear(info);
  2260. }
  2261. unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) {
  2262. size_t i;
  2263. lodepng_color_mode_cleanup(dest);
  2264. *dest = *source;
  2265. if(source->palette) {
  2266. dest->palette = (unsigned char*)lodepng_malloc(1024);
  2267. if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
  2268. for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i];
  2269. }
  2270. return 0;
  2271. }
  2272. LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) {
  2273. LodePNGColorMode result;
  2274. lodepng_color_mode_init(&result);
  2275. result.colortype = colortype;
  2276. result.bitdepth = bitdepth;
  2277. return result;
  2278. }
  2279. static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) {
  2280. size_t i;
  2281. if(a->colortype != b->colortype) return 0;
  2282. if(a->bitdepth != b->bitdepth) return 0;
  2283. if(a->key_defined != b->key_defined) return 0;
  2284. if(a->key_defined) {
  2285. if(a->key_r != b->key_r) return 0;
  2286. if(a->key_g != b->key_g) return 0;
  2287. if(a->key_b != b->key_b) return 0;
  2288. }
  2289. if(a->palettesize != b->palettesize) return 0;
  2290. for(i = 0; i != a->palettesize * 4; ++i) {
  2291. if(a->palette[i] != b->palette[i]) return 0;
  2292. }
  2293. return 1;
  2294. }
  2295. void lodepng_palette_clear(LodePNGColorMode* info) {
  2296. if(info->palette) lodepng_free(info->palette);
  2297. info->palette = 0;
  2298. info->palettesize = 0;
  2299. }
  2300. unsigned lodepng_palette_add(LodePNGColorMode* info,
  2301. unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  2302. if(!info->palette) /*allocate palette if empty*/ {
  2303. lodepng_color_mode_alloc_palette(info);
  2304. if(!info->palette) return 83; /*alloc fail*/
  2305. }
  2306. if(info->palettesize >= 256) {
  2307. return 108; /*too many palette values*/
  2308. }
  2309. info->palette[4 * info->palettesize + 0] = r;
  2310. info->palette[4 * info->palettesize + 1] = g;
  2311. info->palette[4 * info->palettesize + 2] = b;
  2312. info->palette[4 * info->palettesize + 3] = a;
  2313. ++info->palettesize;
  2314. return 0;
  2315. }
  2316. /*calculate bits per pixel out of colortype and bitdepth*/
  2317. unsigned lodepng_get_bpp(const LodePNGColorMode* info) {
  2318. return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
  2319. }
  2320. unsigned lodepng_get_channels(const LodePNGColorMode* info) {
  2321. return getNumColorChannels(info->colortype);
  2322. }
  2323. unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) {
  2324. return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
  2325. }
  2326. unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) {
  2327. return (info->colortype & 4) != 0; /*4 or 6*/
  2328. }
  2329. unsigned lodepng_is_palette_type(const LodePNGColorMode* info) {
  2330. return info->colortype == LCT_PALETTE;
  2331. }
  2332. unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) {
  2333. size_t i;
  2334. for(i = 0; i != info->palettesize; ++i) {
  2335. if(info->palette[i * 4 + 3] < 255) return 1;
  2336. }
  2337. return 0;
  2338. }
  2339. unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) {
  2340. return info->key_defined
  2341. || lodepng_is_alpha_type(info)
  2342. || lodepng_has_palette_alpha(info);
  2343. }
  2344. static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
  2345. size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
  2346. size_t n = (size_t)w * (size_t)h;
  2347. return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u;
  2348. }
  2349. size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) {
  2350. return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth);
  2351. }
  2352. #ifdef LODEPNG_COMPILE_PNG
  2353. #ifdef LODEPNG_COMPILE_DECODER
  2354. /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer,
  2355. and in addition has one extra byte per line: the filter byte. So this gives a larger
  2356. result than lodepng_get_raw_size. */
  2357. static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) {
  2358. size_t bpp = lodepng_get_bpp(color);
  2359. /* + 1 for the filter byte, and possibly plus padding bits per line */
  2360. size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u;
  2361. return (size_t)h * line;
  2362. }
  2363. /*Safely checks whether size_t overflow can be caused due to amount of pixels.
  2364. This check is overcautious rather than precise. If this check indicates no overflow,
  2365. you can safely compute in a size_t (but not an unsigned):
  2366. -(size_t)w * (size_t)h * 8
  2367. -amount of bytes in IDAT (including filter, padding and Adam7 bytes)
  2368. -amount of bytes in raw color model
  2369. Returns 1 if overflow possible, 0 if not.
  2370. */
  2371. static int lodepng_pixel_overflow(unsigned w, unsigned h,
  2372. const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) {
  2373. size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor));
  2374. size_t numpixels, total;
  2375. size_t line; /* bytes per line in worst case */
  2376. if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1;
  2377. if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */
  2378. /* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */
  2379. if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1;
  2380. if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1;
  2381. if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */
  2382. if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */
  2383. return 0; /* no overflow */
  2384. }
  2385. #endif /*LODEPNG_COMPILE_DECODER*/
  2386. #endif /*LODEPNG_COMPILE_PNG*/
  2387. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  2388. static void LodePNGUnknownChunks_init(LodePNGInfo* info) {
  2389. unsigned i;
  2390. for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
  2391. for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
  2392. }
  2393. static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) {
  2394. unsigned i;
  2395. for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
  2396. }
  2397. static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) {
  2398. unsigned i;
  2399. LodePNGUnknownChunks_cleanup(dest);
  2400. for(i = 0; i != 3; ++i) {
  2401. size_t j;
  2402. dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
  2403. dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
  2404. if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
  2405. for(j = 0; j < src->unknown_chunks_size[i]; ++j) {
  2406. dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
  2407. }
  2408. }
  2409. return 0;
  2410. }
  2411. /******************************************************************************/
  2412. static void LodePNGText_init(LodePNGInfo* info) {
  2413. info->text_num = 0;
  2414. info->text_keys = NULL;
  2415. info->text_strings = NULL;
  2416. }
  2417. static void LodePNGText_cleanup(LodePNGInfo* info) {
  2418. size_t i;
  2419. for(i = 0; i != info->text_num; ++i) {
  2420. string_cleanup(&info->text_keys[i]);
  2421. string_cleanup(&info->text_strings[i]);
  2422. }
  2423. lodepng_free(info->text_keys);
  2424. lodepng_free(info->text_strings);
  2425. }
  2426. static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
  2427. size_t i = 0;
  2428. dest->text_keys = 0;
  2429. dest->text_strings = 0;
  2430. dest->text_num = 0;
  2431. for(i = 0; i != source->text_num; ++i) {
  2432. CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
  2433. }
  2434. return 0;
  2435. }
  2436. void lodepng_clear_text(LodePNGInfo* info) {
  2437. LodePNGText_cleanup(info);
  2438. }
  2439. unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) {
  2440. char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
  2441. char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
  2442. if(!new_keys || !new_strings) {
  2443. lodepng_free(new_keys);
  2444. lodepng_free(new_strings);
  2445. return 83; /*alloc fail*/
  2446. }
  2447. ++info->text_num;
  2448. info->text_keys = new_keys;
  2449. info->text_strings = new_strings;
  2450. info->text_keys[info->text_num - 1] = alloc_string(key);
  2451. info->text_strings[info->text_num - 1] = alloc_string(str);
  2452. return 0;
  2453. }
  2454. /******************************************************************************/
  2455. static void LodePNGIText_init(LodePNGInfo* info) {
  2456. info->itext_num = 0;
  2457. info->itext_keys = NULL;
  2458. info->itext_langtags = NULL;
  2459. info->itext_transkeys = NULL;
  2460. info->itext_strings = NULL;
  2461. }
  2462. static void LodePNGIText_cleanup(LodePNGInfo* info) {
  2463. size_t i;
  2464. for(i = 0; i != info->itext_num; ++i) {
  2465. string_cleanup(&info->itext_keys[i]);
  2466. string_cleanup(&info->itext_langtags[i]);
  2467. string_cleanup(&info->itext_transkeys[i]);
  2468. string_cleanup(&info->itext_strings[i]);
  2469. }
  2470. lodepng_free(info->itext_keys);
  2471. lodepng_free(info->itext_langtags);
  2472. lodepng_free(info->itext_transkeys);
  2473. lodepng_free(info->itext_strings);
  2474. }
  2475. static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
  2476. size_t i = 0;
  2477. dest->itext_keys = 0;
  2478. dest->itext_langtags = 0;
  2479. dest->itext_transkeys = 0;
  2480. dest->itext_strings = 0;
  2481. dest->itext_num = 0;
  2482. for(i = 0; i != source->itext_num; ++i) {
  2483. CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
  2484. source->itext_transkeys[i], source->itext_strings[i]));
  2485. }
  2486. return 0;
  2487. }
  2488. void lodepng_clear_itext(LodePNGInfo* info) {
  2489. LodePNGIText_cleanup(info);
  2490. }
  2491. unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
  2492. const char* transkey, const char* str) {
  2493. char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
  2494. char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
  2495. char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
  2496. char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
  2497. if(!new_keys || !new_langtags || !new_transkeys || !new_strings) {
  2498. lodepng_free(new_keys);
  2499. lodepng_free(new_langtags);
  2500. lodepng_free(new_transkeys);
  2501. lodepng_free(new_strings);
  2502. return 83; /*alloc fail*/
  2503. }
  2504. ++info->itext_num;
  2505. info->itext_keys = new_keys;
  2506. info->itext_langtags = new_langtags;
  2507. info->itext_transkeys = new_transkeys;
  2508. info->itext_strings = new_strings;
  2509. info->itext_keys[info->itext_num - 1] = alloc_string(key);
  2510. info->itext_langtags[info->itext_num - 1] = alloc_string(langtag);
  2511. info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey);
  2512. info->itext_strings[info->itext_num - 1] = alloc_string(str);
  2513. return 0;
  2514. }
  2515. /* same as set but does not delete */
  2516. static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {
  2517. if(profile_size == 0) return 100; /*invalid ICC profile size*/
  2518. info->iccp_name = alloc_string(name);
  2519. info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size);
  2520. if(!info->iccp_name || !info->iccp_profile) return 83; /*alloc fail*/
  2521. lodepng_memcpy(info->iccp_profile, profile, profile_size);
  2522. info->iccp_profile_size = profile_size;
  2523. return 0; /*ok*/
  2524. }
  2525. unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {
  2526. if(info->iccp_name) lodepng_clear_icc(info);
  2527. info->iccp_defined = 1;
  2528. return lodepng_assign_icc(info, name, profile, profile_size);
  2529. }
  2530. void lodepng_clear_icc(LodePNGInfo* info) {
  2531. string_cleanup(&info->iccp_name);
  2532. lodepng_free(info->iccp_profile);
  2533. info->iccp_profile = NULL;
  2534. info->iccp_profile_size = 0;
  2535. info->iccp_defined = 0;
  2536. }
  2537. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  2538. void lodepng_info_init(LodePNGInfo* info) {
  2539. lodepng_color_mode_init(&info->color);
  2540. info->interlace_method = 0;
  2541. info->compression_method = 0;
  2542. info->filter_method = 0;
  2543. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  2544. info->background_defined = 0;
  2545. info->background_r = info->background_g = info->background_b = 0;
  2546. LodePNGText_init(info);
  2547. LodePNGIText_init(info);
  2548. info->time_defined = 0;
  2549. info->phys_defined = 0;
  2550. info->gama_defined = 0;
  2551. info->chrm_defined = 0;
  2552. info->srgb_defined = 0;
  2553. info->iccp_defined = 0;
  2554. info->iccp_name = NULL;
  2555. info->iccp_profile = NULL;
  2556. LodePNGUnknownChunks_init(info);
  2557. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  2558. }
  2559. void lodepng_info_cleanup(LodePNGInfo* info) {
  2560. lodepng_color_mode_cleanup(&info->color);
  2561. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  2562. LodePNGText_cleanup(info);
  2563. LodePNGIText_cleanup(info);
  2564. lodepng_clear_icc(info);
  2565. LodePNGUnknownChunks_cleanup(info);
  2566. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  2567. }
  2568. unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
  2569. lodepng_info_cleanup(dest);
  2570. *dest = *source;
  2571. lodepng_color_mode_init(&dest->color);
  2572. CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
  2573. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  2574. CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
  2575. CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
  2576. if(source->iccp_defined) {
  2577. CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size));
  2578. }
  2579. LodePNGUnknownChunks_init(dest);
  2580. CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
  2581. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  2582. return 0;
  2583. }
  2584. /* ////////////////////////////////////////////////////////////////////////// */
  2585. /*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
  2586. static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) {
  2587. unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
  2588. /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
  2589. unsigned p = index & m;
  2590. in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
  2591. in = in << (bits * (m - p));
  2592. if(p == 0) out[index * bits / 8u] = in;
  2593. else out[index * bits / 8u] |= in;
  2594. }
  2595. typedef struct ColorTree ColorTree;
  2596. /*
  2597. One node of a color tree
  2598. This is the data structure used to count the number of unique colors and to get a palette
  2599. index for a color. It's like an octree, but because the alpha channel is used too, each
  2600. node has 16 instead of 8 children.
  2601. */
  2602. struct ColorTree {
  2603. ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
  2604. int index; /*the payload. Only has a meaningful value if this is in the last level*/
  2605. };
  2606. static void color_tree_init(ColorTree* tree) {
  2607. int i;
  2608. for(i = 0; i != 16; ++i) tree->children[i] = 0;
  2609. tree->index = -1;
  2610. }
  2611. static void color_tree_cleanup(ColorTree* tree) {
  2612. int i;
  2613. for(i = 0; i != 16; ++i) {
  2614. if(tree->children[i]) {
  2615. color_tree_cleanup(tree->children[i]);
  2616. lodepng_free(tree->children[i]);
  2617. }
  2618. }
  2619. }
  2620. /*returns -1 if color not present, its index otherwise*/
  2621. static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  2622. int bit = 0;
  2623. for(bit = 0; bit < 8; ++bit) {
  2624. int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
  2625. if(!tree->children[i]) return -1;
  2626. else tree = tree->children[i];
  2627. }
  2628. return tree ? tree->index : -1;
  2629. }
  2630. #ifdef LODEPNG_COMPILE_ENCODER
  2631. static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  2632. return color_tree_get(tree, r, g, b, a) >= 0;
  2633. }
  2634. #endif /*LODEPNG_COMPILE_ENCODER*/
  2635. /*color is not allowed to already exist.
  2636. Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
  2637. static void color_tree_add(ColorTree* tree,
  2638. unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) {
  2639. int bit;
  2640. for(bit = 0; bit < 8; ++bit) {
  2641. int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
  2642. if(!tree->children[i]) {
  2643. tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
  2644. color_tree_init(tree->children[i]);
  2645. }
  2646. tree = tree->children[i];
  2647. }
  2648. tree->index = (int)index;
  2649. }
  2650. /*put a pixel, given its RGBA color, into image of any color type*/
  2651. static unsigned rgba8ToPixel(unsigned char* out, size_t i,
  2652. const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
  2653. unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
  2654. if(mode->colortype == LCT_GREY) {
  2655. unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
  2656. if(mode->bitdepth == 8) out[i] = gray;
  2657. else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray;
  2658. else {
  2659. /*take the most significant bits of gray*/
  2660. gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u);
  2661. addColorBits(out, i, mode->bitdepth, gray);
  2662. }
  2663. } else if(mode->colortype == LCT_RGB) {
  2664. if(mode->bitdepth == 8) {
  2665. out[i * 3 + 0] = r;
  2666. out[i * 3 + 1] = g;
  2667. out[i * 3 + 2] = b;
  2668. } else {
  2669. out[i * 6 + 0] = out[i * 6 + 1] = r;
  2670. out[i * 6 + 2] = out[i * 6 + 3] = g;
  2671. out[i * 6 + 4] = out[i * 6 + 5] = b;
  2672. }
  2673. } else if(mode->colortype == LCT_PALETTE) {
  2674. int index = color_tree_get(tree, r, g, b, a);
  2675. if(index < 0) return 82; /*color not in palette*/
  2676. if(mode->bitdepth == 8) out[i] = index;
  2677. else addColorBits(out, i, mode->bitdepth, (unsigned)index);
  2678. } else if(mode->colortype == LCT_GREY_ALPHA) {
  2679. unsigned char gray = r; /*((unsigned short)r + g + b) / 3u;*/
  2680. if(mode->bitdepth == 8) {
  2681. out[i * 2 + 0] = gray;
  2682. out[i * 2 + 1] = a;
  2683. } else if(mode->bitdepth == 16) {
  2684. out[i * 4 + 0] = out[i * 4 + 1] = gray;
  2685. out[i * 4 + 2] = out[i * 4 + 3] = a;
  2686. }
  2687. } else if(mode->colortype == LCT_RGBA) {
  2688. if(mode->bitdepth == 8) {
  2689. out[i * 4 + 0] = r;
  2690. out[i * 4 + 1] = g;
  2691. out[i * 4 + 2] = b;
  2692. out[i * 4 + 3] = a;
  2693. } else {
  2694. out[i * 8 + 0] = out[i * 8 + 1] = r;
  2695. out[i * 8 + 2] = out[i * 8 + 3] = g;
  2696. out[i * 8 + 4] = out[i * 8 + 5] = b;
  2697. out[i * 8 + 6] = out[i * 8 + 7] = a;
  2698. }
  2699. }
  2700. return 0; /*no error*/
  2701. }
  2702. /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
  2703. static void rgba16ToPixel(unsigned char* out, size_t i,
  2704. const LodePNGColorMode* mode,
  2705. unsigned short r, unsigned short g, unsigned short b, unsigned short a) {
  2706. if(mode->colortype == LCT_GREY) {
  2707. unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
  2708. out[i * 2 + 0] = (gray >> 8) & 255;
  2709. out[i * 2 + 1] = gray & 255;
  2710. } else if(mode->colortype == LCT_RGB) {
  2711. out[i * 6 + 0] = (r >> 8) & 255;
  2712. out[i * 6 + 1] = r & 255;
  2713. out[i * 6 + 2] = (g >> 8) & 255;
  2714. out[i * 6 + 3] = g & 255;
  2715. out[i * 6 + 4] = (b >> 8) & 255;
  2716. out[i * 6 + 5] = b & 255;
  2717. } else if(mode->colortype == LCT_GREY_ALPHA) {
  2718. unsigned short gray = r; /*((unsigned)r + g + b) / 3u;*/
  2719. out[i * 4 + 0] = (gray >> 8) & 255;
  2720. out[i * 4 + 1] = gray & 255;
  2721. out[i * 4 + 2] = (a >> 8) & 255;
  2722. out[i * 4 + 3] = a & 255;
  2723. } else if(mode->colortype == LCT_RGBA) {
  2724. out[i * 8 + 0] = (r >> 8) & 255;
  2725. out[i * 8 + 1] = r & 255;
  2726. out[i * 8 + 2] = (g >> 8) & 255;
  2727. out[i * 8 + 3] = g & 255;
  2728. out[i * 8 + 4] = (b >> 8) & 255;
  2729. out[i * 8 + 5] = b & 255;
  2730. out[i * 8 + 6] = (a >> 8) & 255;
  2731. out[i * 8 + 7] = a & 255;
  2732. }
  2733. }
  2734. /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
  2735. static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
  2736. unsigned char* b, unsigned char* a,
  2737. const unsigned char* in, size_t i,
  2738. const LodePNGColorMode* mode) {
  2739. if(mode->colortype == LCT_GREY) {
  2740. if(mode->bitdepth == 8) {
  2741. *r = *g = *b = in[i];
  2742. if(mode->key_defined && *r == mode->key_r) *a = 0;
  2743. else *a = 255;
  2744. } else if(mode->bitdepth == 16) {
  2745. *r = *g = *b = in[i * 2 + 0];
  2746. if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
  2747. else *a = 255;
  2748. } else {
  2749. unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
  2750. size_t j = i * mode->bitdepth;
  2751. unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
  2752. *r = *g = *b = (value * 255) / highest;
  2753. if(mode->key_defined && value == mode->key_r) *a = 0;
  2754. else *a = 255;
  2755. }
  2756. } else if(mode->colortype == LCT_RGB) {
  2757. if(mode->bitdepth == 8) {
  2758. *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
  2759. if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
  2760. else *a = 255;
  2761. } else {
  2762. *r = in[i * 6 + 0];
  2763. *g = in[i * 6 + 2];
  2764. *b = in[i * 6 + 4];
  2765. if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
  2766. && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
  2767. && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
  2768. else *a = 255;
  2769. }
  2770. } else if(mode->colortype == LCT_PALETTE) {
  2771. unsigned index;
  2772. if(mode->bitdepth == 8) index = in[i];
  2773. else {
  2774. size_t j = i * mode->bitdepth;
  2775. index = readBitsFromReversedStream(&j, in, mode->bitdepth);
  2776. }
  2777. /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  2778. *r = mode->palette[index * 4 + 0];
  2779. *g = mode->palette[index * 4 + 1];
  2780. *b = mode->palette[index * 4 + 2];
  2781. *a = mode->palette[index * 4 + 3];
  2782. } else if(mode->colortype == LCT_GREY_ALPHA) {
  2783. if(mode->bitdepth == 8) {
  2784. *r = *g = *b = in[i * 2 + 0];
  2785. *a = in[i * 2 + 1];
  2786. } else {
  2787. *r = *g = *b = in[i * 4 + 0];
  2788. *a = in[i * 4 + 2];
  2789. }
  2790. } else if(mode->colortype == LCT_RGBA) {
  2791. if(mode->bitdepth == 8) {
  2792. *r = in[i * 4 + 0];
  2793. *g = in[i * 4 + 1];
  2794. *b = in[i * 4 + 2];
  2795. *a = in[i * 4 + 3];
  2796. } else {
  2797. *r = in[i * 8 + 0];
  2798. *g = in[i * 8 + 2];
  2799. *b = in[i * 8 + 4];
  2800. *a = in[i * 8 + 6];
  2801. }
  2802. }
  2803. }
  2804. /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
  2805. mode test cases, optimized to convert the colors much faster, when converting
  2806. to the common case of RGBA with 8 bit per channel. buffer must be RGBA with
  2807. enough memory.*/
  2808. static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,
  2809. const unsigned char* LODEPNG_RESTRICT in,
  2810. const LodePNGColorMode* mode) {
  2811. unsigned num_channels = 4;
  2812. size_t i;
  2813. if(mode->colortype == LCT_GREY) {
  2814. if(mode->bitdepth == 8) {
  2815. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2816. buffer[0] = buffer[1] = buffer[2] = in[i];
  2817. buffer[3] = 255;
  2818. }
  2819. if(mode->key_defined) {
  2820. buffer -= numpixels * num_channels;
  2821. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2822. if(buffer[0] == mode->key_r) buffer[3] = 0;
  2823. }
  2824. }
  2825. } else if(mode->bitdepth == 16) {
  2826. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2827. buffer[0] = buffer[1] = buffer[2] = in[i * 2];
  2828. buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
  2829. }
  2830. } else {
  2831. unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
  2832. size_t j = 0;
  2833. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2834. unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
  2835. buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
  2836. buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
  2837. }
  2838. }
  2839. } else if(mode->colortype == LCT_RGB) {
  2840. if(mode->bitdepth == 8) {
  2841. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2842. lodepng_memcpy(buffer, &in[i * 3], 3);
  2843. buffer[3] = 255;
  2844. }
  2845. if(mode->key_defined) {
  2846. buffer -= numpixels * num_channels;
  2847. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2848. if(buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0;
  2849. }
  2850. }
  2851. } else {
  2852. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2853. buffer[0] = in[i * 6 + 0];
  2854. buffer[1] = in[i * 6 + 2];
  2855. buffer[2] = in[i * 6 + 4];
  2856. buffer[3] = mode->key_defined
  2857. && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
  2858. && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
  2859. && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
  2860. }
  2861. }
  2862. } else if(mode->colortype == LCT_PALETTE) {
  2863. if(mode->bitdepth == 8) {
  2864. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2865. unsigned index = in[i];
  2866. /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  2867. lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
  2868. }
  2869. } else {
  2870. size_t j = 0;
  2871. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2872. unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
  2873. /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  2874. lodepng_memcpy(buffer, &mode->palette[index * 4], 4);
  2875. }
  2876. }
  2877. } else if(mode->colortype == LCT_GREY_ALPHA) {
  2878. if(mode->bitdepth == 8) {
  2879. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2880. buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
  2881. buffer[3] = in[i * 2 + 1];
  2882. }
  2883. } else {
  2884. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2885. buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
  2886. buffer[3] = in[i * 4 + 2];
  2887. }
  2888. }
  2889. } else if(mode->colortype == LCT_RGBA) {
  2890. if(mode->bitdepth == 8) {
  2891. lodepng_memcpy(buffer, in, numpixels * 4);
  2892. } else {
  2893. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2894. buffer[0] = in[i * 8 + 0];
  2895. buffer[1] = in[i * 8 + 2];
  2896. buffer[2] = in[i * 8 + 4];
  2897. buffer[3] = in[i * 8 + 6];
  2898. }
  2899. }
  2900. }
  2901. }
  2902. /*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/
  2903. static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels,
  2904. const unsigned char* LODEPNG_RESTRICT in,
  2905. const LodePNGColorMode* mode) {
  2906. const unsigned num_channels = 3;
  2907. size_t i;
  2908. if(mode->colortype == LCT_GREY) {
  2909. if(mode->bitdepth == 8) {
  2910. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2911. buffer[0] = buffer[1] = buffer[2] = in[i];
  2912. }
  2913. } else if(mode->bitdepth == 16) {
  2914. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2915. buffer[0] = buffer[1] = buffer[2] = in[i * 2];
  2916. }
  2917. } else {
  2918. unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
  2919. size_t j = 0;
  2920. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2921. unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
  2922. buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
  2923. }
  2924. }
  2925. } else if(mode->colortype == LCT_RGB) {
  2926. if(mode->bitdepth == 8) {
  2927. lodepng_memcpy(buffer, in, numpixels * 3);
  2928. } else {
  2929. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2930. buffer[0] = in[i * 6 + 0];
  2931. buffer[1] = in[i * 6 + 2];
  2932. buffer[2] = in[i * 6 + 4];
  2933. }
  2934. }
  2935. } else if(mode->colortype == LCT_PALETTE) {
  2936. if(mode->bitdepth == 8) {
  2937. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2938. unsigned index = in[i];
  2939. /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  2940. lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
  2941. }
  2942. } else {
  2943. size_t j = 0;
  2944. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2945. unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth);
  2946. /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/
  2947. lodepng_memcpy(buffer, &mode->palette[index * 4], 3);
  2948. }
  2949. }
  2950. } else if(mode->colortype == LCT_GREY_ALPHA) {
  2951. if(mode->bitdepth == 8) {
  2952. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2953. buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
  2954. }
  2955. } else {
  2956. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2957. buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
  2958. }
  2959. }
  2960. } else if(mode->colortype == LCT_RGBA) {
  2961. if(mode->bitdepth == 8) {
  2962. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2963. lodepng_memcpy(buffer, &in[i * 4], 3);
  2964. }
  2965. } else {
  2966. for(i = 0; i != numpixels; ++i, buffer += num_channels) {
  2967. buffer[0] = in[i * 8 + 0];
  2968. buffer[1] = in[i * 8 + 2];
  2969. buffer[2] = in[i * 8 + 4];
  2970. }
  2971. }
  2972. }
  2973. }
  2974. /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
  2975. given color type, but the given color type must be 16-bit itself.*/
  2976. static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
  2977. const unsigned char* in, size_t i, const LodePNGColorMode* mode) {
  2978. if(mode->colortype == LCT_GREY) {
  2979. *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
  2980. if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
  2981. else *a = 65535;
  2982. } else if(mode->colortype == LCT_RGB) {
  2983. *r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
  2984. *g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
  2985. *b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
  2986. if(mode->key_defined
  2987. && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
  2988. && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
  2989. && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
  2990. else *a = 65535;
  2991. } else if(mode->colortype == LCT_GREY_ALPHA) {
  2992. *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
  2993. *a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
  2994. } else if(mode->colortype == LCT_RGBA) {
  2995. *r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
  2996. *g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
  2997. *b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
  2998. *a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
  2999. }
  3000. }
  3001. unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
  3002. const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
  3003. unsigned w, unsigned h) {
  3004. size_t i;
  3005. ColorTree tree;
  3006. size_t numpixels = (size_t)w * (size_t)h;
  3007. unsigned error = 0;
  3008. if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) {
  3009. return 107; /* error: must provide palette if input mode is palette */
  3010. }
  3011. if(lodepng_color_mode_equal(mode_out, mode_in)) {
  3012. size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
  3013. for(i = 0; i != numbytes; ++i) out[i] = in[i];
  3014. return 0;
  3015. }
  3016. if(mode_out->colortype == LCT_PALETTE) {
  3017. size_t palettesize = mode_out->palettesize;
  3018. const unsigned char* palette = mode_out->palette;
  3019. size_t palsize = (size_t)1u << mode_out->bitdepth;
  3020. /*if the user specified output palette but did not give the values, assume
  3021. they want the values of the input color type (assuming that one is palette).
  3022. Note that we never create a new palette ourselves.*/
  3023. if(palettesize == 0) {
  3024. palettesize = mode_in->palettesize;
  3025. palette = mode_in->palette;
  3026. /*if the input was also palette with same bitdepth, then the color types are also
  3027. equal, so copy literally. This to preserve the exact indices that were in the PNG
  3028. even in case there are duplicate colors in the palette.*/
  3029. if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) {
  3030. size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
  3031. for(i = 0; i != numbytes; ++i) out[i] = in[i];
  3032. return 0;
  3033. }
  3034. }
  3035. if(palettesize < palsize) palsize = palettesize;
  3036. color_tree_init(&tree);
  3037. for(i = 0; i != palsize; ++i) {
  3038. const unsigned char* p = &palette[i * 4];
  3039. color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i);
  3040. }
  3041. }
  3042. if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) {
  3043. for(i = 0; i != numpixels; ++i) {
  3044. unsigned short r = 0, g = 0, b = 0, a = 0;
  3045. getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  3046. rgba16ToPixel(out, i, mode_out, r, g, b, a);
  3047. }
  3048. } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) {
  3049. getPixelColorsRGBA8(out, numpixels, in, mode_in);
  3050. } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) {
  3051. getPixelColorsRGB8(out, numpixels, in, mode_in);
  3052. } else {
  3053. unsigned char r = 0, g = 0, b = 0, a = 0;
  3054. for(i = 0; i != numpixels; ++i) {
  3055. getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
  3056. error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
  3057. if (error) break;
  3058. }
  3059. }
  3060. if(mode_out->colortype == LCT_PALETTE) {
  3061. color_tree_cleanup(&tree);
  3062. }
  3063. return error;
  3064. }
  3065. /* Converts a single rgb color without alpha from one type to another, color bits truncated to
  3066. their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow
  3067. function, do not use to process all pixels of an image. Alpha channel not supported on purpose:
  3068. this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the
  3069. specification it looks like bKGD should ignore the alpha values of the palette since it can use
  3070. any palette index but doesn't have an alpha channel. Idem with ignoring color key. */
  3071. unsigned lodepng_convert_rgb(
  3072. unsigned* r_out, unsigned* g_out, unsigned* b_out,
  3073. unsigned r_in, unsigned g_in, unsigned b_in,
  3074. const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) {
  3075. unsigned r = 0, g = 0, b = 0;
  3076. unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/
  3077. unsigned shift = 16 - mode_out->bitdepth;
  3078. if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) {
  3079. r = g = b = r_in * mul;
  3080. } else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) {
  3081. r = r_in * mul;
  3082. g = g_in * mul;
  3083. b = b_in * mul;
  3084. } else if(mode_in->colortype == LCT_PALETTE) {
  3085. if(r_in >= mode_in->palettesize) return 82;
  3086. r = mode_in->palette[r_in * 4 + 0] * 257u;
  3087. g = mode_in->palette[r_in * 4 + 1] * 257u;
  3088. b = mode_in->palette[r_in * 4 + 2] * 257u;
  3089. } else {
  3090. return 31;
  3091. }
  3092. /* now convert to output format */
  3093. if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) {
  3094. *r_out = r >> shift ;
  3095. } else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) {
  3096. *r_out = r >> shift ;
  3097. *g_out = g >> shift ;
  3098. *b_out = b >> shift ;
  3099. } else if(mode_out->colortype == LCT_PALETTE) {
  3100. unsigned i;
  3101. /* a 16-bit color cannot be in the palette */
  3102. if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82;
  3103. for(i = 0; i < mode_out->palettesize; i++) {
  3104. unsigned j = i * 4;
  3105. if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] &&
  3106. (b >> 8) == mode_out->palette[j + 2]) {
  3107. *r_out = i;
  3108. return 0;
  3109. }
  3110. }
  3111. return 82;
  3112. } else {
  3113. return 31;
  3114. }
  3115. return 0;
  3116. }
  3117. #ifdef LODEPNG_COMPILE_ENCODER
  3118. void lodepng_color_stats_init(LodePNGColorStats* stats) {
  3119. /*stats*/
  3120. stats->colored = 0;
  3121. stats->key = 0;
  3122. stats->key_r = stats->key_g = stats->key_b = 0;
  3123. stats->alpha = 0;
  3124. stats->numcolors = 0;
  3125. stats->bits = 1;
  3126. stats->numpixels = 0;
  3127. /*settings*/
  3128. stats->allow_palette = 1;
  3129. stats->allow_greyscale = 1;
  3130. }
  3131. /*function used for debug purposes with C++*/
  3132. /*void printColorStats(LodePNGColorStats* p) {
  3133. std::cout << "colored: " << (int)p->colored << ", ";
  3134. std::cout << "key: " << (int)p->key << ", ";
  3135. std::cout << "key_r: " << (int)p->key_r << ", ";
  3136. std::cout << "key_g: " << (int)p->key_g << ", ";
  3137. std::cout << "key_b: " << (int)p->key_b << ", ";
  3138. std::cout << "alpha: " << (int)p->alpha << ", ";
  3139. std::cout << "numcolors: " << (int)p->numcolors << ", ";
  3140. std::cout << "bits: " << (int)p->bits << std::endl;
  3141. }*/
  3142. /*Returns how many bits needed to represent given value (max 8 bit)*/
  3143. static unsigned getValueRequiredBits(unsigned char value) {
  3144. if(value == 0 || value == 255) return 1;
  3145. /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
  3146. if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
  3147. return 8;
  3148. }
  3149. /*stats must already have been inited. */
  3150. void lodepng_compute_color_stats(LodePNGColorStats* stats,
  3151. const unsigned char* in, unsigned w, unsigned h,
  3152. const LodePNGColorMode* mode_in) {
  3153. size_t i;
  3154. ColorTree tree;
  3155. size_t numpixels = (size_t)w * (size_t)h;
  3156. /* mark things as done already if it would be impossible to have a more expensive case */
  3157. unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0;
  3158. unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1;
  3159. unsigned numcolors_done = 0;
  3160. unsigned bpp = lodepng_get_bpp(mode_in);
  3161. unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0;
  3162. unsigned sixteen = 0; /* whether the input image is 16 bit */
  3163. unsigned maxnumcolors = 257;
  3164. if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp));
  3165. stats->numpixels += numpixels;
  3166. /*if palette not allowed, no need to compute numcolors*/
  3167. if(!stats->allow_palette) numcolors_done = 1;
  3168. color_tree_init(&tree);
  3169. /*If the stats was already filled in from previous data, fill its palette in tree
  3170. and mark things as done already if we know they are the most expensive case already*/
  3171. if(stats->alpha) alpha_done = 1;
  3172. if(stats->colored) colored_done = 1;
  3173. if(stats->bits == 16) numcolors_done = 1;
  3174. if(stats->bits >= bpp) bits_done = 1;
  3175. if(stats->numcolors >= maxnumcolors) numcolors_done = 1;
  3176. if(!numcolors_done) {
  3177. for(i = 0; i < stats->numcolors; i++) {
  3178. const unsigned char* color = &stats->palette[i * 4];
  3179. color_tree_add(&tree, color[0], color[1], color[2], color[3], i);
  3180. }
  3181. }
  3182. /*Check if the 16-bit input is truly 16-bit*/
  3183. if(mode_in->bitdepth == 16 && !sixteen) {
  3184. unsigned short r, g, b, a;
  3185. for(i = 0; i != numpixels; ++i) {
  3186. getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  3187. if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
  3188. (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ {
  3189. stats->bits = 16;
  3190. sixteen = 1;
  3191. bits_done = 1;
  3192. numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
  3193. break;
  3194. }
  3195. }
  3196. }
  3197. if(sixteen) {
  3198. unsigned short r = 0, g = 0, b = 0, a = 0;
  3199. for(i = 0; i != numpixels; ++i) {
  3200. getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  3201. if(!colored_done && (r != g || r != b)) {
  3202. stats->colored = 1;
  3203. colored_done = 1;
  3204. }
  3205. if(!alpha_done) {
  3206. unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
  3207. if(a != 65535 && (a != 0 || (stats->key && !matchkey))) {
  3208. stats->alpha = 1;
  3209. stats->key = 0;
  3210. alpha_done = 1;
  3211. } else if(a == 0 && !stats->alpha && !stats->key) {
  3212. stats->key = 1;
  3213. stats->key_r = r;
  3214. stats->key_g = g;
  3215. stats->key_b = b;
  3216. } else if(a == 65535 && stats->key && matchkey) {
  3217. /* Color key cannot be used if an opaque pixel also has that RGB color. */
  3218. stats->alpha = 1;
  3219. stats->key = 0;
  3220. alpha_done = 1;
  3221. }
  3222. }
  3223. if(alpha_done && numcolors_done && colored_done && bits_done) break;
  3224. }
  3225. if(stats->key && !stats->alpha) {
  3226. for(i = 0; i != numpixels; ++i) {
  3227. getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
  3228. if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
  3229. /* Color key cannot be used if an opaque pixel also has that RGB color. */
  3230. stats->alpha = 1;
  3231. stats->key = 0;
  3232. alpha_done = 1;
  3233. }
  3234. }
  3235. }
  3236. } else /* < 16-bit */ {
  3237. unsigned char r = 0, g = 0, b = 0, a = 0;
  3238. for(i = 0; i != numpixels; ++i) {
  3239. getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
  3240. if(!bits_done && stats->bits < 8) {
  3241. /*only r is checked, < 8 bits is only relevant for grayscale*/
  3242. unsigned bits = getValueRequiredBits(r);
  3243. if(bits > stats->bits) stats->bits = bits;
  3244. }
  3245. bits_done = (stats->bits >= bpp);
  3246. if(!colored_done && (r != g || r != b)) {
  3247. stats->colored = 1;
  3248. colored_done = 1;
  3249. if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
  3250. }
  3251. if(!alpha_done) {
  3252. unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b);
  3253. if(a != 255 && (a != 0 || (stats->key && !matchkey))) {
  3254. stats->alpha = 1;
  3255. stats->key = 0;
  3256. alpha_done = 1;
  3257. if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  3258. } else if(a == 0 && !stats->alpha && !stats->key) {
  3259. stats->key = 1;
  3260. stats->key_r = r;
  3261. stats->key_g = g;
  3262. stats->key_b = b;
  3263. } else if(a == 255 && stats->key && matchkey) {
  3264. /* Color key cannot be used if an opaque pixel also has that RGB color. */
  3265. stats->alpha = 1;
  3266. stats->key = 0;
  3267. alpha_done = 1;
  3268. if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  3269. }
  3270. }
  3271. if(!numcolors_done) {
  3272. if(!color_tree_has(&tree, r, g, b, a)) {
  3273. color_tree_add(&tree, r, g, b, a, stats->numcolors);
  3274. if(stats->numcolors < 256) {
  3275. unsigned char* p = stats->palette;
  3276. unsigned n = stats->numcolors;
  3277. p[n * 4 + 0] = r;
  3278. p[n * 4 + 1] = g;
  3279. p[n * 4 + 2] = b;
  3280. p[n * 4 + 3] = a;
  3281. }
  3282. ++stats->numcolors;
  3283. numcolors_done = stats->numcolors >= maxnumcolors;
  3284. }
  3285. }
  3286. if(alpha_done && numcolors_done && colored_done && bits_done) break;
  3287. }
  3288. if(stats->key && !stats->alpha) {
  3289. for(i = 0; i != numpixels; ++i) {
  3290. getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
  3291. if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) {
  3292. /* Color key cannot be used if an opaque pixel also has that RGB color. */
  3293. stats->alpha = 1;
  3294. stats->key = 0;
  3295. alpha_done = 1;
  3296. if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  3297. }
  3298. }
  3299. }
  3300. /*make the stats's key always 16-bit for consistency - repeat each byte twice*/
  3301. stats->key_r += (stats->key_r << 8);
  3302. stats->key_g += (stats->key_g << 8);
  3303. stats->key_b += (stats->key_b << 8);
  3304. }
  3305. color_tree_cleanup(&tree);
  3306. }
  3307. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  3308. /*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit
  3309. (with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for
  3310. all pixels of an image but only for a few additional values. */
  3311. static void lodepng_color_stats_add(LodePNGColorStats* stats,
  3312. unsigned r, unsigned g, unsigned b, unsigned a) {
  3313. unsigned char image[8];
  3314. LodePNGColorMode mode;
  3315. lodepng_color_mode_init(&mode);
  3316. image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g;
  3317. image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a;
  3318. mode.bitdepth = 16;
  3319. mode.colortype = LCT_RGBA;
  3320. lodepng_compute_color_stats(stats, image, 1, 1, &mode);
  3321. lodepng_color_mode_cleanup(&mode);
  3322. }
  3323. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  3324. /*Computes a minimal PNG color model that can contain all colors as indicated by the stats.
  3325. The stats should be computed with lodepng_compute_color_stats.
  3326. mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant.
  3327. Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image,
  3328. e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ...
  3329. This is used if auto_convert is enabled (it is by default).
  3330. */
  3331. static unsigned auto_choose_color(LodePNGColorMode* mode_out,
  3332. const LodePNGColorMode* mode_in,
  3333. const LodePNGColorStats* stats) {
  3334. unsigned error = 0;
  3335. unsigned palettebits;
  3336. size_t i, n;
  3337. size_t numpixels = stats->numpixels;
  3338. unsigned palette_ok, gray_ok;
  3339. unsigned alpha = stats->alpha;
  3340. unsigned key = stats->key;
  3341. unsigned bits = stats->bits;
  3342. mode_out->key_defined = 0;
  3343. if(key && numpixels <= 16) {
  3344. alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
  3345. key = 0;
  3346. if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
  3347. }
  3348. gray_ok = !stats->colored;
  3349. if(!stats->allow_greyscale) gray_ok = 0;
  3350. if(!gray_ok && bits < 8) bits = 8;
  3351. n = stats->numcolors;
  3352. palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
  3353. palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/
  3354. if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
  3355. if(gray_ok && !alpha && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/
  3356. if(!stats->allow_palette) palette_ok = 0;
  3357. if(palette_ok) {
  3358. const unsigned char* p = stats->palette;
  3359. lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
  3360. for(i = 0; i != stats->numcolors; ++i) {
  3361. error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
  3362. if(error) break;
  3363. }
  3364. mode_out->colortype = LCT_PALETTE;
  3365. mode_out->bitdepth = palettebits;
  3366. if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
  3367. && mode_in->bitdepth == mode_out->bitdepth) {
  3368. /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
  3369. lodepng_color_mode_cleanup(mode_out);
  3370. lodepng_color_mode_copy(mode_out, mode_in);
  3371. }
  3372. } else /*8-bit or 16-bit per channel*/ {
  3373. mode_out->bitdepth = bits;
  3374. mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA)
  3375. : (gray_ok ? LCT_GREY : LCT_RGB);
  3376. if(key) {
  3377. unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/
  3378. mode_out->key_r = stats->key_r & mask;
  3379. mode_out->key_g = stats->key_g & mask;
  3380. mode_out->key_b = stats->key_b & mask;
  3381. mode_out->key_defined = 1;
  3382. }
  3383. }
  3384. return error;
  3385. }
  3386. #endif /* #ifdef LODEPNG_COMPILE_ENCODER */
  3387. /*
  3388. Paeth predictor, used by PNG filter type 4
  3389. The parameters are of type short, but should come from unsigned chars, the shorts
  3390. are only needed to make the paeth calculation correct.
  3391. */
  3392. static unsigned char paethPredictor(short a, short b, short c) {
  3393. short pa = LODEPNG_ABS(b - c);
  3394. short pb = LODEPNG_ABS(a - c);
  3395. short pc = LODEPNG_ABS(a + b - c - c);
  3396. /* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */
  3397. if(pb < pa) { a = b; pa = pb; }
  3398. return (pc < pa) ? c : a;
  3399. }
  3400. /*shared values used by multiple Adam7 related functions*/
  3401. static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
  3402. static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
  3403. static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
  3404. static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
  3405. /*
  3406. Outputs various dimensions and positions in the image related to the Adam7 reduced images.
  3407. passw: output containing the width of the 7 passes
  3408. passh: output containing the height of the 7 passes
  3409. filter_passstart: output containing the index of the start and end of each
  3410. reduced image with filter bytes
  3411. padded_passstart output containing the index of the start and end of each
  3412. reduced image when without filter bytes but with padded scanlines
  3413. passstart: output containing the index of the start and end of each reduced
  3414. image without padding between scanlines, but still padding between the images
  3415. w, h: width and height of non-interlaced image
  3416. bpp: bits per pixel
  3417. "padded" is only relevant if bpp is less than 8 and a scanline or image does not
  3418. end at a full byte
  3419. */
  3420. static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
  3421. size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) {
  3422. /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
  3423. unsigned i;
  3424. /*calculate width and height in pixels of each pass*/
  3425. for(i = 0; i != 7; ++i) {
  3426. passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
  3427. passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
  3428. if(passw[i] == 0) passh[i] = 0;
  3429. if(passh[i] == 0) passw[i] = 0;
  3430. }
  3431. filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
  3432. for(i = 0; i != 7; ++i) {
  3433. /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
  3434. filter_passstart[i + 1] = filter_passstart[i]
  3435. + ((passw[i] && passh[i]) ? passh[i] * (1u + (passw[i] * bpp + 7u) / 8u) : 0);
  3436. /*bits padded if needed to fill full byte at end of each scanline*/
  3437. padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7u) / 8u);
  3438. /*only padded at end of reduced image*/
  3439. passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u;
  3440. }
  3441. }
  3442. #ifdef LODEPNG_COMPILE_DECODER
  3443. /* ////////////////////////////////////////////////////////////////////////// */
  3444. /* / PNG Decoder / */
  3445. /* ////////////////////////////////////////////////////////////////////////// */
  3446. /*read the information from the header and store it in the LodePNGInfo. return value is error*/
  3447. unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
  3448. const unsigned char* in, size_t insize) {
  3449. unsigned width, height;
  3450. LodePNGInfo* info = &state->info_png;
  3451. if(insize == 0 || in == 0) {
  3452. CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
  3453. }
  3454. if(insize < 33) {
  3455. CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
  3456. }
  3457. /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
  3458. /* TODO: remove this. One should use a new LodePNGState for new sessions */
  3459. lodepng_info_cleanup(info);
  3460. lodepng_info_init(info);
  3461. if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
  3462. || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {
  3463. CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
  3464. }
  3465. if(lodepng_chunk_length(in + 8) != 13) {
  3466. CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
  3467. }
  3468. if(!lodepng_chunk_type_equals(in + 8, "IHDR")) {
  3469. CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
  3470. }
  3471. /*read the values given in the header*/
  3472. width = lodepng_read32bitInt(&in[16]);
  3473. height = lodepng_read32bitInt(&in[20]);
  3474. /*TODO: remove the undocumented feature that allows to give null pointers to width or height*/
  3475. if(w) *w = width;
  3476. if(h) *h = height;
  3477. info->color.bitdepth = in[24];
  3478. info->color.colortype = (LodePNGColorType)in[25];
  3479. info->compression_method = in[26];
  3480. info->filter_method = in[27];
  3481. info->interlace_method = in[28];
  3482. /*errors returned only after the parsing so other values are still output*/
  3483. /*error: invalid image size*/
  3484. if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93);
  3485. /*error: invalid colortype or bitdepth combination*/
  3486. state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
  3487. if(state->error) return state->error;
  3488. /*error: only compression method 0 is allowed in the specification*/
  3489. if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
  3490. /*error: only filter method 0 is allowed in the specification*/
  3491. if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
  3492. /*error: only interlace methods 0 and 1 exist in the specification*/
  3493. if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
  3494. if(!state->decoder.ignore_crc) {
  3495. unsigned CRC = lodepng_read32bitInt(&in[29]);
  3496. unsigned checksum = lodepng_crc32(&in[12], 17);
  3497. if(CRC != checksum) {
  3498. CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
  3499. }
  3500. }
  3501. return state->error;
  3502. }
  3503. static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
  3504. size_t bytewidth, unsigned char filterType, size_t length) {
  3505. /*
  3506. For PNG filter method 0
  3507. unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
  3508. the filter works byte per byte (bytewidth = 1)
  3509. precon is the previous unfiltered scanline, recon the result, scanline the current one
  3510. the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
  3511. recon and scanline MAY be the same memory address! precon must be disjoint.
  3512. */
  3513. size_t i;
  3514. switch(filterType) {
  3515. case 0:
  3516. for(i = 0; i != length; ++i) recon[i] = scanline[i];
  3517. break;
  3518. case 1:
  3519. for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
  3520. for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
  3521. break;
  3522. case 2:
  3523. if(precon) {
  3524. for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
  3525. } else {
  3526. for(i = 0; i != length; ++i) recon[i] = scanline[i];
  3527. }
  3528. break;
  3529. case 3:
  3530. if(precon) {
  3531. for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u);
  3532. for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1u);
  3533. } else {
  3534. for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
  3535. for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1u);
  3536. }
  3537. break;
  3538. case 4:
  3539. if(precon) {
  3540. for(i = 0; i != bytewidth; ++i) {
  3541. recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
  3542. }
  3543. /* Unroll independent paths of the paeth predictor. A 6x and 8x version would also be possible but that
  3544. adds too much code. Whether this actually speeds anything up at all depends on compiler and settings. */
  3545. if(bytewidth >= 4) {
  3546. for(; i + 3 < length; i += 4) {
  3547. size_t j = i - bytewidth;
  3548. unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3];
  3549. unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3];
  3550. unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3];
  3551. unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2], q3 = precon[j + 3];
  3552. recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
  3553. recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
  3554. recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
  3555. recon[i + 3] = s3 + paethPredictor(r3, p3, q3);
  3556. }
  3557. } else if(bytewidth >= 3) {
  3558. for(; i + 2 < length; i += 3) {
  3559. size_t j = i - bytewidth;
  3560. unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2];
  3561. unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2];
  3562. unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2];
  3563. unsigned char q0 = precon[j + 0], q1 = precon[j + 1], q2 = precon[j + 2];
  3564. recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
  3565. recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
  3566. recon[i + 2] = s2 + paethPredictor(r2, p2, q2);
  3567. }
  3568. } else if(bytewidth >= 2) {
  3569. for(; i + 1 < length; i += 2) {
  3570. size_t j = i - bytewidth;
  3571. unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1];
  3572. unsigned char r0 = recon[j + 0], r1 = recon[j + 1];
  3573. unsigned char p0 = precon[i + 0], p1 = precon[i + 1];
  3574. unsigned char q0 = precon[j + 0], q1 = precon[j + 1];
  3575. recon[i + 0] = s0 + paethPredictor(r0, p0, q0);
  3576. recon[i + 1] = s1 + paethPredictor(r1, p1, q1);
  3577. }
  3578. }
  3579. for(; i != length; ++i) {
  3580. recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
  3581. }
  3582. } else {
  3583. for(i = 0; i != bytewidth; ++i) {
  3584. recon[i] = scanline[i];
  3585. }
  3586. for(i = bytewidth; i < length; ++i) {
  3587. /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
  3588. recon[i] = (scanline[i] + recon[i - bytewidth]);
  3589. }
  3590. }
  3591. break;
  3592. default: return 36; /*error: nonexistent filter type given*/
  3593. }
  3594. return 0;
  3595. }
  3596. static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
  3597. /*
  3598. For PNG filter method 0
  3599. this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
  3600. out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
  3601. w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
  3602. in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
  3603. */
  3604. unsigned y;
  3605. unsigned char* prevline = 0;
  3606. /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
  3607. size_t bytewidth = (bpp + 7u) / 8u;
  3608. size_t linebytes = (w * bpp + 7u) / 8u;
  3609. for(y = 0; y < h; ++y) {
  3610. size_t outindex = linebytes * y;
  3611. size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
  3612. unsigned char filterType = in[inindex];
  3613. CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
  3614. prevline = &out[outindex];
  3615. }
  3616. return 0;
  3617. }
  3618. /*
  3619. in: Adam7 interlaced image, with no padding bits between scanlines, but between
  3620. reduced images so that each reduced image starts at a byte.
  3621. out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
  3622. bpp: bits per pixel
  3623. out has the following size in bits: w * h * bpp.
  3624. in is possibly bigger due to padding bits between reduced images.
  3625. out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
  3626. (because that's likely a little bit faster)
  3627. NOTE: comments about padding bits are only relevant if bpp < 8
  3628. */
  3629. static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
  3630. unsigned passw[7], passh[7];
  3631. size_t filter_passstart[8], padded_passstart[8], passstart[8];
  3632. unsigned i;
  3633. Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  3634. if(bpp >= 8) {
  3635. for(i = 0; i != 7; ++i) {
  3636. unsigned x, y, b;
  3637. size_t bytewidth = bpp / 8u;
  3638. for(y = 0; y < passh[i]; ++y)
  3639. for(x = 0; x < passw[i]; ++x) {
  3640. size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
  3641. size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
  3642. for(b = 0; b < bytewidth; ++b) {
  3643. out[pixeloutstart + b] = in[pixelinstart + b];
  3644. }
  3645. }
  3646. }
  3647. } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
  3648. for(i = 0; i != 7; ++i) {
  3649. unsigned x, y, b;
  3650. unsigned ilinebits = bpp * passw[i];
  3651. unsigned olinebits = bpp * w;
  3652. size_t obp, ibp; /*bit pointers (for out and in buffer)*/
  3653. for(y = 0; y < passh[i]; ++y)
  3654. for(x = 0; x < passw[i]; ++x) {
  3655. ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
  3656. obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
  3657. for(b = 0; b < bpp; ++b) {
  3658. unsigned char bit = readBitFromReversedStream(&ibp, in);
  3659. setBitOfReversedStream(&obp, out, bit);
  3660. }
  3661. }
  3662. }
  3663. }
  3664. }
  3665. static void removePaddingBits(unsigned char* out, const unsigned char* in,
  3666. size_t olinebits, size_t ilinebits, unsigned h) {
  3667. /*
  3668. After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
  3669. to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
  3670. for the Adam7 code, the color convert code and the output to the user.
  3671. in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
  3672. have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
  3673. also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
  3674. only useful if (ilinebits - olinebits) is a value in the range 1..7
  3675. */
  3676. unsigned y;
  3677. size_t diff = ilinebits - olinebits;
  3678. size_t ibp = 0, obp = 0; /*input and output bit pointers*/
  3679. for(y = 0; y < h; ++y) {
  3680. size_t x;
  3681. for(x = 0; x < olinebits; ++x) {
  3682. unsigned char bit = readBitFromReversedStream(&ibp, in);
  3683. setBitOfReversedStream(&obp, out, bit);
  3684. }
  3685. ibp += diff;
  3686. }
  3687. }
  3688. /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
  3689. the IDAT chunks (with filter index bytes and possible padding bits)
  3690. return value is error*/
  3691. static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
  3692. unsigned w, unsigned h, const LodePNGInfo* info_png) {
  3693. /*
  3694. This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
  3695. Steps:
  3696. *) if no Adam7: 1) unfilter 2) remove padding bits (= possible extra bits per scanline if bpp < 8)
  3697. *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
  3698. NOTE: the in buffer will be overwritten with intermediate data!
  3699. */
  3700. unsigned bpp = lodepng_get_bpp(&info_png->color);
  3701. if(bpp == 0) return 31; /*error: invalid colortype*/
  3702. if(info_png->interlace_method == 0) {
  3703. if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
  3704. CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
  3705. removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h);
  3706. }
  3707. /*we can immediately filter into the out buffer, no other steps needed*/
  3708. else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
  3709. } else /*interlace_method is 1 (Adam7)*/ {
  3710. unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
  3711. unsigned i;
  3712. Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  3713. for(i = 0; i != 7; ++i) {
  3714. CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
  3715. /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
  3716. move bytes instead of bits or move not at all*/
  3717. if(bpp < 8) {
  3718. /*remove padding bits in scanlines; after this there still may be padding
  3719. bits between the different reduced images: each reduced image still starts nicely at a byte*/
  3720. removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
  3721. ((passw[i] * bpp + 7u) / 8u) * 8u, passh[i]);
  3722. }
  3723. }
  3724. Adam7_deinterlace(out, in, w, h, bpp);
  3725. }
  3726. return 0;
  3727. }
  3728. static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
  3729. unsigned pos = 0, i;
  3730. color->palettesize = chunkLength / 3u;
  3731. if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/
  3732. lodepng_color_mode_alloc_palette(color);
  3733. if(!color->palette && color->palettesize) {
  3734. color->palettesize = 0;
  3735. return 83; /*alloc fail*/
  3736. }
  3737. for(i = 0; i != color->palettesize; ++i) {
  3738. color->palette[4 * i + 0] = data[pos++]; /*R*/
  3739. color->palette[4 * i + 1] = data[pos++]; /*G*/
  3740. color->palette[4 * i + 2] = data[pos++]; /*B*/
  3741. color->palette[4 * i + 3] = 255; /*alpha*/
  3742. }
  3743. return 0; /* OK */
  3744. }
  3745. static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
  3746. unsigned i;
  3747. if(color->colortype == LCT_PALETTE) {
  3748. /*error: more alpha values given than there are palette entries*/
  3749. if(chunkLength > color->palettesize) return 39;
  3750. for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
  3751. } else if(color->colortype == LCT_GREY) {
  3752. /*error: this chunk must be 2 bytes for grayscale image*/
  3753. if(chunkLength != 2) return 30;
  3754. color->key_defined = 1;
  3755. color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
  3756. } else if(color->colortype == LCT_RGB) {
  3757. /*error: this chunk must be 6 bytes for RGB image*/
  3758. if(chunkLength != 6) return 41;
  3759. color->key_defined = 1;
  3760. color->key_r = 256u * data[0] + data[1];
  3761. color->key_g = 256u * data[2] + data[3];
  3762. color->key_b = 256u * data[4] + data[5];
  3763. }
  3764. else return 42; /*error: tRNS chunk not allowed for other color models*/
  3765. return 0; /* OK */
  3766. }
  3767. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  3768. /*background color chunk (bKGD)*/
  3769. static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  3770. if(info->color.colortype == LCT_PALETTE) {
  3771. /*error: this chunk must be 1 byte for indexed color image*/
  3772. if(chunkLength != 1) return 43;
  3773. /*error: invalid palette index, or maybe this chunk appeared before PLTE*/
  3774. if(data[0] >= info->color.palettesize) return 103;
  3775. info->background_defined = 1;
  3776. info->background_r = info->background_g = info->background_b = data[0];
  3777. } else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
  3778. /*error: this chunk must be 2 bytes for grayscale image*/
  3779. if(chunkLength != 2) return 44;
  3780. /*the values are truncated to bitdepth in the PNG file*/
  3781. info->background_defined = 1;
  3782. info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
  3783. } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
  3784. /*error: this chunk must be 6 bytes for grayscale image*/
  3785. if(chunkLength != 6) return 45;
  3786. /*the values are truncated to bitdepth in the PNG file*/
  3787. info->background_defined = 1;
  3788. info->background_r = 256u * data[0] + data[1];
  3789. info->background_g = 256u * data[2] + data[3];
  3790. info->background_b = 256u * data[4] + data[5];
  3791. }
  3792. return 0; /* OK */
  3793. }
  3794. /*text chunk (tEXt)*/
  3795. static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  3796. unsigned error = 0;
  3797. char *key = 0, *str = 0;
  3798. unsigned i;
  3799. while(!error) /*not really a while loop, only used to break on error*/ {
  3800. unsigned length, string2_begin;
  3801. length = 0;
  3802. while(length < chunkLength && data[length] != 0) ++length;
  3803. /*even though it's not allowed by the standard, no error is thrown if
  3804. there's no null termination char, if the text is empty*/
  3805. if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
  3806. key = (char*)lodepng_malloc(length + 1);
  3807. if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
  3808. key[length] = 0;
  3809. for(i = 0; i != length; ++i) key[i] = (char)data[i];
  3810. string2_begin = length + 1; /*skip keyword null terminator*/
  3811. length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin);
  3812. str = (char*)lodepng_malloc(length + 1);
  3813. if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
  3814. str[length] = 0;
  3815. for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
  3816. error = lodepng_add_text(info, key, str);
  3817. break;
  3818. }
  3819. lodepng_free(key);
  3820. lodepng_free(str);
  3821. return error;
  3822. }
  3823. /*compressed text chunk (zTXt)*/
  3824. static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
  3825. const unsigned char* data, size_t chunkLength) {
  3826. unsigned error = 0;
  3827. unsigned i;
  3828. unsigned length, string2_begin;
  3829. char *key = 0;
  3830. ucvector decoded;
  3831. ucvector_init(&decoded);
  3832. while(!error) /*not really a while loop, only used to break on error*/ {
  3833. for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
  3834. if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
  3835. if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
  3836. key = (char*)lodepng_malloc(length + 1);
  3837. if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
  3838. key[length] = 0;
  3839. for(i = 0; i != length; ++i) key[i] = (char)data[i];
  3840. if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
  3841. string2_begin = length + 2;
  3842. if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
  3843. length = (unsigned)chunkLength - string2_begin;
  3844. /*will fail if zlib error, e.g. if length is too small*/
  3845. error = zlib_decompress(&decoded.data, &decoded.size,
  3846. &data[string2_begin],
  3847. length, zlibsettings);
  3848. if(error) break;
  3849. ucvector_push_back(&decoded, 0);
  3850. error = lodepng_add_text(info, key, (char*)decoded.data);
  3851. break;
  3852. }
  3853. lodepng_free(key);
  3854. ucvector_cleanup(&decoded);
  3855. return error;
  3856. }
  3857. /*international text chunk (iTXt)*/
  3858. static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
  3859. const unsigned char* data, size_t chunkLength) {
  3860. unsigned error = 0;
  3861. unsigned i;
  3862. unsigned length, begin, compressed;
  3863. char *key = 0, *langtag = 0, *transkey = 0;
  3864. ucvector decoded;
  3865. ucvector_init(&decoded); /* TODO: only use in case of compressed text */
  3866. while(!error) /*not really a while loop, only used to break on error*/ {
  3867. /*Quick check if the chunk length isn't too small. Even without check
  3868. it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
  3869. if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
  3870. /*read the key*/
  3871. for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
  3872. if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
  3873. if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
  3874. key = (char*)lodepng_malloc(length + 1);
  3875. if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
  3876. key[length] = 0;
  3877. for(i = 0; i != length; ++i) key[i] = (char)data[i];
  3878. /*read the compression method*/
  3879. compressed = data[length + 1];
  3880. if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
  3881. /*even though it's not allowed by the standard, no error is thrown if
  3882. there's no null termination char, if the text is empty for the next 3 texts*/
  3883. /*read the langtag*/
  3884. begin = length + 3;
  3885. length = 0;
  3886. for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
  3887. langtag = (char*)lodepng_malloc(length + 1);
  3888. if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
  3889. langtag[length] = 0;
  3890. for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
  3891. /*read the transkey*/
  3892. begin += length + 1;
  3893. length = 0;
  3894. for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
  3895. transkey = (char*)lodepng_malloc(length + 1);
  3896. if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
  3897. transkey[length] = 0;
  3898. for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
  3899. /*read the actual text*/
  3900. begin += length + 1;
  3901. length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin;
  3902. if(compressed) {
  3903. /*will fail if zlib error, e.g. if length is too small*/
  3904. error = zlib_decompress(&decoded.data, &decoded.size,
  3905. &data[begin],
  3906. length, zlibsettings);
  3907. if(error) break;
  3908. if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
  3909. ucvector_push_back(&decoded, 0);
  3910. } else {
  3911. if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
  3912. decoded.data[length] = 0;
  3913. for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
  3914. }
  3915. error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
  3916. break;
  3917. }
  3918. lodepng_free(key);
  3919. lodepng_free(langtag);
  3920. lodepng_free(transkey);
  3921. ucvector_cleanup(&decoded);
  3922. return error;
  3923. }
  3924. static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  3925. if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
  3926. info->time_defined = 1;
  3927. info->time.year = 256u * data[0] + data[1];
  3928. info->time.month = data[2];
  3929. info->time.day = data[3];
  3930. info->time.hour = data[4];
  3931. info->time.minute = data[5];
  3932. info->time.second = data[6];
  3933. return 0; /* OK */
  3934. }
  3935. static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  3936. if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
  3937. info->phys_defined = 1;
  3938. info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
  3939. info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
  3940. info->phys_unit = data[8];
  3941. return 0; /* OK */
  3942. }
  3943. static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  3944. if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/
  3945. info->gama_defined = 1;
  3946. info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
  3947. return 0; /* OK */
  3948. }
  3949. static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  3950. if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/
  3951. info->chrm_defined = 1;
  3952. info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3];
  3953. info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7];
  3954. info->chrm_red_x = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11];
  3955. info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15];
  3956. info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];
  3957. info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];
  3958. info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27];
  3959. info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31];
  3960. return 0; /* OK */
  3961. }
  3962. static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
  3963. if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/
  3964. info->srgb_defined = 1;
  3965. info->srgb_intent = data[0];
  3966. return 0; /* OK */
  3967. }
  3968. static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
  3969. const unsigned char* data, size_t chunkLength) {
  3970. unsigned error = 0;
  3971. unsigned i;
  3972. unsigned length, string2_begin;
  3973. ucvector decoded;
  3974. info->iccp_defined = 1;
  3975. if(info->iccp_name) lodepng_clear_icc(info);
  3976. for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
  3977. if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/
  3978. if(length < 1 || length > 79) return 89; /*keyword too short or long*/
  3979. info->iccp_name = (char*)lodepng_malloc(length + 1);
  3980. if(!info->iccp_name) return 83; /*alloc fail*/
  3981. info->iccp_name[length] = 0;
  3982. for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i];
  3983. if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/
  3984. string2_begin = length + 2;
  3985. if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/
  3986. length = (unsigned)chunkLength - string2_begin;
  3987. ucvector_init(&decoded);
  3988. error = zlib_decompress(&decoded.data, &decoded.size,
  3989. &data[string2_begin],
  3990. length, zlibsettings);
  3991. if(!error) {
  3992. if(decoded.size) {
  3993. info->iccp_profile_size = decoded.size;
  3994. info->iccp_profile = (unsigned char*)lodepng_malloc(decoded.size);
  3995. if(info->iccp_profile) {
  3996. lodepng_memcpy(info->iccp_profile, decoded.data, decoded.size);
  3997. } else {
  3998. error = 83; /* alloc fail */
  3999. }
  4000. } else {
  4001. error = 100; /*invalid ICC profile size*/
  4002. }
  4003. }
  4004. ucvector_cleanup(&decoded);
  4005. return error;
  4006. }
  4007. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4008. unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,
  4009. const unsigned char* in, size_t insize) {
  4010. const unsigned char* chunk = in + pos;
  4011. unsigned chunkLength;
  4012. const unsigned char* data;
  4013. unsigned unhandled = 0;
  4014. unsigned error = 0;
  4015. if (pos + 4 > insize) return 30;
  4016. chunkLength = lodepng_chunk_length(chunk);
  4017. if(chunkLength > 2147483647) return 63;
  4018. data = lodepng_chunk_data_const(chunk);
  4019. if(data + chunkLength + 4 > in + insize) return 30;
  4020. if(lodepng_chunk_type_equals(chunk, "PLTE")) {
  4021. error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
  4022. } else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
  4023. error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
  4024. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4025. } else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
  4026. error = readChunk_bKGD(&state->info_png, data, chunkLength);
  4027. } else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
  4028. error = readChunk_tEXt(&state->info_png, data, chunkLength);
  4029. } else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
  4030. error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  4031. } else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
  4032. error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  4033. } else if(lodepng_chunk_type_equals(chunk, "tIME")) {
  4034. error = readChunk_tIME(&state->info_png, data, chunkLength);
  4035. } else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
  4036. error = readChunk_pHYs(&state->info_png, data, chunkLength);
  4037. } else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
  4038. error = readChunk_gAMA(&state->info_png, data, chunkLength);
  4039. } else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
  4040. error = readChunk_cHRM(&state->info_png, data, chunkLength);
  4041. } else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
  4042. error = readChunk_sRGB(&state->info_png, data, chunkLength);
  4043. } else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
  4044. error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  4045. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4046. } else {
  4047. /* unhandled chunk is ok (is not an error) */
  4048. unhandled = 1;
  4049. }
  4050. if(!error && !unhandled && !state->decoder.ignore_crc) {
  4051. if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/
  4052. }
  4053. return error;
  4054. }
  4055. /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
  4056. static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
  4057. LodePNGState* state,
  4058. const unsigned char* in, size_t insize) {
  4059. unsigned char IEND = 0;
  4060. const unsigned char* chunk;
  4061. size_t i;
  4062. ucvector idat; /*the data from idat chunks*/
  4063. unsigned char* scanlines = 0;
  4064. size_t scanlines_size = 0, expected_size = 0;
  4065. size_t outsize = 0;
  4066. /*for unknown chunk order*/
  4067. unsigned unknown = 0;
  4068. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4069. unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
  4070. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4071. /* safe output values in case error happens */
  4072. *out = 0;
  4073. *w = *h = 0;
  4074. state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
  4075. if(state->error) return;
  4076. if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) {
  4077. CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/
  4078. }
  4079. ucvector_init(&idat);
  4080. chunk = &in[33]; /*first byte of the first chunk after the header*/
  4081. /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
  4082. IDAT data is put at the start of the in buffer*/
  4083. while(!IEND && !state->error) {
  4084. unsigned chunkLength;
  4085. const unsigned char* data; /*the data in the chunk*/
  4086. /*error: size of the in buffer too small to contain next chunk*/
  4087. if((size_t)((chunk - in) + 12) > insize || chunk < in) {
  4088. if(state->decoder.ignore_end) break; /*other errors may still happen though*/
  4089. CERROR_BREAK(state->error, 30);
  4090. }
  4091. /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
  4092. chunkLength = lodepng_chunk_length(chunk);
  4093. /*error: chunk length larger than the max PNG chunk size*/
  4094. if(chunkLength > 2147483647) {
  4095. if(state->decoder.ignore_end) break; /*other errors may still happen though*/
  4096. CERROR_BREAK(state->error, 63);
  4097. }
  4098. if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) {
  4099. CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
  4100. }
  4101. data = lodepng_chunk_data_const(chunk);
  4102. unknown = 0;
  4103. /*IDAT chunk, containing compressed image data*/
  4104. if(lodepng_chunk_type_equals(chunk, "IDAT")) {
  4105. size_t oldsize = idat.size;
  4106. size_t newsize;
  4107. if(lodepng_addofl(oldsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95);
  4108. if(!ucvector_resize(&idat, newsize)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
  4109. for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
  4110. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4111. critical_pos = 3;
  4112. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4113. } else if(lodepng_chunk_type_equals(chunk, "IEND")) {
  4114. /*IEND chunk*/
  4115. IEND = 1;
  4116. } else if(lodepng_chunk_type_equals(chunk, "PLTE")) {
  4117. /*palette chunk (PLTE)*/
  4118. state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
  4119. if(state->error) break;
  4120. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4121. critical_pos = 2;
  4122. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4123. } else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
  4124. /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled
  4125. in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that
  4126. affects the alpha channel of pixels. */
  4127. state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
  4128. if(state->error) break;
  4129. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4130. /*background color chunk (bKGD)*/
  4131. } else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
  4132. state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
  4133. if(state->error) break;
  4134. } else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
  4135. /*text chunk (tEXt)*/
  4136. if(state->decoder.read_text_chunks) {
  4137. state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
  4138. if(state->error) break;
  4139. }
  4140. } else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
  4141. /*compressed text chunk (zTXt)*/
  4142. if(state->decoder.read_text_chunks) {
  4143. state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  4144. if(state->error) break;
  4145. }
  4146. } else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
  4147. /*international text chunk (iTXt)*/
  4148. if(state->decoder.read_text_chunks) {
  4149. state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  4150. if(state->error) break;
  4151. }
  4152. } else if(lodepng_chunk_type_equals(chunk, "tIME")) {
  4153. state->error = readChunk_tIME(&state->info_png, data, chunkLength);
  4154. if(state->error) break;
  4155. } else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
  4156. state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
  4157. if(state->error) break;
  4158. } else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
  4159. state->error = readChunk_gAMA(&state->info_png, data, chunkLength);
  4160. if(state->error) break;
  4161. } else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
  4162. state->error = readChunk_cHRM(&state->info_png, data, chunkLength);
  4163. if(state->error) break;
  4164. } else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
  4165. state->error = readChunk_sRGB(&state->info_png, data, chunkLength);
  4166. if(state->error) break;
  4167. } else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
  4168. state->error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
  4169. if(state->error) break;
  4170. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4171. } else /*it's not an implemented chunk type, so ignore it: skip over the data*/ {
  4172. /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
  4173. if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) {
  4174. CERROR_BREAK(state->error, 69);
  4175. }
  4176. unknown = 1;
  4177. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4178. if(state->decoder.remember_unknown_chunks) {
  4179. state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
  4180. &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
  4181. if(state->error) break;
  4182. }
  4183. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4184. }
  4185. if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ {
  4186. if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
  4187. }
  4188. if(!IEND) chunk = lodepng_chunk_next_const(chunk);
  4189. }
  4190. if (state->info_png.color.colortype == LCT_PALETTE
  4191. && !state->info_png.color.palette) {
  4192. state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */
  4193. }
  4194. /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
  4195. If the decompressed size does not match the prediction, the image must be corrupt.*/
  4196. if(state->info_png.interlace_method == 0) {
  4197. expected_size = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color);
  4198. } else {
  4199. /*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/
  4200. const LodePNGColorMode* color = &state->info_png.color;
  4201. expected_size = 0;
  4202. expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color);
  4203. if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color);
  4204. expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color);
  4205. if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color);
  4206. expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color);
  4207. if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color);
  4208. expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color);
  4209. }
  4210. if(!state->error) {
  4211. /* This allocated data will be realloced by zlib_decompress, initially at
  4212. smaller size again. But the fact that it's already allocated at full size
  4213. here speeds the multiple reallocs up. TODO: make zlib_decompress support
  4214. receiving already allocated buffer with expected size instead. */
  4215. scanlines = (unsigned char*)lodepng_malloc(expected_size);
  4216. if(!scanlines) state->error = 83; /*alloc fail*/
  4217. scanlines_size = 0;
  4218. }
  4219. if(!state->error) {
  4220. state->error = zlib_decompress(&scanlines, &scanlines_size, idat.data,
  4221. idat.size, &state->decoder.zlibsettings);
  4222. if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/
  4223. }
  4224. ucvector_cleanup(&idat);
  4225. if(!state->error) {
  4226. outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
  4227. *out = (unsigned char*)lodepng_malloc(outsize);
  4228. if(!*out) state->error = 83; /*alloc fail*/
  4229. }
  4230. if(!state->error) {
  4231. for(i = 0; i < outsize; i++) (*out)[i] = 0;
  4232. state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png);
  4233. }
  4234. lodepng_free(scanlines);
  4235. }
  4236. unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
  4237. LodePNGState* state,
  4238. const unsigned char* in, size_t insize) {
  4239. *out = 0;
  4240. decodeGeneric(out, w, h, state, in, insize);
  4241. if(state->error) return state->error;
  4242. if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) {
  4243. /*same color type, no copying or converting of data needed*/
  4244. /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
  4245. the raw image has to the end user*/
  4246. if(!state->decoder.color_convert) {
  4247. state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
  4248. if(state->error) return state->error;
  4249. }
  4250. } else { /*color conversion needed*/
  4251. unsigned char* data = *out;
  4252. size_t outsize;
  4253. /*TODO: check if this works according to the statement in the documentation: "The converter can convert
  4254. from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/
  4255. if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
  4256. && !(state->info_raw.bitdepth == 8)) {
  4257. return 56; /*unsupported color mode conversion*/
  4258. }
  4259. outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
  4260. *out = (unsigned char*)lodepng_malloc(outsize);
  4261. if(!(*out)) {
  4262. state->error = 83; /*alloc fail*/
  4263. }
  4264. else state->error = lodepng_convert(*out, data, &state->info_raw,
  4265. &state->info_png.color, *w, *h);
  4266. lodepng_free(data);
  4267. }
  4268. return state->error;
  4269. }
  4270. unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
  4271. size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
  4272. unsigned error;
  4273. LodePNGState state;
  4274. lodepng_state_init(&state);
  4275. state.info_raw.colortype = colortype;
  4276. state.info_raw.bitdepth = bitdepth;
  4277. error = lodepng_decode(out, w, h, &state, in, insize);
  4278. lodepng_state_cleanup(&state);
  4279. return error;
  4280. }
  4281. unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
  4282. return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
  4283. }
  4284. unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
  4285. return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
  4286. }
  4287. #ifdef LODEPNG_COMPILE_DISK
  4288. unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
  4289. LodePNGColorType colortype, unsigned bitdepth) {
  4290. unsigned char* buffer = 0;
  4291. size_t buffersize;
  4292. unsigned error;
  4293. /* safe output values in case error happens */
  4294. *out = 0;
  4295. *w = *h = 0;
  4296. error = lodepng_load_file(&buffer, &buffersize, filename);
  4297. if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
  4298. lodepng_free(buffer);
  4299. return error;
  4300. }
  4301. unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
  4302. return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
  4303. }
  4304. unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
  4305. return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
  4306. }
  4307. #endif /*LODEPNG_COMPILE_DISK*/
  4308. void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) {
  4309. settings->color_convert = 1;
  4310. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4311. settings->read_text_chunks = 1;
  4312. settings->remember_unknown_chunks = 0;
  4313. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4314. settings->ignore_crc = 0;
  4315. settings->ignore_critical = 0;
  4316. settings->ignore_end = 0;
  4317. lodepng_decompress_settings_init(&settings->zlibsettings);
  4318. }
  4319. #endif /*LODEPNG_COMPILE_DECODER*/
  4320. #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
  4321. void lodepng_state_init(LodePNGState* state) {
  4322. #ifdef LODEPNG_COMPILE_DECODER
  4323. lodepng_decoder_settings_init(&state->decoder);
  4324. #endif /*LODEPNG_COMPILE_DECODER*/
  4325. #ifdef LODEPNG_COMPILE_ENCODER
  4326. lodepng_encoder_settings_init(&state->encoder);
  4327. #endif /*LODEPNG_COMPILE_ENCODER*/
  4328. lodepng_color_mode_init(&state->info_raw);
  4329. lodepng_info_init(&state->info_png);
  4330. state->error = 1;
  4331. }
  4332. void lodepng_state_cleanup(LodePNGState* state) {
  4333. lodepng_color_mode_cleanup(&state->info_raw);
  4334. lodepng_info_cleanup(&state->info_png);
  4335. }
  4336. void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) {
  4337. lodepng_state_cleanup(dest);
  4338. *dest = *source;
  4339. lodepng_color_mode_init(&dest->info_raw);
  4340. lodepng_info_init(&dest->info_png);
  4341. dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
  4342. dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
  4343. }
  4344. #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
  4345. #ifdef LODEPNG_COMPILE_ENCODER
  4346. /* ////////////////////////////////////////////////////////////////////////// */
  4347. /* / PNG Encoder / */
  4348. /* ////////////////////////////////////////////////////////////////////////// */
  4349. /*chunkName must be string of 4 characters*/
  4350. static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) {
  4351. CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
  4352. out->allocsize = out->size; /*fix the allocsize again*/
  4353. return 0;
  4354. }
  4355. static void writeSignature(ucvector* out) {
  4356. /*8 bytes PNG signature, aka the magic bytes*/
  4357. ucvector_push_back(out, 137);
  4358. ucvector_push_back(out, 80);
  4359. ucvector_push_back(out, 78);
  4360. ucvector_push_back(out, 71);
  4361. ucvector_push_back(out, 13);
  4362. ucvector_push_back(out, 10);
  4363. ucvector_push_back(out, 26);
  4364. ucvector_push_back(out, 10);
  4365. }
  4366. static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
  4367. LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) {
  4368. unsigned char data[13];
  4369. lodepng_set32bitInt(data + 0, w); /*width*/
  4370. lodepng_set32bitInt(data + 4, h); /*height*/
  4371. data[8] = (unsigned char)bitdepth; /*bit depth*/
  4372. data[9] = (unsigned char)colortype; /*color type*/
  4373. data[10] = 0; /*compression method*/
  4374. data[11] = 0; /*filter method*/
  4375. data[12] = interlace_method; /*interlace method*/
  4376. return addChunk(out, "IHDR", data, sizeof(data));
  4377. }
  4378. static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) {
  4379. unsigned error = 0;
  4380. size_t i;
  4381. ucvector PLTE;
  4382. ucvector_init(&PLTE);
  4383. for(i = 0; i != info->palettesize * 4; ++i) {
  4384. /*add all channels except alpha channel*/
  4385. if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
  4386. }
  4387. error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
  4388. ucvector_cleanup(&PLTE);
  4389. return error;
  4390. }
  4391. static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) {
  4392. unsigned error = 0;
  4393. size_t i;
  4394. ucvector tRNS;
  4395. ucvector_init(&tRNS);
  4396. if(info->colortype == LCT_PALETTE) {
  4397. size_t amount = info->palettesize;
  4398. /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
  4399. for(i = info->palettesize; i != 0; --i) {
  4400. if(info->palette[4 * (i - 1) + 3] == 255) --amount;
  4401. else break;
  4402. }
  4403. /*add only alpha channel*/
  4404. for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
  4405. } else if(info->colortype == LCT_GREY) {
  4406. if(info->key_defined) {
  4407. ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
  4408. ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
  4409. }
  4410. } else if(info->colortype == LCT_RGB) {
  4411. if(info->key_defined) {
  4412. ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
  4413. ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
  4414. ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8));
  4415. ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255));
  4416. ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8));
  4417. ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255));
  4418. }
  4419. }
  4420. error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
  4421. ucvector_cleanup(&tRNS);
  4422. return error;
  4423. }
  4424. static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
  4425. LodePNGCompressSettings* zlibsettings) {
  4426. ucvector zlibdata;
  4427. unsigned error = 0;
  4428. /*compress with the Zlib compressor*/
  4429. ucvector_init(&zlibdata);
  4430. error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
  4431. if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
  4432. ucvector_cleanup(&zlibdata);
  4433. return error;
  4434. }
  4435. static unsigned addChunk_IEND(ucvector* out) {
  4436. unsigned error = 0;
  4437. error = addChunk(out, "IEND", 0, 0);
  4438. return error;
  4439. }
  4440. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4441. static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) {
  4442. unsigned error = 0;
  4443. size_t i;
  4444. ucvector text;
  4445. ucvector_init(&text);
  4446. for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
  4447. if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  4448. ucvector_push_back(&text, 0); /*0 termination char*/
  4449. for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
  4450. error = addChunk(out, "tEXt", text.data, text.size);
  4451. ucvector_cleanup(&text);
  4452. return error;
  4453. }
  4454. static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
  4455. LodePNGCompressSettings* zlibsettings) {
  4456. unsigned error = 0;
  4457. ucvector data, compressed;
  4458. size_t i, textsize = lodepng_strlen(textstring);
  4459. ucvector_init(&data);
  4460. ucvector_init(&compressed);
  4461. for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
  4462. if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  4463. ucvector_push_back(&data, 0); /*0 termination char*/
  4464. ucvector_push_back(&data, 0); /*compression method: 0*/
  4465. error = zlib_compress(&compressed.data, &compressed.size,
  4466. (const unsigned char*)textstring, textsize, zlibsettings);
  4467. if(!error) {
  4468. for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
  4469. error = addChunk(out, "zTXt", data.data, data.size);
  4470. }
  4471. ucvector_cleanup(&compressed);
  4472. ucvector_cleanup(&data);
  4473. return error;
  4474. }
  4475. static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
  4476. const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) {
  4477. unsigned error = 0;
  4478. ucvector data;
  4479. size_t i, textsize = lodepng_strlen(textstring);
  4480. ucvector_init(&data);
  4481. for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
  4482. if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  4483. ucvector_push_back(&data, 0); /*null termination char*/
  4484. ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
  4485. ucvector_push_back(&data, 0); /*compression method*/
  4486. for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
  4487. ucvector_push_back(&data, 0); /*null termination char*/
  4488. for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]);
  4489. ucvector_push_back(&data, 0); /*null termination char*/
  4490. if(compressed) {
  4491. ucvector compressed_data;
  4492. ucvector_init(&compressed_data);
  4493. error = zlib_compress(&compressed_data.data, &compressed_data.size,
  4494. (const unsigned char*)textstring, textsize, zlibsettings);
  4495. if(!error) {
  4496. for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]);
  4497. }
  4498. ucvector_cleanup(&compressed_data);
  4499. } else /*not compressed*/ {
  4500. for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
  4501. }
  4502. if(!error) error = addChunk(out, "iTXt", data.data, data.size);
  4503. ucvector_cleanup(&data);
  4504. return error;
  4505. }
  4506. static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) {
  4507. unsigned char data[6];
  4508. size_t size = 0;
  4509. if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
  4510. data[0] = (unsigned char)(info->background_r >> 8);
  4511. data[1] = (unsigned char)(info->background_r & 255);
  4512. size = 2;
  4513. } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
  4514. data[0] = (unsigned char)(info->background_r >> 8);
  4515. data[1] = (unsigned char)(info->background_r & 255);
  4516. data[2] = (unsigned char)(info->background_g >> 8);
  4517. data[3] = (unsigned char)(info->background_g & 255);
  4518. data[4] = (unsigned char)(info->background_b >> 8);
  4519. data[5] = (unsigned char)(info->background_b & 255);
  4520. size = 6;
  4521. } else if(info->color.colortype == LCT_PALETTE) {
  4522. data[0] =(unsigned char)(info->background_r & 255); /*palette index*/
  4523. size = 1;
  4524. }
  4525. return addChunk(out, "bKGD", data, size);
  4526. }
  4527. static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) {
  4528. unsigned char data[7];
  4529. data[0] = (unsigned char)(time->year >> 8);
  4530. data[1] = (unsigned char)(time->year & 255);
  4531. data[2] = (unsigned char)time->month;
  4532. data[3] = (unsigned char)time->day;
  4533. data[4] = (unsigned char)time->hour;
  4534. data[5] = (unsigned char)time->minute;
  4535. data[6] = (unsigned char)time->second;
  4536. return addChunk(out, "tIME", data, sizeof(data));
  4537. }
  4538. static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) {
  4539. unsigned char data[9];
  4540. lodepng_set32bitInt(data + 0, info->phys_x);
  4541. lodepng_set32bitInt(data + 4, info->phys_y); data[8] = info->phys_unit;
  4542. return addChunk(out, "pHYs", data, sizeof(data));
  4543. }
  4544. static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) {
  4545. unsigned char data[4];
  4546. lodepng_set32bitInt(data, info->gama_gamma);
  4547. return addChunk(out, "gAMA", data, sizeof(data));
  4548. }
  4549. static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) {
  4550. unsigned char data[32];
  4551. lodepng_set32bitInt(data + 0, info->chrm_white_x);
  4552. lodepng_set32bitInt(data + 4, info->chrm_white_y);
  4553. lodepng_set32bitInt(data + 8, info->chrm_red_x);
  4554. lodepng_set32bitInt(data + 12, info->chrm_red_y);
  4555. lodepng_set32bitInt(data + 16, info->chrm_green_x);
  4556. lodepng_set32bitInt(data + 20, info->chrm_green_y);
  4557. lodepng_set32bitInt(data + 24, info->chrm_blue_x);
  4558. lodepng_set32bitInt(data + 28, info->chrm_blue_y);
  4559. return addChunk(out, "cHRM", data, sizeof(data));
  4560. }
  4561. static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) {
  4562. unsigned char data = info->srgb_intent;
  4563. return addChunk(out, "sRGB", &data, 1);
  4564. }
  4565. static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) {
  4566. unsigned error = 0;
  4567. ucvector data, compressed;
  4568. size_t i;
  4569. ucvector_init(&data);
  4570. ucvector_init(&compressed);
  4571. for(i = 0; info->iccp_name[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)info->iccp_name[i]);
  4572. if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
  4573. ucvector_push_back(&data, 0); /*0 termination char*/
  4574. ucvector_push_back(&data, 0); /*compression method: 0*/
  4575. error = zlib_compress(&compressed.data, &compressed.size,
  4576. info->iccp_profile, info->iccp_profile_size, zlibsettings);
  4577. if(!error) {
  4578. for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
  4579. error = addChunk(out, "iCCP", data.data, data.size);
  4580. }
  4581. ucvector_cleanup(&compressed);
  4582. ucvector_cleanup(&data);
  4583. return error;
  4584. }
  4585. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4586. static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
  4587. size_t length, size_t bytewidth, unsigned char filterType) {
  4588. size_t i;
  4589. switch(filterType) {
  4590. case 0: /*None*/
  4591. for(i = 0; i != length; ++i) out[i] = scanline[i];
  4592. break;
  4593. case 1: /*Sub*/
  4594. for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
  4595. for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
  4596. break;
  4597. case 2: /*Up*/
  4598. if(prevline) {
  4599. for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
  4600. } else {
  4601. for(i = 0; i != length; ++i) out[i] = scanline[i];
  4602. }
  4603. break;
  4604. case 3: /*Average*/
  4605. if(prevline) {
  4606. for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);
  4607. for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);
  4608. } else {
  4609. for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
  4610. for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);
  4611. }
  4612. break;
  4613. case 4: /*Paeth*/
  4614. if(prevline) {
  4615. /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
  4616. for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
  4617. for(i = bytewidth; i < length; ++i) {
  4618. out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
  4619. }
  4620. } else {
  4621. for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
  4622. /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
  4623. for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
  4624. }
  4625. break;
  4626. default: return; /*nonexistent filter type given*/
  4627. }
  4628. }
  4629. /* integer binary logarithm */
  4630. static size_t ilog2(size_t i) {
  4631. size_t result = 0;
  4632. while(i >= 65536) { result += 16; i >>= 16; }
  4633. while(i >= 256) { result += 8; i >>= 8; }
  4634. while(i >= 16) { result += 4; i >>= 4; }
  4635. while(i >= 2) { result += 1; i >>= 1; }
  4636. return result;
  4637. }
  4638. /* integer approximation for i * log2(i), helper function for LFS_ENTROPY */
  4639. static size_t ilog2i(size_t i) {
  4640. size_t l;
  4641. if(i == 0) return 0;
  4642. l = ilog2(i);
  4643. /* approximate i*log2(i): l is integer logarithm, ((i - (1u << l)) << 1u)
  4644. linearly approximates the missing fractional part multiplied by i */
  4645. return i * l + ((i - (1u << l)) << 1u);
  4646. }
  4647. static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
  4648. const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) {
  4649. /*
  4650. For PNG filter method 0
  4651. out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are
  4652. the scanlines with 1 extra byte per scanline
  4653. */
  4654. unsigned bpp = lodepng_get_bpp(info);
  4655. /*the width of a scanline in bytes, not including the filter type*/
  4656. size_t linebytes = (w * bpp + 7u) / 8u;
  4657. /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
  4658. size_t bytewidth = (bpp + 7u) / 8u;
  4659. const unsigned char* prevline = 0;
  4660. unsigned x, y;
  4661. unsigned error = 0;
  4662. LodePNGFilterStrategy strategy = settings->filter_strategy;
  4663. /*
  4664. There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
  4665. * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
  4666. use fixed filtering, with the filter None).
  4667. * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
  4668. not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
  4669. all five filters and select the filter that produces the smallest sum of absolute values per row.
  4670. This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
  4671. If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
  4672. but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
  4673. heuristic is used.
  4674. */
  4675. if(settings->filter_palette_zero &&
  4676. (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
  4677. if(bpp == 0) return 31; /*error: invalid color type*/
  4678. if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) {
  4679. unsigned char type = (unsigned char)strategy;
  4680. for(y = 0; y != h; ++y) {
  4681. size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
  4682. size_t inindex = linebytes * y;
  4683. out[outindex] = type; /*filter type byte*/
  4684. filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
  4685. prevline = &in[inindex];
  4686. }
  4687. } else if(strategy == LFS_MINSUM) {
  4688. /*adaptive filtering*/
  4689. unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
  4690. size_t smallest = 0;
  4691. unsigned char type, bestType = 0;
  4692. for(type = 0; type != 5; ++type) {
  4693. attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
  4694. if(!attempt[type]) return 83; /*alloc fail*/
  4695. }
  4696. if(!error) {
  4697. for(y = 0; y != h; ++y) {
  4698. /*try the 5 filter types*/
  4699. for(type = 0; type != 5; ++type) {
  4700. size_t sum = 0;
  4701. filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
  4702. /*calculate the sum of the result*/
  4703. if(type == 0) {
  4704. for(x = 0; x != linebytes; ++x) sum += (unsigned char)(attempt[type][x]);
  4705. } else {
  4706. for(x = 0; x != linebytes; ++x) {
  4707. /*For differences, each byte should be treated as signed, values above 127 are negative
  4708. (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
  4709. This means filtertype 0 is almost never chosen, but that is justified.*/
  4710. unsigned char s = attempt[type][x];
  4711. sum += s < 128 ? s : (255U - s);
  4712. }
  4713. }
  4714. /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
  4715. if(type == 0 || sum < smallest) {
  4716. bestType = type;
  4717. smallest = sum;
  4718. }
  4719. }
  4720. prevline = &in[y * linebytes];
  4721. /*now fill the out values*/
  4722. out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
  4723. for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
  4724. }
  4725. }
  4726. for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
  4727. } else if(strategy == LFS_ENTROPY) {
  4728. unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
  4729. size_t bestSum = 0;
  4730. unsigned type, bestType = 0;
  4731. unsigned count[256];
  4732. for(type = 0; type != 5; ++type) {
  4733. attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
  4734. if(!attempt[type]) return 83; /*alloc fail*/
  4735. }
  4736. for(y = 0; y != h; ++y) {
  4737. /*try the 5 filter types*/
  4738. for(type = 0; type != 5; ++type) {
  4739. size_t sum = 0;
  4740. filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
  4741. for(x = 0; x != 256; ++x) count[x] = 0;
  4742. for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];
  4743. ++count[type]; /*the filter type itself is part of the scanline*/
  4744. for(x = 0; x != 256; ++x) {
  4745. sum += ilog2i(count[x]);
  4746. }
  4747. /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
  4748. if(type == 0 || sum > bestSum) {
  4749. bestType = type;
  4750. bestSum = sum;
  4751. }
  4752. }
  4753. prevline = &in[y * linebytes];
  4754. /*now fill the out values*/
  4755. out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
  4756. for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
  4757. }
  4758. for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
  4759. } else if(strategy == LFS_PREDEFINED) {
  4760. for(y = 0; y != h; ++y) {
  4761. size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
  4762. size_t inindex = linebytes * y;
  4763. unsigned char type = settings->predefined_filters[y];
  4764. out[outindex] = type; /*filter type byte*/
  4765. filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
  4766. prevline = &in[inindex];
  4767. }
  4768. } else if(strategy == LFS_BRUTE_FORCE) {
  4769. /*brute force filter chooser.
  4770. deflate the scanline after every filter attempt to see which one deflates best.
  4771. This is very slow and gives only slightly smaller, sometimes even larger, result*/
  4772. size_t size[5];
  4773. unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
  4774. size_t smallest = 0;
  4775. unsigned type = 0, bestType = 0;
  4776. unsigned char* dummy;
  4777. LodePNGCompressSettings zlibsettings = settings->zlibsettings;
  4778. /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
  4779. to simulate the true case where the tree is the same for the whole image. Sometimes it gives
  4780. better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
  4781. cases better compression. It does make this a bit less slow, so it's worth doing this.*/
  4782. zlibsettings.btype = 1;
  4783. /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
  4784. images only, so disable it*/
  4785. zlibsettings.custom_zlib = 0;
  4786. zlibsettings.custom_deflate = 0;
  4787. for(type = 0; type != 5; ++type) {
  4788. attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
  4789. if(!attempt[type]) return 83; /*alloc fail*/
  4790. }
  4791. for(y = 0; y != h; ++y) /*try the 5 filter types*/ {
  4792. for(type = 0; type != 5; ++type) {
  4793. unsigned testsize = (unsigned)linebytes;
  4794. /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
  4795. filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
  4796. size[type] = 0;
  4797. dummy = 0;
  4798. zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);
  4799. lodepng_free(dummy);
  4800. /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
  4801. if(type == 0 || size[type] < smallest) {
  4802. bestType = type;
  4803. smallest = size[type];
  4804. }
  4805. }
  4806. prevline = &in[y * linebytes];
  4807. out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
  4808. for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
  4809. }
  4810. for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
  4811. }
  4812. else return 88; /* unknown filter strategy */
  4813. return error;
  4814. }
  4815. static void addPaddingBits(unsigned char* out, const unsigned char* in,
  4816. size_t olinebits, size_t ilinebits, unsigned h) {
  4817. /*The opposite of the removePaddingBits function
  4818. olinebits must be >= ilinebits*/
  4819. unsigned y;
  4820. size_t diff = olinebits - ilinebits;
  4821. size_t obp = 0, ibp = 0; /*bit pointers*/
  4822. for(y = 0; y != h; ++y) {
  4823. size_t x;
  4824. for(x = 0; x < ilinebits; ++x) {
  4825. unsigned char bit = readBitFromReversedStream(&ibp, in);
  4826. setBitOfReversedStream(&obp, out, bit);
  4827. }
  4828. /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
  4829. "Use of uninitialised value of size ###" warning from valgrind*/
  4830. for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
  4831. }
  4832. }
  4833. /*
  4834. in: non-interlaced image with size w*h
  4835. out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
  4836. no padding bits between scanlines, but between reduced images so that each
  4837. reduced image starts at a byte.
  4838. bpp: bits per pixel
  4839. there are no padding bits, not between scanlines, not between reduced images
  4840. in has the following size in bits: w * h * bpp.
  4841. out is possibly bigger due to padding bits between reduced images
  4842. NOTE: comments about padding bits are only relevant if bpp < 8
  4843. */
  4844. static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
  4845. unsigned passw[7], passh[7];
  4846. size_t filter_passstart[8], padded_passstart[8], passstart[8];
  4847. unsigned i;
  4848. Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  4849. if(bpp >= 8) {
  4850. for(i = 0; i != 7; ++i) {
  4851. unsigned x, y, b;
  4852. size_t bytewidth = bpp / 8u;
  4853. for(y = 0; y < passh[i]; ++y)
  4854. for(x = 0; x < passw[i]; ++x) {
  4855. size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
  4856. size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
  4857. for(b = 0; b < bytewidth; ++b) {
  4858. out[pixeloutstart + b] = in[pixelinstart + b];
  4859. }
  4860. }
  4861. }
  4862. } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
  4863. for(i = 0; i != 7; ++i) {
  4864. unsigned x, y, b;
  4865. unsigned ilinebits = bpp * passw[i];
  4866. unsigned olinebits = bpp * w;
  4867. size_t obp, ibp; /*bit pointers (for out and in buffer)*/
  4868. for(y = 0; y < passh[i]; ++y)
  4869. for(x = 0; x < passw[i]; ++x) {
  4870. ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
  4871. obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
  4872. for(b = 0; b < bpp; ++b) {
  4873. unsigned char bit = readBitFromReversedStream(&ibp, in);
  4874. setBitOfReversedStream(&obp, out, bit);
  4875. }
  4876. }
  4877. }
  4878. }
  4879. }
  4880. /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
  4881. return value is error**/
  4882. static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
  4883. unsigned w, unsigned h,
  4884. const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) {
  4885. /*
  4886. This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
  4887. *) if no Adam7: 1) add padding bits (= possible extra bits per scanline if bpp < 8) 2) filter
  4888. *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
  4889. */
  4890. unsigned bpp = lodepng_get_bpp(&info_png->color);
  4891. unsigned error = 0;
  4892. if(info_png->interlace_method == 0) {
  4893. *outsize = h + (h * ((w * bpp + 7u) / 8u)); /*image size plus an extra byte per scanline + possible padding bits*/
  4894. *out = (unsigned char*)lodepng_malloc(*outsize);
  4895. if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
  4896. if(!error) {
  4897. /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
  4898. if(bpp < 8 && w * bpp != ((w * bpp + 7u) / 8u) * 8u) {
  4899. unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7u) / 8u));
  4900. if(!padded) error = 83; /*alloc fail*/
  4901. if(!error) {
  4902. addPaddingBits(padded, in, ((w * bpp + 7u) / 8u) * 8u, w * bpp, h);
  4903. error = filter(*out, padded, w, h, &info_png->color, settings);
  4904. }
  4905. lodepng_free(padded);
  4906. } else {
  4907. /*we can immediately filter into the out buffer, no other steps needed*/
  4908. error = filter(*out, in, w, h, &info_png->color, settings);
  4909. }
  4910. }
  4911. } else /*interlace_method is 1 (Adam7)*/ {
  4912. unsigned passw[7], passh[7];
  4913. size_t filter_passstart[8], padded_passstart[8], passstart[8];
  4914. unsigned char* adam7;
  4915. Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
  4916. *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
  4917. *out = (unsigned char*)lodepng_malloc(*outsize);
  4918. if(!(*out)) error = 83; /*alloc fail*/
  4919. adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
  4920. if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
  4921. if(!error) {
  4922. unsigned i;
  4923. Adam7_interlace(adam7, in, w, h, bpp);
  4924. for(i = 0; i != 7; ++i) {
  4925. if(bpp < 8) {
  4926. unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
  4927. if(!padded) ERROR_BREAK(83); /*alloc fail*/
  4928. addPaddingBits(padded, &adam7[passstart[i]],
  4929. ((passw[i] * bpp + 7u) / 8u) * 8u, passw[i] * bpp, passh[i]);
  4930. error = filter(&(*out)[filter_passstart[i]], padded,
  4931. passw[i], passh[i], &info_png->color, settings);
  4932. lodepng_free(padded);
  4933. } else {
  4934. error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
  4935. passw[i], passh[i], &info_png->color, settings);
  4936. }
  4937. if(error) break;
  4938. }
  4939. }
  4940. lodepng_free(adam7);
  4941. }
  4942. return error;
  4943. }
  4944. /*
  4945. palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
  4946. returns 0 if the palette is opaque,
  4947. returns 1 if the palette has a single color with alpha 0 ==> color key
  4948. returns 2 if the palette is semi-translucent.
  4949. */
  4950. static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) {
  4951. size_t i;
  4952. unsigned key = 0;
  4953. unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
  4954. for(i = 0; i != palettesize; ++i) {
  4955. if(!key && palette[4 * i + 3] == 0) {
  4956. r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
  4957. key = 1;
  4958. i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
  4959. }
  4960. else if(palette[4 * i + 3] != 255) return 2;
  4961. /*when key, no opaque RGB may have key's RGB*/
  4962. else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
  4963. }
  4964. return key;
  4965. }
  4966. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  4967. static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) {
  4968. unsigned char* inchunk = data;
  4969. while((size_t)(inchunk - data) < datasize) {
  4970. CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
  4971. out->allocsize = out->size; /*fix the allocsize again*/
  4972. inchunk = lodepng_chunk_next(inchunk);
  4973. }
  4974. return 0;
  4975. }
  4976. static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) {
  4977. /*
  4978. It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19
  4979. are "RGB ". We do not perform any full parsing of the ICC profile here, other
  4980. than check those 4 bytes to grayscale profile. Other than that, validity of
  4981. the profile is not checked. This is needed only because the PNG specification
  4982. requires using a non-gray color model if there is an ICC profile with "RGB "
  4983. (sadly limiting compression opportunities if the input data is grayscale RGB
  4984. data), and requires using a gray color model if it is "GRAY".
  4985. */
  4986. if(size < 20) return 0;
  4987. return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y';
  4988. }
  4989. static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) {
  4990. /* See comment in isGrayICCProfile*/
  4991. if(size < 20) return 0;
  4992. return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' ';
  4993. }
  4994. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  4995. unsigned lodepng_encode(unsigned char** out, size_t* outsize,
  4996. const unsigned char* image, unsigned w, unsigned h,
  4997. LodePNGState* state) {
  4998. unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
  4999. size_t datasize = 0;
  5000. ucvector outv;
  5001. LodePNGInfo info;
  5002. const LodePNGInfo* info_png = &state->info_png;
  5003. ucvector_init(&outv);
  5004. lodepng_info_init(&info);
  5005. /*provide some proper output values if error will happen*/
  5006. *out = 0;
  5007. *outsize = 0;
  5008. state->error = 0;
  5009. /*check input values validity*/
  5010. if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette)
  5011. && (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) {
  5012. state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
  5013. goto cleanup;
  5014. }
  5015. if(state->encoder.zlibsettings.btype > 2) {
  5016. state->error = 61; /*error: nonexistent btype*/
  5017. goto cleanup;
  5018. }
  5019. if(info_png->interlace_method > 1) {
  5020. state->error = 71; /*error: nonexistent interlace mode*/
  5021. goto cleanup;
  5022. }
  5023. state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth);
  5024. if(state->error) goto cleanup; /*error: nonexistent color type given*/
  5025. state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
  5026. if(state->error) goto cleanup; /*error: nonexistent color type given*/
  5027. /* color convert and compute scanline filter types */
  5028. lodepng_info_copy(&info, &state->info_png);
  5029. if(state->encoder.auto_convert) {
  5030. LodePNGColorStats stats;
  5031. lodepng_color_stats_init(&stats);
  5032. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5033. if(info_png->iccp_defined &&
  5034. isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
  5035. /*the PNG specification does not allow to use palette with a GRAY ICC profile, even
  5036. if the palette has only gray colors, so disallow it.*/
  5037. stats.allow_palette = 0;
  5038. }
  5039. if(info_png->iccp_defined &&
  5040. isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) {
  5041. /*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/
  5042. stats.allow_greyscale = 0;
  5043. }
  5044. #endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
  5045. lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw);
  5046. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5047. if(info_png->background_defined) {
  5048. /*the background chunk's color must be taken into account as well*/
  5049. unsigned r = 0, g = 0, b = 0;
  5050. LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16);
  5051. lodepng_convert_rgb(&r, &g, &b, info_png->background_r, info_png->background_g, info_png->background_b, &mode16, &info_png->color);
  5052. lodepng_color_stats_add(&stats, r, g, b, 65535);
  5053. }
  5054. #endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
  5055. state->error = auto_choose_color(&info.color, &state->info_raw, &stats);
  5056. if(state->error) goto cleanup;
  5057. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5058. /*also convert the background chunk*/
  5059. if(info_png->background_defined) {
  5060. if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b,
  5061. info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) {
  5062. state->error = 104;
  5063. goto cleanup;
  5064. }
  5065. }
  5066. #endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
  5067. }
  5068. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5069. if(info_png->iccp_defined) {
  5070. unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
  5071. unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size);
  5072. unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA;
  5073. if(!gray_icc && !rgb_icc) {
  5074. state->error = 100; /* Disallowed profile color type for PNG */
  5075. goto cleanup;
  5076. }
  5077. if(gray_icc != gray_png) {
  5078. /*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa,
  5079. or in case of auto_convert, it wasn't possible to find appropriate model*/
  5080. state->error = state->encoder.auto_convert ? 102 : 101;
  5081. goto cleanup;
  5082. }
  5083. }
  5084. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  5085. if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) {
  5086. unsigned char* converted;
  5087. size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u;
  5088. converted = (unsigned char*)lodepng_malloc(size);
  5089. if(!converted && size) state->error = 83; /*alloc fail*/
  5090. if(!state->error) {
  5091. state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
  5092. }
  5093. if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
  5094. lodepng_free(converted);
  5095. if(state->error) goto cleanup;
  5096. }
  5097. else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
  5098. /* output all PNG chunks */ {
  5099. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5100. size_t i;
  5101. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  5102. /*write signature and chunks*/
  5103. writeSignature(&outv);
  5104. /*IHDR*/
  5105. addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
  5106. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5107. /*unknown chunks between IHDR and PLTE*/
  5108. if(info.unknown_chunks_data[0]) {
  5109. state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
  5110. if(state->error) goto cleanup;
  5111. }
  5112. /*color profile chunks must come before PLTE */
  5113. if(info.iccp_defined) addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings);
  5114. if(info.srgb_defined) addChunk_sRGB(&outv, &info);
  5115. if(info.gama_defined) addChunk_gAMA(&outv, &info);
  5116. if(info.chrm_defined) addChunk_cHRM(&outv, &info);
  5117. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  5118. /*PLTE*/
  5119. if(info.color.colortype == LCT_PALETTE) {
  5120. addChunk_PLTE(&outv, &info.color);
  5121. }
  5122. if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) {
  5123. addChunk_PLTE(&outv, &info.color);
  5124. }
  5125. /*tRNS*/
  5126. if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) {
  5127. addChunk_tRNS(&outv, &info.color);
  5128. }
  5129. if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) {
  5130. addChunk_tRNS(&outv, &info.color);
  5131. }
  5132. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5133. /*bKGD (must come between PLTE and the IDAt chunks*/
  5134. if(info.background_defined) {
  5135. state->error = addChunk_bKGD(&outv, &info);
  5136. if(state->error) goto cleanup;
  5137. }
  5138. /*pHYs (must come before the IDAT chunks)*/
  5139. if(info.phys_defined) addChunk_pHYs(&outv, &info);
  5140. /*unknown chunks between PLTE and IDAT*/
  5141. if(info.unknown_chunks_data[1]) {
  5142. state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
  5143. if(state->error) goto cleanup;
  5144. }
  5145. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  5146. /*IDAT (multiple IDAT chunks must be consecutive)*/
  5147. state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
  5148. if(state->error) goto cleanup;
  5149. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5150. /*tIME*/
  5151. if(info.time_defined) addChunk_tIME(&outv, &info.time);
  5152. /*tEXt and/or zTXt*/
  5153. for(i = 0; i != info.text_num; ++i) {
  5154. if(lodepng_strlen(info.text_keys[i]) > 79) {
  5155. state->error = 66; /*text chunk too large*/
  5156. goto cleanup;
  5157. }
  5158. if(lodepng_strlen(info.text_keys[i]) < 1) {
  5159. state->error = 67; /*text chunk too small*/
  5160. goto cleanup;
  5161. }
  5162. if(state->encoder.text_compression) {
  5163. addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
  5164. } else {
  5165. addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
  5166. }
  5167. }
  5168. /*LodePNG version id in text chunk*/
  5169. if(state->encoder.add_id) {
  5170. unsigned already_added_id_text = 0;
  5171. for(i = 0; i != info.text_num; ++i) {
  5172. const char* k = info.text_keys[i];
  5173. /* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */
  5174. if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' &&
  5175. k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') {
  5176. already_added_id_text = 1;
  5177. break;
  5178. }
  5179. }
  5180. if(already_added_id_text == 0) {
  5181. addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
  5182. }
  5183. }
  5184. /*iTXt*/
  5185. for(i = 0; i != info.itext_num; ++i) {
  5186. if(lodepng_strlen(info.itext_keys[i]) > 79) {
  5187. state->error = 66; /*text chunk too large*/
  5188. goto cleanup;
  5189. }
  5190. if(lodepng_strlen(info.itext_keys[i]) < 1) {
  5191. state->error = 67; /*text chunk too small*/
  5192. goto cleanup;
  5193. }
  5194. addChunk_iTXt(&outv, state->encoder.text_compression,
  5195. info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
  5196. &state->encoder.zlibsettings);
  5197. }
  5198. /*unknown chunks between IDAT and IEND*/
  5199. if(info.unknown_chunks_data[2]) {
  5200. state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
  5201. if(state->error) goto cleanup;
  5202. }
  5203. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  5204. addChunk_IEND(&outv);
  5205. }
  5206. cleanup:
  5207. lodepng_info_cleanup(&info);
  5208. lodepng_free(data);
  5209. /*instead of cleaning the vector up, give it to the output*/
  5210. *out = outv.data;
  5211. *outsize = outv.size;
  5212. return state->error;
  5213. }
  5214. unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
  5215. unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
  5216. unsigned error;
  5217. LodePNGState state;
  5218. lodepng_state_init(&state);
  5219. state.info_raw.colortype = colortype;
  5220. state.info_raw.bitdepth = bitdepth;
  5221. state.info_png.color.colortype = colortype;
  5222. state.info_png.color.bitdepth = bitdepth;
  5223. lodepng_encode(out, outsize, image, w, h, &state);
  5224. error = state.error;
  5225. lodepng_state_cleanup(&state);
  5226. return error;
  5227. }
  5228. unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
  5229. return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
  5230. }
  5231. unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
  5232. return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
  5233. }
  5234. #ifdef LODEPNG_COMPILE_DISK
  5235. unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
  5236. LodePNGColorType colortype, unsigned bitdepth) {
  5237. unsigned char* buffer;
  5238. size_t buffersize;
  5239. unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
  5240. if(!error) error = lodepng_save_file(buffer, buffersize, filename);
  5241. lodepng_free(buffer);
  5242. return error;
  5243. }
  5244. unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
  5245. return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
  5246. }
  5247. unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
  5248. return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
  5249. }
  5250. #endif /*LODEPNG_COMPILE_DISK*/
  5251. void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) {
  5252. lodepng_compress_settings_init(&settings->zlibsettings);
  5253. settings->filter_palette_zero = 1;
  5254. settings->filter_strategy = LFS_MINSUM;
  5255. settings->auto_convert = 1;
  5256. settings->force_palette = 0;
  5257. settings->predefined_filters = 0;
  5258. #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
  5259. settings->add_id = 0;
  5260. settings->text_compression = 1;
  5261. #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
  5262. }
  5263. #endif /*LODEPNG_COMPILE_ENCODER*/
  5264. #endif /*LODEPNG_COMPILE_PNG*/
  5265. #ifdef LODEPNG_COMPILE_ERROR_TEXT
  5266. /*
  5267. This returns the description of a numerical error code in English. This is also
  5268. the documentation of all the error codes.
  5269. */
  5270. const char* lodepng_error_text(unsigned code) {
  5271. switch(code) {
  5272. case 0: return "no error, everything went ok";
  5273. case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
  5274. case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
  5275. case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
  5276. case 13: return "problem while processing dynamic deflate block";
  5277. case 14: return "problem while processing dynamic deflate block";
  5278. case 15: return "problem while processing dynamic deflate block";
  5279. /*this error could happen if there are only 0 or 1 symbols present in the huffman code:*/
  5280. case 16: return "nonexistent code while processing dynamic deflate block";
  5281. case 17: return "end of out buffer memory reached while inflating";
  5282. case 18: return "invalid distance code while inflating";
  5283. case 19: return "end of out buffer memory reached while inflating";
  5284. case 20: return "invalid deflate block BTYPE encountered while decoding";
  5285. case 21: return "NLEN is not ones complement of LEN in a deflate block";
  5286. /*end of out buffer memory reached while inflating:
  5287. This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
  5288. all the pixels of the image, given the color depth and image dimensions. Something that doesn't
  5289. happen in a normal, well encoded, PNG image.*/
  5290. case 22: return "end of out buffer memory reached while inflating";
  5291. case 23: return "end of in buffer memory reached while inflating";
  5292. case 24: return "invalid FCHECK in zlib header";
  5293. case 25: return "invalid compression method in zlib header";
  5294. case 26: return "FDICT encountered in zlib header while it's not used for PNG";
  5295. case 27: return "PNG file is smaller than a PNG header";
  5296. /*Checks the magic file header, the first 8 bytes of the PNG file*/
  5297. case 28: return "incorrect PNG signature, it's no PNG or corrupted";
  5298. case 29: return "first chunk is not the header chunk";
  5299. case 30: return "chunk length too large, chunk broken off at end of file";
  5300. case 31: return "illegal PNG color type or bpp";
  5301. case 32: return "illegal PNG compression method";
  5302. case 33: return "illegal PNG filter method";
  5303. case 34: return "illegal PNG interlace method";
  5304. case 35: return "chunk length of a chunk is too large or the chunk too small";
  5305. case 36: return "illegal PNG filter type encountered";
  5306. case 37: return "illegal bit depth for this color type given";
  5307. case 38: return "the palette is too small or too big"; /*0, or more than 256 colors*/
  5308. case 39: return "tRNS chunk before PLTE or has more entries than palette size";
  5309. case 40: return "tRNS chunk has wrong size for grayscale image";
  5310. case 41: return "tRNS chunk has wrong size for RGB image";
  5311. case 42: return "tRNS chunk appeared while it was not allowed for this color type";
  5312. case 43: return "bKGD chunk has wrong size for palette image";
  5313. case 44: return "bKGD chunk has wrong size for grayscale image";
  5314. case 45: return "bKGD chunk has wrong size for RGB image";
  5315. case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";
  5316. case 49: return "jumped past memory while generating dynamic huffman tree";
  5317. case 50: return "jumped past memory while generating dynamic huffman tree";
  5318. case 51: return "jumped past memory while inflating huffman block";
  5319. case 52: return "jumped past memory while inflating";
  5320. case 53: return "size of zlib data too small";
  5321. case 54: return "repeat symbol in tree while there was no value symbol yet";
  5322. /*jumped past tree while generating huffman tree, this could be when the
  5323. tree will have more leaves than symbols after generating it out of the
  5324. given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
  5325. case 55: return "jumped past tree while generating huffman tree";
  5326. case 56: return "given output image colortype or bitdepth not supported for color conversion";
  5327. case 57: return "invalid CRC encountered (checking CRC can be disabled)";
  5328. case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
  5329. case 59: return "requested color conversion not supported";
  5330. case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
  5331. case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
  5332. /*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/
  5333. case 62: return "conversion from color to grayscale not supported";
  5334. /*(2^31-1)*/
  5335. case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk";
  5336. /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
  5337. case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
  5338. case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
  5339. case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
  5340. case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
  5341. case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
  5342. case 71: return "nonexistent interlace mode given to encoder (must be 0 or 1)";
  5343. case 72: return "while decoding, nonexistent compression method encountering in zTXt or iTXt chunk (it must be 0)";
  5344. case 73: return "invalid tIME chunk size";
  5345. case 74: return "invalid pHYs chunk size";
  5346. /*length could be wrong, or data chopped off*/
  5347. case 75: return "no null termination char found while decoding text chunk";
  5348. case 76: return "iTXt chunk too short to contain required bytes";
  5349. case 77: return "integer overflow in buffer size";
  5350. case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
  5351. case 79: return "failed to open file for writing";
  5352. case 80: return "tried creating a tree of 0 symbols";
  5353. case 81: return "lazy matching at pos 0 is impossible";
  5354. case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds";
  5355. case 83: return "memory allocation failed";
  5356. case 84: return "given image too small to contain all pixels to be encoded";
  5357. case 86: return "impossible offset in lz77 encoding (internal bug)";
  5358. case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
  5359. case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
  5360. case 89: return "text chunk keyword too short or long: must have size 1-79";
  5361. /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
  5362. case 90: return "windowsize must be a power of two";
  5363. case 91: return "invalid decompressed idat size";
  5364. case 92: return "integer overflow due to too many pixels";
  5365. case 93: return "zero width or height is invalid";
  5366. case 94: return "header chunk must have a size of 13 bytes";
  5367. case 95: return "integer overflow with combined idat chunk size";
  5368. case 96: return "invalid gAMA chunk size";
  5369. case 97: return "invalid cHRM chunk size";
  5370. case 98: return "invalid sRGB chunk size";
  5371. case 99: return "invalid sRGB rendering intent";
  5372. case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY";
  5373. case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa";
  5374. case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification";
  5375. case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?";
  5376. case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)";
  5377. case 105: return "integer overflow of bitsize";
  5378. case 106: return "PNG file must have PLTE chunk if color type is palette";
  5379. case 107: return "color convert from palette mode requested without setting the palette data in it";
  5380. case 108: return "tried to add more than 256 values to a palette";
  5381. }
  5382. return "unknown error code";
  5383. }
  5384. #endif /*LODEPNG_COMPILE_ERROR_TEXT*/
  5385. /* ////////////////////////////////////////////////////////////////////////// */
  5386. /* ////////////////////////////////////////////////////////////////////////// */
  5387. /* // C++ Wrapper // */
  5388. /* ////////////////////////////////////////////////////////////////////////// */
  5389. /* ////////////////////////////////////////////////////////////////////////// */
  5390. #ifdef LODEPNG_COMPILE_CPP
  5391. namespace lodepng {
  5392. #ifdef LODEPNG_COMPILE_DISK
  5393. unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename) {
  5394. long size = lodepng_filesize(filename.c_str());
  5395. if(size < 0) return 78;
  5396. buffer.resize((size_t)size);
  5397. return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str());
  5398. }
  5399. /*write given buffer to the file, overwriting the file, it doesn't append to it.*/
  5400. unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename) {
  5401. return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());
  5402. }
  5403. #endif /* LODEPNG_COMPILE_DISK */
  5404. #ifdef LODEPNG_COMPILE_ZLIB
  5405. #ifdef LODEPNG_COMPILE_DECODER
  5406. unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
  5407. const LodePNGDecompressSettings& settings) {
  5408. unsigned char* buffer = 0;
  5409. size_t buffersize = 0;
  5410. unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
  5411. if(buffer) {
  5412. out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  5413. lodepng_free(buffer);
  5414. }
  5415. return error;
  5416. }
  5417. unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
  5418. const LodePNGDecompressSettings& settings) {
  5419. return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
  5420. }
  5421. #endif /* LODEPNG_COMPILE_DECODER */
  5422. #ifdef LODEPNG_COMPILE_ENCODER
  5423. unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
  5424. const LodePNGCompressSettings& settings) {
  5425. unsigned char* buffer = 0;
  5426. size_t buffersize = 0;
  5427. unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
  5428. if(buffer) {
  5429. out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  5430. lodepng_free(buffer);
  5431. }
  5432. return error;
  5433. }
  5434. unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
  5435. const LodePNGCompressSettings& settings) {
  5436. return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
  5437. }
  5438. #endif /* LODEPNG_COMPILE_ENCODER */
  5439. #endif /* LODEPNG_COMPILE_ZLIB */
  5440. #ifdef LODEPNG_COMPILE_PNG
  5441. State::State() {
  5442. lodepng_state_init(this);
  5443. }
  5444. State::State(const State& other) {
  5445. lodepng_state_init(this);
  5446. lodepng_state_copy(this, &other);
  5447. }
  5448. State::~State() {
  5449. lodepng_state_cleanup(this);
  5450. }
  5451. State& State::operator=(const State& other) {
  5452. lodepng_state_copy(this, &other);
  5453. return *this;
  5454. }
  5455. #ifdef LODEPNG_COMPILE_DECODER
  5456. unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
  5457. size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
  5458. unsigned char* buffer;
  5459. unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
  5460. if(buffer && !error) {
  5461. State state;
  5462. state.info_raw.colortype = colortype;
  5463. state.info_raw.bitdepth = bitdepth;
  5464. size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
  5465. out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  5466. lodepng_free(buffer);
  5467. }
  5468. return error;
  5469. }
  5470. unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
  5471. const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth) {
  5472. return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
  5473. }
  5474. unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
  5475. State& state,
  5476. const unsigned char* in, size_t insize) {
  5477. unsigned char* buffer = NULL;
  5478. unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
  5479. if(buffer && !error) {
  5480. size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
  5481. out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  5482. }
  5483. lodepng_free(buffer);
  5484. return error;
  5485. }
  5486. unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
  5487. State& state,
  5488. const std::vector<unsigned char>& in) {
  5489. return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
  5490. }
  5491. #ifdef LODEPNG_COMPILE_DISK
  5492. unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
  5493. LodePNGColorType colortype, unsigned bitdepth) {
  5494. std::vector<unsigned char> buffer;
  5495. /* safe output values in case error happens */
  5496. w = h = 0;
  5497. unsigned error = load_file(buffer, filename);
  5498. if(error) return error;
  5499. return decode(out, w, h, buffer, colortype, bitdepth);
  5500. }
  5501. #endif /* LODEPNG_COMPILE_DECODER */
  5502. #endif /* LODEPNG_COMPILE_DISK */
  5503. #ifdef LODEPNG_COMPILE_ENCODER
  5504. unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
  5505. LodePNGColorType colortype, unsigned bitdepth) {
  5506. unsigned char* buffer;
  5507. size_t buffersize;
  5508. unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
  5509. if(buffer) {
  5510. out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  5511. lodepng_free(buffer);
  5512. }
  5513. return error;
  5514. }
  5515. unsigned encode(std::vector<unsigned char>& out,
  5516. const std::vector<unsigned char>& in, unsigned w, unsigned h,
  5517. LodePNGColorType colortype, unsigned bitdepth) {
  5518. if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
  5519. return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
  5520. }
  5521. unsigned encode(std::vector<unsigned char>& out,
  5522. const unsigned char* in, unsigned w, unsigned h,
  5523. State& state) {
  5524. unsigned char* buffer;
  5525. size_t buffersize;
  5526. unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
  5527. if(buffer) {
  5528. out.insert(out.end(), &buffer[0], &buffer[buffersize]);
  5529. lodepng_free(buffer);
  5530. }
  5531. return error;
  5532. }
  5533. unsigned encode(std::vector<unsigned char>& out,
  5534. const std::vector<unsigned char>& in, unsigned w, unsigned h,
  5535. State& state) {
  5536. if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
  5537. return encode(out, in.empty() ? 0 : &in[0], w, h, state);
  5538. }
  5539. #ifdef LODEPNG_COMPILE_DISK
  5540. unsigned encode(const std::string& filename,
  5541. const unsigned char* in, unsigned w, unsigned h,
  5542. LodePNGColorType colortype, unsigned bitdepth) {
  5543. std::vector<unsigned char> buffer;
  5544. unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
  5545. if(!error) error = save_file(buffer, filename);
  5546. return error;
  5547. }
  5548. unsigned encode(const std::string& filename,
  5549. const std::vector<unsigned char>& in, unsigned w, unsigned h,
  5550. LodePNGColorType colortype, unsigned bitdepth) {
  5551. if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
  5552. return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
  5553. }
  5554. #endif /* LODEPNG_COMPILE_DISK */
  5555. #endif /* LODEPNG_COMPILE_ENCODER */
  5556. #endif /* LODEPNG_COMPILE_PNG */
  5557. } /* namespace lodepng */
  5558. #endif /*LODEPNG_COMPILE_CPP*/