pngvalid.c 378 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296
  1. /* pngvalid.c - validate libpng by constructing then reading png files.
  2. *
  3. * Copyright (c) 2021 Cosmin Truta
  4. * Copyright (c) 2014-2017 John Cunningham Bowler
  5. *
  6. * This code is released under the libpng license.
  7. * For conditions of distribution and use, see the disclaimer
  8. * and license in png.h
  9. *
  10. * NOTES:
  11. * This is a C program that is intended to be linked against libpng. It
  12. * generates bitmaps internally, stores them as PNG files (using the
  13. * sequential write code) then reads them back (using the sequential
  14. * read code) and validates that the result has the correct data.
  15. *
  16. * The program can be modified and extended to test the correctness of
  17. * transformations performed by libpng.
  18. */
  19. #define _POSIX_SOURCE 1
  20. #define _ISOC99_SOURCE 1 /* For floating point */
  21. #define _GNU_SOURCE 1 /* For the floating point exception extension */
  22. #define _BSD_SOURCE 1 /* For the floating point exception extension */
  23. #define _DEFAULT_SOURCE 1 /* For the floating point exception extension */
  24. #include <signal.h>
  25. #include <stdio.h>
  26. #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
  27. # include <config.h>
  28. #endif
  29. #ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
  30. # include <fenv.h>
  31. #endif
  32. #ifndef FE_DIVBYZERO
  33. # define FE_DIVBYZERO 0
  34. #endif
  35. #ifndef FE_INVALID
  36. # define FE_INVALID 0
  37. #endif
  38. #ifndef FE_OVERFLOW
  39. # define FE_OVERFLOW 0
  40. #endif
  41. /* Define the following to use this test against your installed libpng, rather
  42. * than the one being built here:
  43. */
  44. #ifdef PNG_FREESTANDING_TESTS
  45. # include <png.h>
  46. #else
  47. # include "../../png.h"
  48. #endif
  49. #ifdef PNG_ZLIB_HEADER
  50. # include PNG_ZLIB_HEADER
  51. #else
  52. # include <zlib.h> /* For crc32 */
  53. #endif
  54. /* 1.6.1 added support for the configure test harness, which uses 77 to indicate
  55. * a skipped test, in earlier versions we need to succeed on a skipped test, so:
  56. */
  57. #if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H)
  58. # define SKIP 77
  59. #else
  60. # define SKIP 0
  61. #endif
  62. /* pngvalid requires write support and one of the fixed or floating point APIs.
  63. * progressive read is also required currently as the progressive read pointer
  64. * is used to record the 'display' structure.
  65. */
  66. #if defined PNG_WRITE_SUPPORTED &&\
  67. (defined PNG_PROGRESSIVE_READ_SUPPORTED) &&\
  68. (defined PNG_FIXED_POINT_SUPPORTED || defined PNG_FLOATING_POINT_SUPPORTED)
  69. #if PNG_LIBPNG_VER < 10500
  70. /* This deliberately lacks the const. */
  71. typedef png_byte *png_const_bytep;
  72. /* This is copied from 1.5.1 png.h: */
  73. #define PNG_INTERLACE_ADAM7_PASSES 7
  74. #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
  75. #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
  76. #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
  77. #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
  78. #define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
  79. -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
  80. #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
  81. -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
  82. #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
  83. (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
  84. #define PNG_COL_FROM_PASS_COL(xIn, pass) \
  85. (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
  86. #define PNG_PASS_MASK(pass,off) ( \
  87. ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
  88. ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
  89. #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
  90. ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
  91. #define PNG_COL_IN_INTERLACE_PASS(x, pass) \
  92. ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
  93. /* These are needed too for the default build: */
  94. #define PNG_WRITE_16BIT_SUPPORTED
  95. #define PNG_READ_16BIT_SUPPORTED
  96. /* This comes from pnglibconf.h after 1.5: */
  97. #define PNG_FP_1 100000
  98. #define PNG_GAMMA_THRESHOLD_FIXED\
  99. ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
  100. #endif
  101. #if PNG_LIBPNG_VER < 10600
  102. /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
  103. * compiled against earlier versions.
  104. */
  105. # define png_const_structp png_structp
  106. #endif
  107. #ifndef RELEASE_BUILD
  108. /* RELEASE_BUILD is true for releases and release candidates: */
  109. # define RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC)
  110. #endif
  111. #if RELEASE_BUILD
  112. # define debugonly(something)
  113. #else /* !RELEASE_BUILD */
  114. # define debugonly(something) something
  115. #endif /* !RELEASE_BUILD */
  116. #include <float.h> /* For floating point constants */
  117. #include <stdlib.h> /* For malloc */
  118. #include <string.h> /* For memcpy, memset */
  119. #include <math.h> /* For floor */
  120. /* Convenience macros. */
  121. #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
  122. #define CHUNK_IHDR CHUNK(73,72,68,82)
  123. #define CHUNK_PLTE CHUNK(80,76,84,69)
  124. #define CHUNK_IDAT CHUNK(73,68,65,84)
  125. #define CHUNK_IEND CHUNK(73,69,78,68)
  126. #define CHUNK_cHRM CHUNK(99,72,82,77)
  127. #define CHUNK_gAMA CHUNK(103,65,77,65)
  128. #define CHUNK_sBIT CHUNK(115,66,73,84)
  129. #define CHUNK_sRGB CHUNK(115,82,71,66)
  130. /* Unused formal parameter errors are removed using the following macro which is
  131. * expected to have no bad effects on performance.
  132. */
  133. #ifndef UNUSED
  134. # if defined(__GNUC__) || defined(_MSC_VER)
  135. # define UNUSED(param) (void)param;
  136. # else
  137. # define UNUSED(param)
  138. # endif
  139. #endif
  140. /***************************** EXCEPTION HANDLING *****************************/
  141. #ifdef PNG_FREESTANDING_TESTS
  142. # include <cexcept.h>
  143. #else
  144. # include "../visupng/cexcept.h"
  145. #endif
  146. #ifdef __cplusplus
  147. # define this not_the_cpp_this
  148. # define new not_the_cpp_new
  149. # define voidcast(type, value) static_cast<type>(value)
  150. #else
  151. # define voidcast(type, value) (value)
  152. #endif /* __cplusplus */
  153. struct png_store;
  154. define_exception_type(struct png_store*);
  155. /* The following are macros to reduce typing everywhere where the well known
  156. * name 'the_exception_context' must be defined.
  157. */
  158. #define anon_context(ps) struct exception_context *the_exception_context = \
  159. &(ps)->exception_context
  160. #define context(ps,fault) anon_context(ps); png_store *fault
  161. /* This macro returns the number of elements in an array as an (unsigned int),
  162. * it is necessary to avoid the inability of certain versions of GCC to use
  163. * the value of a compile-time constant when performing range checks. It must
  164. * be passed an array name.
  165. */
  166. #define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
  167. /* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires
  168. * some broken GCC versions to be fixed up to avoid invalid whining about auto
  169. * variables that are *not* changed within the scope of a setjmp being changed.
  170. *
  171. * Feel free to extend the list of broken versions.
  172. */
  173. #define is_gnu(major,minor)\
  174. (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor)
  175. #define is_gnu_patch(major,minor,patch)\
  176. is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0
  177. /* For the moment just do it always; all versions of GCC seem to be broken: */
  178. #ifdef __GNUC__
  179. const void * volatile make_volatile_for_gnu;
  180. # define gnu_volatile(x) make_volatile_for_gnu = &x;
  181. #else /* !GNUC broken versions */
  182. # define gnu_volatile(x)
  183. #endif /* !GNUC broken versions */
  184. /******************************* UTILITIES ************************************/
  185. /* Error handling is particularly problematic in production code - error
  186. * handlers often themselves have bugs which lead to programs that detect
  187. * minor errors crashing. The following functions deal with one very
  188. * common class of errors in error handlers - attempting to format error or
  189. * warning messages into buffers that are too small.
  190. */
  191. static size_t safecat(char *buffer, size_t bufsize, size_t pos,
  192. const char *cat)
  193. {
  194. while (pos < bufsize && cat != NULL && *cat != 0)
  195. buffer[pos++] = *cat++;
  196. if (pos >= bufsize)
  197. pos = bufsize-1;
  198. buffer[pos] = 0;
  199. return pos;
  200. }
  201. static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
  202. {
  203. char number[64];
  204. sprintf(number, "%d", n);
  205. return safecat(buffer, bufsize, pos, number);
  206. }
  207. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  208. static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
  209. int precision)
  210. {
  211. char number[64];
  212. sprintf(number, "%.*f", precision, d);
  213. return safecat(buffer, bufsize, pos, number);
  214. }
  215. #endif
  216. static const char invalid[] = "invalid";
  217. static const char sep[] = ": ";
  218. static const char *colour_types[8] =
  219. {
  220. "grayscale", invalid, "truecolour", "indexed-colour",
  221. "grayscale with alpha", invalid, "truecolour with alpha", invalid
  222. };
  223. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  224. /* Convert a double precision value to fixed point. */
  225. static png_fixed_point
  226. fix(double d)
  227. {
  228. d = floor(d * PNG_FP_1 + .5);
  229. return (png_fixed_point)d;
  230. }
  231. #endif /* PNG_READ_SUPPORTED */
  232. /* Generate random bytes. This uses a boring repeatable algorithm and it
  233. * is implemented here so that it gives the same set of numbers on every
  234. * architecture. It's a linear congruential generator (Knuth or Sedgewick
  235. * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
  236. * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
  237. * Generation.)
  238. */
  239. static void
  240. make_random_bytes(png_uint_32* seed, void* pv, size_t size)
  241. {
  242. png_uint_32 u0 = seed[0], u1 = seed[1];
  243. png_bytep bytes = voidcast(png_bytep, pv);
  244. /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
  245. * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
  246. */
  247. size_t i;
  248. for (i=0; i<size; ++i)
  249. {
  250. /* First generate 8 new bits then shift them in at the end. */
  251. png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
  252. u1 <<= 8;
  253. u1 |= u0 >> 24;
  254. u0 <<= 8;
  255. u0 |= u;
  256. *bytes++ = (png_byte)u;
  257. }
  258. seed[0] = u0;
  259. seed[1] = u1;
  260. }
  261. static void
  262. make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
  263. {
  264. make_random_bytes(seed, bytes, 4);
  265. }
  266. #if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED ||\
  267. defined PNG_WRITE_FILTER_SUPPORTED
  268. static void
  269. randomize_bytes(void *pv, size_t size)
  270. {
  271. static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
  272. make_random_bytes(random_seed, pv, size);
  273. }
  274. #define R8(this) randomize_bytes(&(this), sizeof (this))
  275. #ifdef PNG_READ_SUPPORTED
  276. static png_byte
  277. random_byte(void)
  278. {
  279. unsigned char b1[1];
  280. randomize_bytes(b1, sizeof b1);
  281. return b1[0];
  282. }
  283. #endif /* READ */
  284. static png_uint_16
  285. random_u16(void)
  286. {
  287. unsigned char b2[2];
  288. randomize_bytes(b2, sizeof b2);
  289. return png_get_uint_16(b2);
  290. }
  291. #if defined PNG_READ_RGB_TO_GRAY_SUPPORTED ||\
  292. defined PNG_READ_FILLER_SUPPORTED
  293. static png_uint_32
  294. random_u32(void)
  295. {
  296. unsigned char b4[4];
  297. randomize_bytes(b4, sizeof b4);
  298. return png_get_uint_32(b4);
  299. }
  300. #endif /* READ_FILLER || READ_RGB_TO_GRAY */
  301. #endif /* READ || WRITE_tRNS || WRITE_FILTER */
  302. #if defined PNG_READ_TRANSFORMS_SUPPORTED ||\
  303. defined PNG_WRITE_FILTER_SUPPORTED
  304. static unsigned int
  305. random_mod(unsigned int max)
  306. {
  307. return random_u16() % max; /* 0 .. max-1 */
  308. }
  309. #endif /* READ_TRANSFORMS || WRITE_FILTER */
  310. #if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\
  311. (defined PNG_READ_FILLER_SUPPORTED)
  312. static int
  313. random_choice(void)
  314. {
  315. return random_byte() & 1;
  316. }
  317. #endif /* READ_RGB_TO_GRAY || READ_FILLER */
  318. /* A numeric ID based on PNG file characteristics. The 'do_interlace' field
  319. * simply records whether pngvalid did the interlace itself or whether it
  320. * was done by libpng. Width and height must be less than 256. 'palette' is an
  321. * index of the palette to use for formats with a palette otherwise a boolean
  322. * indicating if a tRNS chunk was generated.
  323. */
  324. #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
  325. ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
  326. (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
  327. #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
  328. #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
  329. #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
  330. #define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3))
  331. #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
  332. #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
  333. #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
  334. /* Utility to construct a standard name for a standard image. */
  335. static size_t
  336. standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
  337. int bit_depth, unsigned int npalette, int interlace_type,
  338. png_uint_32 w, png_uint_32 h, int do_interlace)
  339. {
  340. pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
  341. if (colour_type == 3) /* must have a palette */
  342. {
  343. pos = safecat(buffer, bufsize, pos, "[");
  344. pos = safecatn(buffer, bufsize, pos, npalette);
  345. pos = safecat(buffer, bufsize, pos, "]");
  346. }
  347. else if (npalette != 0)
  348. pos = safecat(buffer, bufsize, pos, "+tRNS");
  349. pos = safecat(buffer, bufsize, pos, " ");
  350. pos = safecatn(buffer, bufsize, pos, bit_depth);
  351. pos = safecat(buffer, bufsize, pos, " bit");
  352. if (interlace_type != PNG_INTERLACE_NONE)
  353. {
  354. pos = safecat(buffer, bufsize, pos, " interlaced");
  355. if (do_interlace)
  356. pos = safecat(buffer, bufsize, pos, "(pngvalid)");
  357. else
  358. pos = safecat(buffer, bufsize, pos, "(libpng)");
  359. }
  360. if (w > 0 || h > 0)
  361. {
  362. pos = safecat(buffer, bufsize, pos, " ");
  363. pos = safecatn(buffer, bufsize, pos, w);
  364. pos = safecat(buffer, bufsize, pos, "x");
  365. pos = safecatn(buffer, bufsize, pos, h);
  366. }
  367. return pos;
  368. }
  369. static size_t
  370. standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
  371. {
  372. return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
  373. DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
  374. WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
  375. }
  376. /* Convenience API and defines to list valid formats. Note that 16 bit read and
  377. * write support is required to do 16 bit read tests (we must be able to make a
  378. * 16 bit image to test!)
  379. */
  380. #ifdef PNG_WRITE_16BIT_SUPPORTED
  381. # define WRITE_BDHI 4
  382. # ifdef PNG_READ_16BIT_SUPPORTED
  383. # define READ_BDHI 4
  384. # define DO_16BIT
  385. # endif
  386. #else
  387. # define WRITE_BDHI 3
  388. #endif
  389. #ifndef DO_16BIT
  390. # define READ_BDHI 3
  391. #endif
  392. /* The following defines the number of different palettes to generate for
  393. * each log bit depth of a colour type 3 standard image.
  394. */
  395. #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
  396. static int
  397. next_format(png_bytep colour_type, png_bytep bit_depth,
  398. unsigned int* palette_number, int low_depth_gray, int tRNS)
  399. {
  400. if (*bit_depth == 0)
  401. {
  402. *colour_type = 0;
  403. if (low_depth_gray)
  404. *bit_depth = 1;
  405. else
  406. *bit_depth = 8;
  407. *palette_number = 0;
  408. return 1;
  409. }
  410. if (*colour_type < 4/*no alpha channel*/)
  411. {
  412. /* Add multiple palettes for colour type 3, one image with tRNS
  413. * and one without for other non-alpha formats:
  414. */
  415. unsigned int pn = ++*palette_number;
  416. png_byte ct = *colour_type;
  417. if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
  418. (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
  419. return 1;
  420. /* No: next bit depth */
  421. *palette_number = 0;
  422. }
  423. *bit_depth = (png_byte)(*bit_depth << 1);
  424. /* Palette images are restricted to 8 bit depth */
  425. if (*bit_depth <= 8
  426. #ifdef DO_16BIT
  427. || (*colour_type != 3 && *bit_depth <= 16)
  428. #endif
  429. )
  430. return 1;
  431. /* Move to the next color type, or return 0 at the end. */
  432. switch (*colour_type)
  433. {
  434. case 0:
  435. *colour_type = 2;
  436. *bit_depth = 8;
  437. return 1;
  438. case 2:
  439. *colour_type = 3;
  440. *bit_depth = 1;
  441. return 1;
  442. case 3:
  443. *colour_type = 4;
  444. *bit_depth = 8;
  445. return 1;
  446. case 4:
  447. *colour_type = 6;
  448. *bit_depth = 8;
  449. return 1;
  450. default:
  451. return 0;
  452. }
  453. }
  454. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  455. static unsigned int
  456. sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
  457. png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
  458. {
  459. png_uint_32 bit_index, result;
  460. /* Find a sample index for the desired sample: */
  461. x *= bit_depth;
  462. bit_index = x;
  463. if ((colour_type & 1) == 0) /* !palette */
  464. {
  465. if (colour_type & 2)
  466. bit_index *= 3;
  467. if (colour_type & 4)
  468. bit_index += x; /* Alpha channel */
  469. /* Multiple channels; select one: */
  470. if (colour_type & (2+4))
  471. bit_index += sample_index * bit_depth;
  472. }
  473. /* Return the sample from the row as an integer. */
  474. row += bit_index >> 3;
  475. result = *row;
  476. if (bit_depth == 8)
  477. return result;
  478. else if (bit_depth > 8)
  479. {
  480. if (swap16)
  481. return (*++row << 8) + result;
  482. else
  483. return (result << 8) + *++row;
  484. }
  485. /* Less than 8 bits per sample. By default PNG has the big end of
  486. * the egg on the left of the screen, but if littleendian is set
  487. * then the big end is on the right.
  488. */
  489. bit_index &= 7;
  490. if (!littleendian)
  491. bit_index = 8-bit_index-bit_depth;
  492. return (result >> bit_index) & ((1U<<bit_depth)-1);
  493. }
  494. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  495. /* Copy a single pixel, of a given size, from one buffer to another -
  496. * while this is basically bit addressed there is an implicit assumption
  497. * that pixels 8 or more bits in size are byte aligned and that pixels
  498. * do not otherwise cross byte boundaries. (This is, so far as I know,
  499. * universally true in bitmap computer graphics. [JCB 20101212])
  500. *
  501. * NOTE: The to and from buffers may be the same.
  502. */
  503. static void
  504. pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
  505. png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
  506. int littleendian)
  507. {
  508. /* Assume we can multiply by 'size' without overflow because we are
  509. * just working in a single buffer.
  510. */
  511. toIndex *= pixelSize;
  512. fromIndex *= pixelSize;
  513. if (pixelSize < 8) /* Sub-byte */
  514. {
  515. /* Mask to select the location of the copied pixel: */
  516. unsigned int destMask = ((1U<<pixelSize)-1) <<
  517. (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
  518. /* The following read the entire pixels and clears the extra: */
  519. unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
  520. unsigned int sourceByte = fromBuffer[fromIndex >> 3];
  521. /* Don't rely on << or >> supporting '0' here, just in case: */
  522. fromIndex &= 7;
  523. if (littleendian)
  524. {
  525. if (fromIndex > 0) sourceByte >>= fromIndex;
  526. if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
  527. }
  528. else
  529. {
  530. if (fromIndex > 0) sourceByte <<= fromIndex;
  531. if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
  532. }
  533. toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
  534. }
  535. else /* One or more bytes */
  536. memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
  537. }
  538. #ifdef PNG_READ_SUPPORTED
  539. /* Copy a complete row of pixels, taking into account potential partial
  540. * bytes at the end.
  541. */
  542. static void
  543. row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
  544. int littleendian)
  545. {
  546. memcpy(toBuffer, fromBuffer, bitWidth >> 3);
  547. if ((bitWidth & 7) != 0)
  548. {
  549. unsigned int mask;
  550. toBuffer += bitWidth >> 3;
  551. fromBuffer += bitWidth >> 3;
  552. if (littleendian)
  553. mask = 0xff << (bitWidth & 7);
  554. else
  555. mask = 0xff >> (bitWidth & 7);
  556. *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
  557. }
  558. }
  559. /* Compare pixels - they are assumed to start at the first byte in the
  560. * given buffers.
  561. */
  562. static int
  563. pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
  564. {
  565. #if PNG_LIBPNG_VER < 10506
  566. if (memcmp(pa, pb, bit_width>>3) == 0)
  567. {
  568. png_uint_32 p;
  569. if ((bit_width & 7) == 0) return 0;
  570. /* Ok, any differences? */
  571. p = pa[bit_width >> 3];
  572. p ^= pb[bit_width >> 3];
  573. if (p == 0) return 0;
  574. /* There are, but they may not be significant, remove the bits
  575. * after the end (the low order bits in PNG.)
  576. */
  577. bit_width &= 7;
  578. p >>= 8-bit_width;
  579. if (p == 0) return 0;
  580. }
  581. #else
  582. /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
  583. * bits too:
  584. */
  585. if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
  586. return 0;
  587. #endif
  588. /* Return the index of the changed byte. */
  589. {
  590. png_uint_32 where = 0;
  591. while (pa[where] == pb[where]) ++where;
  592. return 1+where;
  593. }
  594. }
  595. #endif /* PNG_READ_SUPPORTED */
  596. /*************************** BASIC PNG FILE WRITING ***************************/
  597. /* A png_store takes data from the sequential writer or provides data
  598. * to the sequential reader. It can also store the result of a PNG
  599. * write for later retrieval.
  600. */
  601. #define STORE_BUFFER_SIZE 500 /* arbitrary */
  602. typedef struct png_store_buffer
  603. {
  604. struct png_store_buffer* prev; /* NOTE: stored in reverse order */
  605. png_byte buffer[STORE_BUFFER_SIZE];
  606. } png_store_buffer;
  607. #define FILE_NAME_SIZE 64
  608. typedef struct store_palette_entry /* record of a single palette entry */
  609. {
  610. png_byte red;
  611. png_byte green;
  612. png_byte blue;
  613. png_byte alpha;
  614. } store_palette_entry, store_palette[256];
  615. typedef struct png_store_file
  616. {
  617. struct png_store_file* next; /* as many as you like... */
  618. char name[FILE_NAME_SIZE];
  619. unsigned int IDAT_bits; /* Number of bits in IDAT size */
  620. png_uint_32 IDAT_size; /* Total size of IDAT data */
  621. png_uint_32 id; /* must be correct (see FILEID) */
  622. size_t datacount; /* In this (the last) buffer */
  623. png_store_buffer data; /* Last buffer in file */
  624. int npalette; /* Number of entries in palette */
  625. store_palette_entry* palette; /* May be NULL */
  626. } png_store_file;
  627. /* The following is a pool of memory allocated by a single libpng read or write
  628. * operation.
  629. */
  630. typedef struct store_pool
  631. {
  632. struct png_store *store; /* Back pointer */
  633. struct store_memory *list; /* List of allocated memory */
  634. png_byte mark[4]; /* Before and after data */
  635. /* Statistics for this run. */
  636. png_alloc_size_t max; /* Maximum single allocation */
  637. png_alloc_size_t current; /* Current allocation */
  638. png_alloc_size_t limit; /* Highest current allocation */
  639. png_alloc_size_t total; /* Total allocation */
  640. /* Overall statistics (retained across successive runs). */
  641. png_alloc_size_t max_max;
  642. png_alloc_size_t max_limit;
  643. png_alloc_size_t max_total;
  644. } store_pool;
  645. typedef struct png_store
  646. {
  647. /* For cexcept.h exception handling - simply store one of these;
  648. * the context is a self pointer but it may point to a different
  649. * png_store (in fact it never does in this program.)
  650. */
  651. struct exception_context
  652. exception_context;
  653. unsigned int verbose :1;
  654. unsigned int treat_warnings_as_errors :1;
  655. unsigned int expect_error :1;
  656. unsigned int expect_warning :1;
  657. unsigned int saw_warning :1;
  658. unsigned int speed :1;
  659. unsigned int progressive :1; /* use progressive read */
  660. unsigned int validated :1; /* used as a temporary flag */
  661. int nerrors;
  662. int nwarnings;
  663. int noptions; /* number of options below: */
  664. struct {
  665. unsigned char option; /* option number, 0..30 */
  666. unsigned char setting; /* setting (unset,invalid,on,off) */
  667. } options[16];
  668. char test[128]; /* Name of test */
  669. char error[256];
  670. /* Share fields */
  671. png_uint_32 chunklen; /* Length of chunk+overhead (chunkpos >= 8) */
  672. png_uint_32 chunktype;/* Type of chunk (valid if chunkpos >= 4) */
  673. png_uint_32 chunkpos; /* Position in chunk */
  674. png_uint_32 IDAT_size;/* Accumulated IDAT size in .new */
  675. unsigned int IDAT_bits;/* Cache of the file store value */
  676. /* Read fields */
  677. png_structp pread; /* Used to read a saved file */
  678. png_infop piread;
  679. png_store_file* current; /* Set when reading */
  680. png_store_buffer* next; /* Set when reading */
  681. size_t readpos; /* Position in *next */
  682. png_byte* image; /* Buffer for reading interlaced images */
  683. size_t cb_image; /* Size of this buffer */
  684. size_t cb_row; /* Row size of the image(s) */
  685. uLong IDAT_crc;
  686. png_uint_32 IDAT_len; /* Used when re-chunking IDAT chunks */
  687. png_uint_32 IDAT_pos; /* Used when re-chunking IDAT chunks */
  688. png_uint_32 image_h; /* Number of rows in a single image */
  689. store_pool read_memory_pool;
  690. /* Write fields */
  691. png_store_file* saved;
  692. png_structp pwrite; /* Used when writing a new file */
  693. png_infop piwrite;
  694. size_t writepos; /* Position in .new */
  695. char wname[FILE_NAME_SIZE];
  696. png_store_buffer new; /* The end of the new PNG file being written. */
  697. store_pool write_memory_pool;
  698. store_palette_entry* palette;
  699. int npalette;
  700. } png_store;
  701. /* Initialization and cleanup */
  702. static void
  703. store_pool_mark(png_bytep mark)
  704. {
  705. static png_uint_32 store_seed[2] = { 0x12345678, 1};
  706. make_four_random_bytes(store_seed, mark);
  707. }
  708. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  709. /* Use this for random 32 bit values; this function makes sure the result is
  710. * non-zero.
  711. */
  712. static png_uint_32
  713. random_32(void)
  714. {
  715. for (;;)
  716. {
  717. png_byte mark[4];
  718. png_uint_32 result;
  719. store_pool_mark(mark);
  720. result = png_get_uint_32(mark);
  721. if (result != 0)
  722. return result;
  723. }
  724. }
  725. #endif /* PNG_READ_SUPPORTED */
  726. static void
  727. store_pool_init(png_store *ps, store_pool *pool)
  728. {
  729. memset(pool, 0, sizeof *pool);
  730. pool->store = ps;
  731. pool->list = NULL;
  732. pool->max = pool->current = pool->limit = pool->total = 0;
  733. pool->max_max = pool->max_limit = pool->max_total = 0;
  734. store_pool_mark(pool->mark);
  735. }
  736. static void
  737. store_init(png_store* ps)
  738. {
  739. memset(ps, 0, sizeof *ps);
  740. init_exception_context(&ps->exception_context);
  741. store_pool_init(ps, &ps->read_memory_pool);
  742. store_pool_init(ps, &ps->write_memory_pool);
  743. ps->verbose = 0;
  744. ps->treat_warnings_as_errors = 0;
  745. ps->expect_error = 0;
  746. ps->expect_warning = 0;
  747. ps->saw_warning = 0;
  748. ps->speed = 0;
  749. ps->progressive = 0;
  750. ps->validated = 0;
  751. ps->nerrors = ps->nwarnings = 0;
  752. ps->pread = NULL;
  753. ps->piread = NULL;
  754. ps->saved = ps->current = NULL;
  755. ps->next = NULL;
  756. ps->readpos = 0;
  757. ps->image = NULL;
  758. ps->cb_image = 0;
  759. ps->cb_row = 0;
  760. ps->image_h = 0;
  761. ps->pwrite = NULL;
  762. ps->piwrite = NULL;
  763. ps->writepos = 0;
  764. ps->chunkpos = 8;
  765. ps->chunktype = 0;
  766. ps->chunklen = 16;
  767. ps->IDAT_size = 0;
  768. ps->IDAT_bits = 0;
  769. ps->new.prev = NULL;
  770. ps->palette = NULL;
  771. ps->npalette = 0;
  772. ps->noptions = 0;
  773. }
  774. static void
  775. store_freebuffer(png_store_buffer* psb)
  776. {
  777. if (psb->prev)
  778. {
  779. store_freebuffer(psb->prev);
  780. free(psb->prev);
  781. psb->prev = NULL;
  782. }
  783. }
  784. static void
  785. store_freenew(png_store *ps)
  786. {
  787. store_freebuffer(&ps->new);
  788. ps->writepos = 0;
  789. ps->chunkpos = 8;
  790. ps->chunktype = 0;
  791. ps->chunklen = 16;
  792. ps->IDAT_size = 0;
  793. ps->IDAT_bits = 0;
  794. if (ps->palette != NULL)
  795. {
  796. free(ps->palette);
  797. ps->palette = NULL;
  798. ps->npalette = 0;
  799. }
  800. }
  801. static void
  802. store_storenew(png_store *ps)
  803. {
  804. png_store_buffer *pb;
  805. pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
  806. if (pb == NULL)
  807. png_error(ps->pwrite, "store new: OOM");
  808. *pb = ps->new;
  809. ps->new.prev = pb;
  810. ps->writepos = 0;
  811. }
  812. static void
  813. store_freefile(png_store_file **ppf)
  814. {
  815. if (*ppf != NULL)
  816. {
  817. store_freefile(&(*ppf)->next);
  818. store_freebuffer(&(*ppf)->data);
  819. (*ppf)->datacount = 0;
  820. if ((*ppf)->palette != NULL)
  821. {
  822. free((*ppf)->palette);
  823. (*ppf)->palette = NULL;
  824. (*ppf)->npalette = 0;
  825. }
  826. free(*ppf);
  827. *ppf = NULL;
  828. }
  829. }
  830. static unsigned int
  831. bits_of(png_uint_32 num)
  832. {
  833. /* Return the number of bits in 'num' */
  834. unsigned int b = 0;
  835. if (num & 0xffff0000U) b += 16U, num >>= 16;
  836. if (num & 0xff00U) b += 8U, num >>= 8;
  837. if (num & 0xf0U) b += 4U, num >>= 4;
  838. if (num & 0xcU) b += 2U, num >>= 2;
  839. if (num & 0x2U) ++b, num >>= 1;
  840. if (num) ++b;
  841. return b; /* 0..32 */
  842. }
  843. /* Main interface to file storage, after writing a new PNG file (see the API
  844. * below) call store_storefile to store the result with the given name and id.
  845. */
  846. static void
  847. store_storefile(png_store *ps, png_uint_32 id)
  848. {
  849. png_store_file *pf;
  850. if (ps->chunkpos != 0U || ps->chunktype != 0U || ps->chunklen != 0U ||
  851. ps->IDAT_size == 0)
  852. png_error(ps->pwrite, "storefile: incomplete write");
  853. pf = voidcast(png_store_file*, malloc(sizeof *pf));
  854. if (pf == NULL)
  855. png_error(ps->pwrite, "storefile: OOM");
  856. safecat(pf->name, sizeof pf->name, 0, ps->wname);
  857. pf->id = id;
  858. pf->data = ps->new;
  859. pf->datacount = ps->writepos;
  860. pf->IDAT_size = ps->IDAT_size;
  861. pf->IDAT_bits = bits_of(ps->IDAT_size);
  862. /* Because the IDAT always has zlib header stuff this must be true: */
  863. if (pf->IDAT_bits == 0U)
  864. png_error(ps->pwrite, "storefile: 0 sized IDAT");
  865. ps->new.prev = NULL;
  866. ps->writepos = 0;
  867. ps->chunkpos = 8;
  868. ps->chunktype = 0;
  869. ps->chunklen = 16;
  870. ps->IDAT_size = 0;
  871. pf->palette = ps->palette;
  872. pf->npalette = ps->npalette;
  873. ps->palette = 0;
  874. ps->npalette = 0;
  875. /* And save it. */
  876. pf->next = ps->saved;
  877. ps->saved = pf;
  878. }
  879. /* Generate an error message (in the given buffer) */
  880. static size_t
  881. store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
  882. size_t pos, const char *msg)
  883. {
  884. if (pp != NULL && pp == ps->pread)
  885. {
  886. /* Reading a file */
  887. pos = safecat(buffer, bufsize, pos, "read: ");
  888. if (ps->current != NULL)
  889. {
  890. pos = safecat(buffer, bufsize, pos, ps->current->name);
  891. pos = safecat(buffer, bufsize, pos, sep);
  892. }
  893. }
  894. else if (pp != NULL && pp == ps->pwrite)
  895. {
  896. /* Writing a file */
  897. pos = safecat(buffer, bufsize, pos, "write: ");
  898. pos = safecat(buffer, bufsize, pos, ps->wname);
  899. pos = safecat(buffer, bufsize, pos, sep);
  900. }
  901. else
  902. {
  903. /* Neither reading nor writing (or a memory error in struct delete) */
  904. pos = safecat(buffer, bufsize, pos, "pngvalid: ");
  905. }
  906. if (ps->test[0] != 0)
  907. {
  908. pos = safecat(buffer, bufsize, pos, ps->test);
  909. pos = safecat(buffer, bufsize, pos, sep);
  910. }
  911. pos = safecat(buffer, bufsize, pos, msg);
  912. return pos;
  913. }
  914. /* Verbose output to the error stream: */
  915. static void
  916. store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
  917. png_const_charp message)
  918. {
  919. char buffer[512];
  920. if (prefix)
  921. fputs(prefix, stderr);
  922. (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
  923. fputs(buffer, stderr);
  924. fputc('\n', stderr);
  925. }
  926. /* Log an error or warning - the relevant count is always incremented. */
  927. static void
  928. store_log(png_store* ps, png_const_structp pp, png_const_charp message,
  929. int is_error)
  930. {
  931. /* The warning is copied to the error buffer if there are no errors and it is
  932. * the first warning. The error is copied to the error buffer if it is the
  933. * first error (overwriting any prior warnings).
  934. */
  935. if (is_error ? (ps->nerrors)++ == 0 :
  936. (ps->nwarnings)++ == 0 && ps->nerrors == 0)
  937. store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
  938. if (ps->verbose)
  939. store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
  940. }
  941. #ifdef PNG_READ_SUPPORTED
  942. /* Internal error function, called with a png_store but no libpng stuff. */
  943. static void
  944. internal_error(png_store *ps, png_const_charp message)
  945. {
  946. store_log(ps, NULL, message, 1 /* error */);
  947. /* And finally throw an exception. */
  948. {
  949. struct exception_context *the_exception_context = &ps->exception_context;
  950. Throw ps;
  951. }
  952. }
  953. #endif /* PNG_READ_SUPPORTED */
  954. /* Functions to use as PNG callbacks. */
  955. static void PNGCBAPI
  956. store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
  957. {
  958. png_const_structp pp = ppIn;
  959. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  960. if (!ps->expect_error)
  961. store_log(ps, pp, message, 1 /* error */);
  962. /* And finally throw an exception. */
  963. {
  964. struct exception_context *the_exception_context = &ps->exception_context;
  965. Throw ps;
  966. }
  967. }
  968. static void PNGCBAPI
  969. store_warning(png_structp ppIn, png_const_charp message)
  970. {
  971. png_const_structp pp = ppIn;
  972. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  973. if (!ps->expect_warning)
  974. store_log(ps, pp, message, 0 /* warning */);
  975. else
  976. ps->saw_warning = 1;
  977. }
  978. /* These somewhat odd functions are used when reading an image to ensure that
  979. * the buffer is big enough, the png_structp is for errors.
  980. */
  981. /* Return a single row from the correct image. */
  982. static png_bytep
  983. store_image_row(const png_store* ps, png_const_structp pp, int nImage,
  984. png_uint_32 y)
  985. {
  986. size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
  987. if (ps->image == NULL)
  988. png_error(pp, "no allocated image");
  989. if (coffset + ps->cb_row + 3 > ps->cb_image)
  990. png_error(pp, "image too small");
  991. return ps->image + coffset;
  992. }
  993. static void
  994. store_image_free(png_store *ps, png_const_structp pp)
  995. {
  996. if (ps->image != NULL)
  997. {
  998. png_bytep image = ps->image;
  999. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  1000. {
  1001. if (pp != NULL)
  1002. png_error(pp, "png_store image overwrite (1)");
  1003. else
  1004. store_log(ps, NULL, "png_store image overwrite (2)", 1);
  1005. }
  1006. ps->image = NULL;
  1007. ps->cb_image = 0;
  1008. --image;
  1009. free(image);
  1010. }
  1011. }
  1012. static void
  1013. store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
  1014. size_t cbRow, png_uint_32 cRows)
  1015. {
  1016. size_t cb = nImages * cRows * (cbRow + 5);
  1017. if (ps->cb_image < cb)
  1018. {
  1019. png_bytep image;
  1020. store_image_free(ps, pp);
  1021. /* The buffer is deliberately mis-aligned. */
  1022. image = voidcast(png_bytep, malloc(cb+2));
  1023. if (image == NULL)
  1024. {
  1025. /* Called from the startup - ignore the error for the moment. */
  1026. if (pp == NULL)
  1027. return;
  1028. png_error(pp, "OOM allocating image buffer");
  1029. }
  1030. /* These magic tags are used to detect overwrites above. */
  1031. ++image;
  1032. image[-1] = 0xed;
  1033. image[cb] = 0xfe;
  1034. ps->image = image;
  1035. ps->cb_image = cb;
  1036. }
  1037. /* We have an adequate sized image; lay out the rows. There are 2 bytes at
  1038. * the start and three at the end of each (this ensures that the row
  1039. * alignment starts out odd - 2+1 and changes for larger images on each row.)
  1040. */
  1041. ps->cb_row = cbRow;
  1042. ps->image_h = cRows;
  1043. /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
  1044. * This deliberately doesn't match the bits in the size test image which are
  1045. * outside the image; these are set to 0xff (all 1). To make the row
  1046. * comparison work in the 'size' test case the size rows are pre-initialized
  1047. * to the same value prior to calling 'standard_row'.
  1048. */
  1049. memset(ps->image, 178, cb);
  1050. /* Then put in the marks. */
  1051. while (--nImages >= 0)
  1052. {
  1053. png_uint_32 y;
  1054. for (y=0; y<cRows; ++y)
  1055. {
  1056. png_bytep row = store_image_row(ps, pp, nImages, y);
  1057. /* The markers: */
  1058. row[-2] = 190;
  1059. row[-1] = 239;
  1060. row[cbRow] = 222;
  1061. row[cbRow+1] = 173;
  1062. row[cbRow+2] = 17;
  1063. }
  1064. }
  1065. }
  1066. #ifdef PNG_READ_SUPPORTED
  1067. static void
  1068. store_image_check(const png_store* ps, png_const_structp pp, int iImage)
  1069. {
  1070. png_const_bytep image = ps->image;
  1071. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  1072. png_error(pp, "image overwrite");
  1073. else
  1074. {
  1075. size_t cbRow = ps->cb_row;
  1076. png_uint_32 rows = ps->image_h;
  1077. image += iImage * (cbRow+5) * ps->image_h;
  1078. image += 2; /* skip image first row markers */
  1079. for (; rows > 0; --rows)
  1080. {
  1081. if (image[-2] != 190 || image[-1] != 239)
  1082. png_error(pp, "row start overwritten");
  1083. if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
  1084. image[cbRow+2] != 17)
  1085. png_error(pp, "row end overwritten");
  1086. image += cbRow+5;
  1087. }
  1088. }
  1089. }
  1090. #endif /* PNG_READ_SUPPORTED */
  1091. static int
  1092. valid_chunktype(png_uint_32 chunktype)
  1093. {
  1094. /* Each byte in the chunk type must be in one of the ranges 65..90, 97..122
  1095. * (both inclusive), so:
  1096. */
  1097. unsigned int i;
  1098. for (i=0; i<4; ++i)
  1099. {
  1100. unsigned int c = chunktype & 0xffU;
  1101. if (!((c >= 65U && c <= 90U) || (c >= 97U && c <= 122U)))
  1102. return 0;
  1103. chunktype >>= 8;
  1104. }
  1105. return 1; /* It's valid */
  1106. }
  1107. static void PNGCBAPI
  1108. store_write(png_structp ppIn, png_bytep pb, size_t st)
  1109. {
  1110. png_const_structp pp = ppIn;
  1111. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  1112. size_t writepos = ps->writepos;
  1113. png_uint_32 chunkpos = ps->chunkpos;
  1114. png_uint_32 chunktype = ps->chunktype;
  1115. png_uint_32 chunklen = ps->chunklen;
  1116. if (ps->pwrite != pp)
  1117. png_error(pp, "store state damaged");
  1118. /* Technically this is legal, but in practice libpng never writes more than
  1119. * the maximum chunk size at once so if it happens something weird has
  1120. * changed inside libpng (probably).
  1121. */
  1122. if (st > 0x7fffffffU)
  1123. png_error(pp, "unexpected write size");
  1124. /* Now process the bytes to be written. Do this in units of the space in the
  1125. * output (write) buffer or, at the start 4 bytes for the chunk type and
  1126. * length limited in any case by the amount of data.
  1127. */
  1128. while (st > 0)
  1129. {
  1130. if (writepos >= STORE_BUFFER_SIZE)
  1131. store_storenew(ps), writepos = 0;
  1132. if (chunkpos < 4)
  1133. {
  1134. png_byte b = *pb++;
  1135. --st;
  1136. chunklen = (chunklen << 8) + b;
  1137. ps->new.buffer[writepos++] = b;
  1138. ++chunkpos;
  1139. }
  1140. else if (chunkpos < 8)
  1141. {
  1142. png_byte b = *pb++;
  1143. --st;
  1144. chunktype = (chunktype << 8) + b;
  1145. ps->new.buffer[writepos++] = b;
  1146. if (++chunkpos == 8)
  1147. {
  1148. chunklen &= 0xffffffffU;
  1149. if (chunklen > 0x7fffffffU)
  1150. png_error(pp, "chunk length too great");
  1151. chunktype &= 0xffffffffU;
  1152. if (chunktype == CHUNK_IDAT)
  1153. {
  1154. if (chunklen > ~ps->IDAT_size)
  1155. png_error(pp, "pngvalid internal image too large");
  1156. ps->IDAT_size += chunklen;
  1157. }
  1158. else if (!valid_chunktype(chunktype))
  1159. png_error(pp, "invalid chunk type");
  1160. chunklen += 12; /* for header and CRC */
  1161. }
  1162. }
  1163. else /* chunkpos >= 8 */
  1164. {
  1165. size_t cb = st;
  1166. if (cb > STORE_BUFFER_SIZE - writepos)
  1167. cb = STORE_BUFFER_SIZE - writepos;
  1168. if (cb > chunklen - chunkpos/* bytes left in chunk*/)
  1169. cb = (size_t)/*SAFE*/(chunklen - chunkpos);
  1170. memcpy(ps->new.buffer + writepos, pb, cb);
  1171. chunkpos += (png_uint_32)/*SAFE*/cb;
  1172. pb += cb;
  1173. writepos += cb;
  1174. st -= cb;
  1175. if (chunkpos >= chunklen) /* must be equal */
  1176. chunkpos = chunktype = chunklen = 0;
  1177. }
  1178. } /* while (st > 0) */
  1179. ps->writepos = writepos;
  1180. ps->chunkpos = chunkpos;
  1181. ps->chunktype = chunktype;
  1182. ps->chunklen = chunklen;
  1183. }
  1184. static void PNGCBAPI
  1185. store_flush(png_structp ppIn)
  1186. {
  1187. UNUSED(ppIn) /*DOES NOTHING*/
  1188. }
  1189. #ifdef PNG_READ_SUPPORTED
  1190. static size_t
  1191. store_read_buffer_size(png_store *ps)
  1192. {
  1193. /* Return the bytes available for read in the current buffer. */
  1194. if (ps->next != &ps->current->data)
  1195. return STORE_BUFFER_SIZE;
  1196. return ps->current->datacount;
  1197. }
  1198. /* Return total bytes available for read. */
  1199. static size_t
  1200. store_read_buffer_avail(png_store *ps)
  1201. {
  1202. if (ps->current != NULL && ps->next != NULL)
  1203. {
  1204. png_store_buffer *next = &ps->current->data;
  1205. size_t cbAvail = ps->current->datacount;
  1206. while (next != ps->next && next != NULL)
  1207. {
  1208. next = next->prev;
  1209. cbAvail += STORE_BUFFER_SIZE;
  1210. }
  1211. if (next != ps->next)
  1212. png_error(ps->pread, "buffer read error");
  1213. if (cbAvail > ps->readpos)
  1214. return cbAvail - ps->readpos;
  1215. }
  1216. return 0;
  1217. }
  1218. static int
  1219. store_read_buffer_next(png_store *ps)
  1220. {
  1221. png_store_buffer *pbOld = ps->next;
  1222. png_store_buffer *pbNew = &ps->current->data;
  1223. if (pbOld != pbNew)
  1224. {
  1225. while (pbNew != NULL && pbNew->prev != pbOld)
  1226. pbNew = pbNew->prev;
  1227. if (pbNew != NULL)
  1228. {
  1229. ps->next = pbNew;
  1230. ps->readpos = 0;
  1231. return 1;
  1232. }
  1233. png_error(ps->pread, "buffer lost");
  1234. }
  1235. return 0; /* EOF or error */
  1236. }
  1237. /* Need separate implementation and callback to allow use of the same code
  1238. * during progressive read, where the io_ptr is set internally by libpng.
  1239. */
  1240. static void
  1241. store_read_imp(png_store *ps, png_bytep pb, size_t st)
  1242. {
  1243. if (ps->current == NULL || ps->next == NULL)
  1244. png_error(ps->pread, "store state damaged");
  1245. while (st > 0)
  1246. {
  1247. size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
  1248. if (cbAvail > 0)
  1249. {
  1250. if (cbAvail > st) cbAvail = st;
  1251. memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
  1252. st -= cbAvail;
  1253. pb += cbAvail;
  1254. ps->readpos += cbAvail;
  1255. }
  1256. else if (!store_read_buffer_next(ps))
  1257. png_error(ps->pread, "read beyond end of file");
  1258. }
  1259. }
  1260. static size_t
  1261. store_read_chunk(png_store *ps, png_bytep pb, size_t max, size_t min)
  1262. {
  1263. png_uint_32 chunklen = ps->chunklen;
  1264. png_uint_32 chunktype = ps->chunktype;
  1265. png_uint_32 chunkpos = ps->chunkpos;
  1266. size_t st = max;
  1267. if (st > 0) do
  1268. {
  1269. if (chunkpos >= chunklen) /* end of last chunk */
  1270. {
  1271. png_byte buffer[8];
  1272. /* Read the header of the next chunk: */
  1273. store_read_imp(ps, buffer, 8U);
  1274. chunklen = png_get_uint_32(buffer) + 12U;
  1275. chunktype = png_get_uint_32(buffer+4U);
  1276. chunkpos = 0U; /* Position read so far */
  1277. }
  1278. if (chunktype == CHUNK_IDAT)
  1279. {
  1280. png_uint_32 IDAT_pos = ps->IDAT_pos;
  1281. png_uint_32 IDAT_len = ps->IDAT_len;
  1282. png_uint_32 IDAT_size = ps->IDAT_size;
  1283. /* The IDAT headers are constructed here; skip the input header. */
  1284. if (chunkpos < 8U)
  1285. chunkpos = 8U;
  1286. if (IDAT_pos == IDAT_len)
  1287. {
  1288. png_byte random = random_byte();
  1289. /* Make a new IDAT chunk, if IDAT_len is 0 this is the first IDAT,
  1290. * if IDAT_size is 0 this is the end. At present this is set up
  1291. * using a random number so that there is a 25% chance before
  1292. * the start of the first IDAT chunk being 0 length.
  1293. */
  1294. if (IDAT_len == 0U) /* First IDAT */
  1295. {
  1296. switch (random & 3U)
  1297. {
  1298. case 0U: IDAT_len = 12U; break; /* 0 bytes */
  1299. case 1U: IDAT_len = 13U; break; /* 1 byte */
  1300. default: IDAT_len = random_u32();
  1301. IDAT_len %= IDAT_size;
  1302. IDAT_len += 13U; /* 1..IDAT_size bytes */
  1303. break;
  1304. }
  1305. }
  1306. else if (IDAT_size == 0U) /* all IDAT data read */
  1307. {
  1308. /* The last (IDAT) chunk should be positioned at the CRC now: */
  1309. if (chunkpos != chunklen-4U)
  1310. png_error(ps->pread, "internal: IDAT size mismatch");
  1311. /* The only option here is to add a zero length IDAT, this
  1312. * happens 25% of the time. Because of the check above
  1313. * chunklen-4U-chunkpos must be zero, we just need to skip the
  1314. * CRC now.
  1315. */
  1316. if ((random & 3U) == 0U)
  1317. IDAT_len = 12U; /* Output another 0 length IDAT */
  1318. else
  1319. {
  1320. /* End of IDATs, skip the CRC to make the code above load the
  1321. * next chunk header next time round.
  1322. */
  1323. png_byte buffer[4];
  1324. store_read_imp(ps, buffer, 4U);
  1325. chunkpos += 4U;
  1326. ps->IDAT_pos = IDAT_pos;
  1327. ps->IDAT_len = IDAT_len;
  1328. ps->IDAT_size = 0U;
  1329. continue; /* Read the next chunk */
  1330. }
  1331. }
  1332. else
  1333. {
  1334. /* Middle of IDATs, use 'random' to determine the number of bits
  1335. * to use in the IDAT length.
  1336. */
  1337. IDAT_len = random_u32();
  1338. IDAT_len &= (1U << (1U + random % ps->IDAT_bits)) - 1U;
  1339. if (IDAT_len > IDAT_size)
  1340. IDAT_len = IDAT_size;
  1341. IDAT_len += 12U; /* zero bytes may occur */
  1342. }
  1343. IDAT_pos = 0U;
  1344. ps->IDAT_crc = 0x35af061e; /* Ie: crc32(0UL, "IDAT", 4) */
  1345. } /* IDAT_pos == IDAT_len */
  1346. if (IDAT_pos < 8U) /* Return the header */ do
  1347. {
  1348. png_uint_32 b;
  1349. unsigned int shift;
  1350. if (IDAT_pos < 4U)
  1351. b = IDAT_len - 12U;
  1352. else
  1353. b = CHUNK_IDAT;
  1354. shift = 3U & IDAT_pos;
  1355. ++IDAT_pos;
  1356. if (shift < 3U)
  1357. b >>= 8U*(3U-shift);
  1358. *pb++ = 0xffU & b;
  1359. }
  1360. while (--st > 0 && IDAT_pos < 8);
  1361. else if (IDAT_pos < IDAT_len - 4U) /* I.e not the CRC */
  1362. {
  1363. if (chunkpos < chunklen-4U)
  1364. {
  1365. uInt avail = (uInt)-1;
  1366. if (avail > (IDAT_len-4U) - IDAT_pos)
  1367. avail = (uInt)/*SAFE*/((IDAT_len-4U) - IDAT_pos);
  1368. if (avail > st)
  1369. avail = (uInt)/*SAFE*/st;
  1370. if (avail > (chunklen-4U) - chunkpos)
  1371. avail = (uInt)/*SAFE*/((chunklen-4U) - chunkpos);
  1372. store_read_imp(ps, pb, avail);
  1373. ps->IDAT_crc = crc32(ps->IDAT_crc, pb, avail);
  1374. pb += (size_t)/*SAFE*/avail;
  1375. st -= (size_t)/*SAFE*/avail;
  1376. chunkpos += (png_uint_32)/*SAFE*/avail;
  1377. IDAT_size -= (png_uint_32)/*SAFE*/avail;
  1378. IDAT_pos += (png_uint_32)/*SAFE*/avail;
  1379. }
  1380. else /* skip the input CRC */
  1381. {
  1382. png_byte buffer[4];
  1383. store_read_imp(ps, buffer, 4U);
  1384. chunkpos += 4U;
  1385. }
  1386. }
  1387. else /* IDAT crc */ do
  1388. {
  1389. uLong b = ps->IDAT_crc;
  1390. unsigned int shift = (IDAT_len - IDAT_pos); /* 4..1 */
  1391. ++IDAT_pos;
  1392. if (shift > 1U)
  1393. b >>= 8U*(shift-1U);
  1394. *pb++ = 0xffU & b;
  1395. }
  1396. while (--st > 0 && IDAT_pos < IDAT_len);
  1397. ps->IDAT_pos = IDAT_pos;
  1398. ps->IDAT_len = IDAT_len;
  1399. ps->IDAT_size = IDAT_size;
  1400. }
  1401. else /* !IDAT */
  1402. {
  1403. /* If there is still some pending IDAT data after the IDAT chunks have
  1404. * been processed there is a problem:
  1405. */
  1406. if (ps->IDAT_len > 0 && ps->IDAT_size > 0)
  1407. png_error(ps->pread, "internal: missing IDAT data");
  1408. if (chunktype == CHUNK_IEND && ps->IDAT_len == 0U)
  1409. png_error(ps->pread, "internal: missing IDAT");
  1410. if (chunkpos < 8U) /* Return the header */ do
  1411. {
  1412. png_uint_32 b;
  1413. unsigned int shift;
  1414. if (chunkpos < 4U)
  1415. b = chunklen - 12U;
  1416. else
  1417. b = chunktype;
  1418. shift = 3U & chunkpos;
  1419. ++chunkpos;
  1420. if (shift < 3U)
  1421. b >>= 8U*(3U-shift);
  1422. *pb++ = 0xffU & b;
  1423. }
  1424. while (--st > 0 && chunkpos < 8);
  1425. else /* Return chunk bytes, including the CRC */
  1426. {
  1427. size_t avail = st;
  1428. if (avail > chunklen - chunkpos)
  1429. avail = (size_t)/*SAFE*/(chunklen - chunkpos);
  1430. store_read_imp(ps, pb, avail);
  1431. pb += avail;
  1432. st -= avail;
  1433. chunkpos += (png_uint_32)/*SAFE*/avail;
  1434. /* Check for end of chunk and end-of-file; don't try to read a new
  1435. * chunk header at this point unless instructed to do so by 'min'.
  1436. */
  1437. if (chunkpos >= chunklen && max-st >= min &&
  1438. store_read_buffer_avail(ps) == 0)
  1439. break;
  1440. }
  1441. } /* !IDAT */
  1442. }
  1443. while (st > 0);
  1444. ps->chunklen = chunklen;
  1445. ps->chunktype = chunktype;
  1446. ps->chunkpos = chunkpos;
  1447. return st; /* space left */
  1448. }
  1449. static void PNGCBAPI
  1450. store_read(png_structp ppIn, png_bytep pb, size_t st)
  1451. {
  1452. png_const_structp pp = ppIn;
  1453. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  1454. if (ps == NULL || ps->pread != pp)
  1455. png_error(pp, "bad store read call");
  1456. store_read_chunk(ps, pb, st, st);
  1457. }
  1458. static void
  1459. store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
  1460. {
  1461. if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
  1462. png_error(pp, "store state damaged (progressive)");
  1463. /* This is another Horowitz and Hill random noise generator. In this case
  1464. * the aim is to stress the progressive reader with truly horrible variable
  1465. * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
  1466. * is generated. We could probably just count from 1 to 32767 and get as
  1467. * good a result.
  1468. */
  1469. while (store_read_buffer_avail(ps) > 0)
  1470. {
  1471. static png_uint_32 noise = 2;
  1472. size_t cb;
  1473. png_byte buffer[512];
  1474. /* Generate 15 more bits of stuff: */
  1475. noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
  1476. cb = noise & 0x1ff;
  1477. cb -= store_read_chunk(ps, buffer, cb, 1);
  1478. png_process_data(pp, pi, buffer, cb);
  1479. }
  1480. }
  1481. #endif /* PNG_READ_SUPPORTED */
  1482. /* The caller must fill this in: */
  1483. static store_palette_entry *
  1484. store_write_palette(png_store *ps, int npalette)
  1485. {
  1486. if (ps->pwrite == NULL)
  1487. store_log(ps, NULL, "attempt to write palette without write stream", 1);
  1488. if (ps->palette != NULL)
  1489. png_error(ps->pwrite, "multiple store_write_palette calls");
  1490. /* This function can only return NULL if called with '0'! */
  1491. if (npalette > 0)
  1492. {
  1493. ps->palette = voidcast(store_palette_entry*, malloc(npalette *
  1494. sizeof *ps->palette));
  1495. if (ps->palette == NULL)
  1496. png_error(ps->pwrite, "store new palette: OOM");
  1497. ps->npalette = npalette;
  1498. }
  1499. return ps->palette;
  1500. }
  1501. #ifdef PNG_READ_SUPPORTED
  1502. static store_palette_entry *
  1503. store_current_palette(png_store *ps, int *npalette)
  1504. {
  1505. /* This is an internal error (the call has been made outside a read
  1506. * operation.)
  1507. */
  1508. if (ps->current == NULL)
  1509. {
  1510. store_log(ps, ps->pread, "no current stream for palette", 1);
  1511. return NULL;
  1512. }
  1513. /* The result may be null if there is no palette. */
  1514. *npalette = ps->current->npalette;
  1515. return ps->current->palette;
  1516. }
  1517. #endif /* PNG_READ_SUPPORTED */
  1518. /***************************** MEMORY MANAGEMENT*** ***************************/
  1519. #ifdef PNG_USER_MEM_SUPPORTED
  1520. /* A store_memory is simply the header for an allocated block of memory. The
  1521. * pointer returned to libpng is just after the end of the header block, the
  1522. * allocated memory is followed by a second copy of the 'mark'.
  1523. */
  1524. typedef struct store_memory
  1525. {
  1526. store_pool *pool; /* Originating pool */
  1527. struct store_memory *next; /* Singly linked list */
  1528. png_alloc_size_t size; /* Size of memory allocated */
  1529. png_byte mark[4]; /* ID marker */
  1530. } store_memory;
  1531. /* Handle a fatal error in memory allocation. This calls png_error if the
  1532. * libpng struct is non-NULL, else it outputs a message and returns. This means
  1533. * that a memory problem while libpng is running will abort (png_error) the
  1534. * handling of particular file while one in cleanup (after the destroy of the
  1535. * struct has returned) will simply keep going and free (or attempt to free)
  1536. * all the memory.
  1537. */
  1538. static void
  1539. store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
  1540. {
  1541. if (pp != NULL)
  1542. png_error(pp, msg);
  1543. /* Else we have to do it ourselves. png_error eventually calls store_log,
  1544. * above. store_log accepts a NULL png_structp - it just changes what gets
  1545. * output by store_message.
  1546. */
  1547. store_log(ps, pp, msg, 1 /* error */);
  1548. }
  1549. static void
  1550. store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
  1551. {
  1552. /* Note that pp may be NULL (see store_pool_delete below), the caller has
  1553. * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
  1554. * pointer (for sure), but the contents may have been trashed.
  1555. */
  1556. if (memory->pool != pool)
  1557. store_pool_error(pool->store, pp, "memory corrupted (pool)");
  1558. else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
  1559. store_pool_error(pool->store, pp, "memory corrupted (start)");
  1560. /* It should be safe to read the size field now. */
  1561. else
  1562. {
  1563. png_alloc_size_t cb = memory->size;
  1564. if (cb > pool->max)
  1565. store_pool_error(pool->store, pp, "memory corrupted (size)");
  1566. else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
  1567. != 0)
  1568. store_pool_error(pool->store, pp, "memory corrupted (end)");
  1569. /* Finally give the library a chance to find problems too: */
  1570. else
  1571. {
  1572. pool->current -= cb;
  1573. free(memory);
  1574. }
  1575. }
  1576. }
  1577. static void
  1578. store_pool_delete(png_store *ps, store_pool *pool)
  1579. {
  1580. if (pool->list != NULL)
  1581. {
  1582. fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
  1583. pool == &ps->read_memory_pool ? "read" : "write",
  1584. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1585. ps->current->name : "unknown file") : ps->wname);
  1586. ++ps->nerrors;
  1587. do
  1588. {
  1589. store_memory *next = pool->list;
  1590. pool->list = next->next;
  1591. next->next = NULL;
  1592. fprintf(stderr, "\t%lu bytes @ %p\n",
  1593. (unsigned long)next->size, (const void*)(next+1));
  1594. /* The NULL means this will always return, even if the memory is
  1595. * corrupted.
  1596. */
  1597. store_memory_free(NULL, pool, next);
  1598. }
  1599. while (pool->list != NULL);
  1600. }
  1601. /* And reset the other fields too for the next time. */
  1602. if (pool->max > pool->max_max) pool->max_max = pool->max;
  1603. pool->max = 0;
  1604. if (pool->current != 0) /* unexpected internal error */
  1605. fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
  1606. ps->test, pool == &ps->read_memory_pool ? "read" : "write",
  1607. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1608. ps->current->name : "unknown file") : ps->wname);
  1609. pool->current = 0;
  1610. if (pool->limit > pool->max_limit)
  1611. pool->max_limit = pool->limit;
  1612. pool->limit = 0;
  1613. if (pool->total > pool->max_total)
  1614. pool->max_total = pool->total;
  1615. pool->total = 0;
  1616. /* Get a new mark too. */
  1617. store_pool_mark(pool->mark);
  1618. }
  1619. /* The memory callbacks: */
  1620. static png_voidp PNGCBAPI
  1621. store_malloc(png_structp ppIn, png_alloc_size_t cb)
  1622. {
  1623. png_const_structp pp = ppIn;
  1624. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1625. store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
  1626. (sizeof pool->mark)));
  1627. if (new != NULL)
  1628. {
  1629. if (cb > pool->max)
  1630. pool->max = cb;
  1631. pool->current += cb;
  1632. if (pool->current > pool->limit)
  1633. pool->limit = pool->current;
  1634. pool->total += cb;
  1635. new->size = cb;
  1636. memcpy(new->mark, pool->mark, sizeof new->mark);
  1637. memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
  1638. new->pool = pool;
  1639. new->next = pool->list;
  1640. pool->list = new;
  1641. ++new;
  1642. }
  1643. else
  1644. {
  1645. /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
  1646. * other than to retrieve the allocation pointer! libpng calls the
  1647. * store_malloc callback in two basic cases:
  1648. *
  1649. * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
  1650. * returned.
  1651. * 2) From png_struct or png_info structure creation; png_malloc is
  1652. * to return so cleanup can be performed.
  1653. *
  1654. * To handle this store_malloc can log a message, but can't do anything
  1655. * else.
  1656. */
  1657. store_log(pool->store, pp, "out of memory", 1 /* is_error */);
  1658. }
  1659. return new;
  1660. }
  1661. static void PNGCBAPI
  1662. store_free(png_structp ppIn, png_voidp memory)
  1663. {
  1664. png_const_structp pp = ppIn;
  1665. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1666. store_memory *this = voidcast(store_memory*, memory), **test;
  1667. /* Because libpng calls store_free with a dummy png_struct when deleting
  1668. * png_struct or png_info via png_destroy_struct_2 it is necessary to check
  1669. * the passed in png_structp to ensure it is valid, and not pass it to
  1670. * png_error if it is not.
  1671. */
  1672. if (pp != pool->store->pread && pp != pool->store->pwrite)
  1673. pp = NULL;
  1674. /* First check that this 'memory' really is valid memory - it must be in the
  1675. * pool list. If it is, use the shared memory_free function to free it.
  1676. */
  1677. --this;
  1678. for (test = &pool->list; *test != this; test = &(*test)->next)
  1679. {
  1680. if (*test == NULL)
  1681. {
  1682. store_pool_error(pool->store, pp, "bad pointer to free");
  1683. return;
  1684. }
  1685. }
  1686. /* Unlink this entry, *test == this. */
  1687. *test = this->next;
  1688. this->next = NULL;
  1689. store_memory_free(pp, pool, this);
  1690. }
  1691. #endif /* PNG_USER_MEM_SUPPORTED */
  1692. /* Setup functions. */
  1693. /* Cleanup when aborting a write or after storing the new file. */
  1694. static void
  1695. store_write_reset(png_store *ps)
  1696. {
  1697. if (ps->pwrite != NULL)
  1698. {
  1699. anon_context(ps);
  1700. Try
  1701. png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
  1702. Catch_anonymous
  1703. {
  1704. /* memory corruption: continue. */
  1705. }
  1706. ps->pwrite = NULL;
  1707. ps->piwrite = NULL;
  1708. }
  1709. /* And make sure that all the memory has been freed - this will output
  1710. * spurious errors in the case of memory corruption above, but this is safe.
  1711. */
  1712. # ifdef PNG_USER_MEM_SUPPORTED
  1713. store_pool_delete(ps, &ps->write_memory_pool);
  1714. # endif
  1715. store_freenew(ps);
  1716. }
  1717. /* The following is the main write function, it returns a png_struct and,
  1718. * optionally, a png_info suitable for writiing a new PNG file. Use
  1719. * store_storefile above to record this file after it has been written. The
  1720. * returned libpng structures as destroyed by store_write_reset above.
  1721. */
  1722. static png_structp
  1723. set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
  1724. {
  1725. anon_context(ps);
  1726. Try
  1727. {
  1728. if (ps->pwrite != NULL)
  1729. png_error(ps->pwrite, "write store already in use");
  1730. store_write_reset(ps);
  1731. safecat(ps->wname, sizeof ps->wname, 0, name);
  1732. /* Don't do the slow memory checks if doing a speed test, also if user
  1733. * memory is not supported we can't do it anyway.
  1734. */
  1735. # ifdef PNG_USER_MEM_SUPPORTED
  1736. if (!ps->speed)
  1737. ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
  1738. ps, store_error, store_warning, &ps->write_memory_pool,
  1739. store_malloc, store_free);
  1740. else
  1741. # endif
  1742. ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  1743. ps, store_error, store_warning);
  1744. png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
  1745. # ifdef PNG_SET_OPTION_SUPPORTED
  1746. {
  1747. int opt;
  1748. for (opt=0; opt<ps->noptions; ++opt)
  1749. if (png_set_option(ps->pwrite, ps->options[opt].option,
  1750. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1751. png_error(ps->pwrite, "png option invalid");
  1752. }
  1753. # endif
  1754. if (ppi != NULL)
  1755. *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
  1756. }
  1757. Catch_anonymous
  1758. return NULL;
  1759. return ps->pwrite;
  1760. }
  1761. /* Cleanup when finished reading (either due to error or in the success case).
  1762. * This routine exists even when there is no read support to make the code
  1763. * tidier (avoid a mass of ifdefs) and so easier to maintain.
  1764. */
  1765. static void
  1766. store_read_reset(png_store *ps)
  1767. {
  1768. # ifdef PNG_READ_SUPPORTED
  1769. if (ps->pread != NULL)
  1770. {
  1771. anon_context(ps);
  1772. Try
  1773. png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
  1774. Catch_anonymous
  1775. {
  1776. /* error already output: continue */
  1777. }
  1778. ps->pread = NULL;
  1779. ps->piread = NULL;
  1780. }
  1781. # endif
  1782. # ifdef PNG_USER_MEM_SUPPORTED
  1783. /* Always do this to be safe. */
  1784. store_pool_delete(ps, &ps->read_memory_pool);
  1785. # endif
  1786. ps->current = NULL;
  1787. ps->next = NULL;
  1788. ps->readpos = 0;
  1789. ps->validated = 0;
  1790. ps->chunkpos = 8;
  1791. ps->chunktype = 0;
  1792. ps->chunklen = 16;
  1793. ps->IDAT_size = 0;
  1794. }
  1795. #ifdef PNG_READ_SUPPORTED
  1796. static void
  1797. store_read_set(png_store *ps, png_uint_32 id)
  1798. {
  1799. png_store_file *pf = ps->saved;
  1800. while (pf != NULL)
  1801. {
  1802. if (pf->id == id)
  1803. {
  1804. ps->current = pf;
  1805. ps->next = NULL;
  1806. ps->IDAT_size = pf->IDAT_size;
  1807. ps->IDAT_bits = pf->IDAT_bits; /* just a cache */
  1808. ps->IDAT_len = 0;
  1809. ps->IDAT_pos = 0;
  1810. ps->IDAT_crc = 0UL;
  1811. store_read_buffer_next(ps);
  1812. return;
  1813. }
  1814. pf = pf->next;
  1815. }
  1816. {
  1817. size_t pos;
  1818. char msg[FILE_NAME_SIZE+64];
  1819. pos = standard_name_from_id(msg, sizeof msg, 0, id);
  1820. pos = safecat(msg, sizeof msg, pos, ": file not found");
  1821. png_error(ps->pread, msg);
  1822. }
  1823. }
  1824. /* The main interface for reading a saved file - pass the id number of the file
  1825. * to retrieve. Ids must be unique or the earlier file will be hidden. The API
  1826. * returns a png_struct and, optionally, a png_info. Both of these will be
  1827. * destroyed by store_read_reset above.
  1828. */
  1829. static png_structp
  1830. set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
  1831. const char *name)
  1832. {
  1833. /* Set the name for png_error */
  1834. safecat(ps->test, sizeof ps->test, 0, name);
  1835. if (ps->pread != NULL)
  1836. png_error(ps->pread, "read store already in use");
  1837. store_read_reset(ps);
  1838. /* Both the create APIs can return NULL if used in their default mode
  1839. * (because there is no other way of handling an error because the jmp_buf
  1840. * by default is stored in png_struct and that has not been allocated!)
  1841. * However, given that store_error works correctly in these circumstances
  1842. * we don't ever expect NULL in this program.
  1843. */
  1844. # ifdef PNG_USER_MEM_SUPPORTED
  1845. if (!ps->speed)
  1846. ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
  1847. store_error, store_warning, &ps->read_memory_pool, store_malloc,
  1848. store_free);
  1849. else
  1850. # endif
  1851. ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
  1852. store_warning);
  1853. if (ps->pread == NULL)
  1854. {
  1855. struct exception_context *the_exception_context = &ps->exception_context;
  1856. store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
  1857. 1 /*error*/);
  1858. Throw ps;
  1859. }
  1860. # ifdef PNG_SET_OPTION_SUPPORTED
  1861. {
  1862. int opt;
  1863. for (opt=0; opt<ps->noptions; ++opt)
  1864. if (png_set_option(ps->pread, ps->options[opt].option,
  1865. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1866. png_error(ps->pread, "png option invalid");
  1867. }
  1868. # endif
  1869. store_read_set(ps, id);
  1870. if (ppi != NULL)
  1871. *ppi = ps->piread = png_create_info_struct(ps->pread);
  1872. return ps->pread;
  1873. }
  1874. #endif /* PNG_READ_SUPPORTED */
  1875. /* The overall cleanup of a store simply calls the above then removes all the
  1876. * saved files. This does not delete the store itself.
  1877. */
  1878. static void
  1879. store_delete(png_store *ps)
  1880. {
  1881. store_write_reset(ps);
  1882. store_read_reset(ps);
  1883. store_freefile(&ps->saved);
  1884. store_image_free(ps, NULL);
  1885. }
  1886. /*********************** PNG FILE MODIFICATION ON READ ************************/
  1887. /* Files may be modified on read. The following structure contains a complete
  1888. * png_store together with extra members to handle modification and a special
  1889. * read callback for libpng. To use this the 'modifications' field must be set
  1890. * to a list of png_modification structures that actually perform the
  1891. * modification, otherwise a png_modifier is functionally equivalent to a
  1892. * png_store. There is a special read function, set_modifier_for_read, which
  1893. * replaces set_store_for_read.
  1894. */
  1895. typedef enum modifier_state
  1896. {
  1897. modifier_start, /* Initial value */
  1898. modifier_signature, /* Have a signature */
  1899. modifier_IHDR /* Have an IHDR */
  1900. } modifier_state;
  1901. typedef struct CIE_color
  1902. {
  1903. /* A single CIE tristimulus value, representing the unique response of a
  1904. * standard observer to a variety of light spectra. The observer recognizes
  1905. * all spectra that produce this response as the same color, therefore this
  1906. * is effectively a description of a color.
  1907. */
  1908. double X, Y, Z;
  1909. } CIE_color;
  1910. typedef struct color_encoding
  1911. {
  1912. /* A description of an (R,G,B) encoding of color (as defined above); this
  1913. * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
  1914. * (0,0,1) plus an encoding value that is used to encode the linear
  1915. * components R, G and B to give the actual values R^gamma, G^gamma and
  1916. * B^gamma that are stored.
  1917. */
  1918. double gamma; /* Encoding (file) gamma of space */
  1919. CIE_color red, green, blue; /* End points */
  1920. } color_encoding;
  1921. #ifdef PNG_READ_SUPPORTED
  1922. #if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED
  1923. static double
  1924. chromaticity_x(CIE_color c)
  1925. {
  1926. return c.X / (c.X + c.Y + c.Z);
  1927. }
  1928. static double
  1929. chromaticity_y(CIE_color c)
  1930. {
  1931. return c.Y / (c.X + c.Y + c.Z);
  1932. }
  1933. static CIE_color
  1934. white_point(const color_encoding *encoding)
  1935. {
  1936. CIE_color white;
  1937. white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
  1938. white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
  1939. white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
  1940. return white;
  1941. }
  1942. #endif /* READ_TRANSFORMS && READ_cHRM */
  1943. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1944. static void
  1945. normalize_color_encoding(color_encoding *encoding)
  1946. {
  1947. const double whiteY = encoding->red.Y + encoding->green.Y +
  1948. encoding->blue.Y;
  1949. if (whiteY != 1)
  1950. {
  1951. encoding->red.X /= whiteY;
  1952. encoding->red.Y /= whiteY;
  1953. encoding->red.Z /= whiteY;
  1954. encoding->green.X /= whiteY;
  1955. encoding->green.Y /= whiteY;
  1956. encoding->green.Z /= whiteY;
  1957. encoding->blue.X /= whiteY;
  1958. encoding->blue.Y /= whiteY;
  1959. encoding->blue.Z /= whiteY;
  1960. }
  1961. }
  1962. #endif
  1963. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  1964. static size_t
  1965. safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
  1966. const color_encoding *e, double encoding_gamma)
  1967. {
  1968. if (e != 0)
  1969. {
  1970. if (encoding_gamma != 0)
  1971. pos = safecat(buffer, bufsize, pos, "(");
  1972. pos = safecat(buffer, bufsize, pos, "R(");
  1973. pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
  1974. pos = safecat(buffer, bufsize, pos, ",");
  1975. pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
  1976. pos = safecat(buffer, bufsize, pos, ",");
  1977. pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
  1978. pos = safecat(buffer, bufsize, pos, "),G(");
  1979. pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
  1980. pos = safecat(buffer, bufsize, pos, ",");
  1981. pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
  1982. pos = safecat(buffer, bufsize, pos, ",");
  1983. pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
  1984. pos = safecat(buffer, bufsize, pos, "),B(");
  1985. pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
  1986. pos = safecat(buffer, bufsize, pos, ",");
  1987. pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
  1988. pos = safecat(buffer, bufsize, pos, ",");
  1989. pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
  1990. pos = safecat(buffer, bufsize, pos, ")");
  1991. if (encoding_gamma != 0)
  1992. pos = safecat(buffer, bufsize, pos, ")");
  1993. }
  1994. if (encoding_gamma != 0)
  1995. {
  1996. pos = safecat(buffer, bufsize, pos, "^");
  1997. pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
  1998. }
  1999. return pos;
  2000. }
  2001. #endif /* READ_TRANSFORMS */
  2002. #endif /* PNG_READ_SUPPORTED */
  2003. typedef struct png_modifier
  2004. {
  2005. png_store this; /* I am a png_store */
  2006. struct png_modification *modifications; /* Changes to make */
  2007. modifier_state state; /* My state */
  2008. /* Information from IHDR: */
  2009. png_byte bit_depth; /* From IHDR */
  2010. png_byte colour_type; /* From IHDR */
  2011. /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
  2012. * other chunks to be inserted.
  2013. */
  2014. png_uint_32 pending_len;
  2015. png_uint_32 pending_chunk;
  2016. /* Test values */
  2017. double *gammas;
  2018. unsigned int ngammas;
  2019. unsigned int ngamma_tests; /* Number of gamma tests to run*/
  2020. double current_gamma; /* 0 if not set */
  2021. const color_encoding *encodings;
  2022. unsigned int nencodings;
  2023. const color_encoding *current_encoding; /* If an encoding has been set */
  2024. unsigned int encoding_counter; /* For iteration */
  2025. int encoding_ignored; /* Something overwrote it */
  2026. /* Control variables used to iterate through possible encodings, the
  2027. * following must be set to 0 and tested by the function that uses the
  2028. * png_modifier because the modifier only sets it to 1 (true.)
  2029. */
  2030. unsigned int repeat :1; /* Repeat this transform test. */
  2031. unsigned int test_uses_encoding :1;
  2032. /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */
  2033. png_byte sbitlow;
  2034. /* Error control - these are the limits on errors accepted by the gamma tests
  2035. * below.
  2036. */
  2037. double maxout8; /* Maximum output value error */
  2038. double maxabs8; /* Absolute sample error 0..1 */
  2039. double maxcalc8; /* Absolute sample error 0..1 */
  2040. double maxpc8; /* Percentage sample error 0..100% */
  2041. double maxout16; /* Maximum output value error */
  2042. double maxabs16; /* Absolute sample error 0..1 */
  2043. double maxcalc16;/* Absolute sample error 0..1 */
  2044. double maxcalcG; /* Absolute sample error 0..1 */
  2045. double maxpc16; /* Percentage sample error 0..100% */
  2046. /* This is set by transforms that need to allow a higher limit, it is an
  2047. * internal check on pngvalid to ensure that the calculated error limits are
  2048. * not ridiculous; without this it is too easy to make a mistake in pngvalid
  2049. * that allows any value through.
  2050. *
  2051. * NOTE: this is not checked in release builds.
  2052. */
  2053. double limit; /* limit on error values, normally 4E-3 */
  2054. /* Log limits - values above this are logged, but not necessarily
  2055. * warned.
  2056. */
  2057. double log8; /* Absolute error in 8 bits to log */
  2058. double log16; /* Absolute error in 16 bits to log */
  2059. /* Logged 8 and 16 bit errors ('output' values): */
  2060. double error_gray_2;
  2061. double error_gray_4;
  2062. double error_gray_8;
  2063. double error_gray_16;
  2064. double error_color_8;
  2065. double error_color_16;
  2066. double error_indexed;
  2067. /* Flags: */
  2068. /* Whether to call png_read_update_info, not png_read_start_image, and how
  2069. * many times to call it.
  2070. */
  2071. int use_update_info;
  2072. /* Whether or not to interlace. */
  2073. int interlace_type :9; /* int, but must store '1' */
  2074. /* Run the standard tests? */
  2075. unsigned int test_standard :1;
  2076. /* Run the odd-sized image and interlace read/write tests? */
  2077. unsigned int test_size :1;
  2078. /* Run tests on reading with a combination of transforms, */
  2079. unsigned int test_transform :1;
  2080. unsigned int test_tRNS :1; /* Includes tRNS images */
  2081. /* When to use the use_input_precision option, this controls the gamma
  2082. * validation code checks. If set any value that is within the transformed
  2083. * range input-.5 to input+.5 will be accepted, otherwise the value must be
  2084. * within the normal limits. It should not be necessary to set this; the
  2085. * result should always be exact within the permitted error limits.
  2086. */
  2087. unsigned int use_input_precision :1;
  2088. unsigned int use_input_precision_sbit :1;
  2089. unsigned int use_input_precision_16to8 :1;
  2090. /* If set assume that the calculation bit depth is set by the input
  2091. * precision, not the output precision.
  2092. */
  2093. unsigned int calculations_use_input_precision :1;
  2094. /* If set assume that the calculations are done in 16 bits even if the sample
  2095. * depth is 8 bits.
  2096. */
  2097. unsigned int assume_16_bit_calculations :1;
  2098. /* Which gamma tests to run: */
  2099. unsigned int test_gamma_threshold :1;
  2100. unsigned int test_gamma_transform :1; /* main tests */
  2101. unsigned int test_gamma_sbit :1;
  2102. unsigned int test_gamma_scale16 :1;
  2103. unsigned int test_gamma_background :1;
  2104. unsigned int test_gamma_alpha_mode :1;
  2105. unsigned int test_gamma_expand16 :1;
  2106. unsigned int test_exhaustive :1;
  2107. /* Whether or not to run the low-bit-depth grayscale tests. This fails on
  2108. * gamma images in some cases because of gross inaccuracies in the grayscale
  2109. * gamma handling for low bit depth.
  2110. */
  2111. unsigned int test_lbg :1;
  2112. unsigned int test_lbg_gamma_threshold :1;
  2113. unsigned int test_lbg_gamma_transform :1;
  2114. unsigned int test_lbg_gamma_sbit :1;
  2115. unsigned int test_lbg_gamma_composition :1;
  2116. unsigned int log :1; /* Log max error */
  2117. /* Buffer information, the buffer size limits the size of the chunks that can
  2118. * be modified - they must fit (including header and CRC) into the buffer!
  2119. */
  2120. size_t flush; /* Count of bytes to flush */
  2121. size_t buffer_count; /* Bytes in buffer */
  2122. size_t buffer_position; /* Position in buffer */
  2123. png_byte buffer[1024];
  2124. } png_modifier;
  2125. /* This returns true if the test should be stopped now because it has already
  2126. * failed and it is running silently.
  2127. */
  2128. static int fail(png_modifier *pm)
  2129. {
  2130. return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
  2131. (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
  2132. }
  2133. static void
  2134. modifier_init(png_modifier *pm)
  2135. {
  2136. memset(pm, 0, sizeof *pm);
  2137. store_init(&pm->this);
  2138. pm->modifications = NULL;
  2139. pm->state = modifier_start;
  2140. pm->sbitlow = 1U;
  2141. pm->ngammas = 0;
  2142. pm->ngamma_tests = 0;
  2143. pm->gammas = 0;
  2144. pm->current_gamma = 0;
  2145. pm->encodings = 0;
  2146. pm->nencodings = 0;
  2147. pm->current_encoding = 0;
  2148. pm->encoding_counter = 0;
  2149. pm->encoding_ignored = 0;
  2150. pm->repeat = 0;
  2151. pm->test_uses_encoding = 0;
  2152. pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
  2153. pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
  2154. pm->maxcalcG = 0;
  2155. pm->limit = 4E-3;
  2156. pm->log8 = pm->log16 = 0; /* Means 'off' */
  2157. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
  2158. pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
  2159. pm->error_indexed = 0;
  2160. pm->use_update_info = 0;
  2161. pm->interlace_type = PNG_INTERLACE_NONE;
  2162. pm->test_standard = 0;
  2163. pm->test_size = 0;
  2164. pm->test_transform = 0;
  2165. # ifdef PNG_WRITE_tRNS_SUPPORTED
  2166. pm->test_tRNS = 1;
  2167. # else
  2168. pm->test_tRNS = 0;
  2169. # endif
  2170. pm->use_input_precision = 0;
  2171. pm->use_input_precision_sbit = 0;
  2172. pm->use_input_precision_16to8 = 0;
  2173. pm->calculations_use_input_precision = 0;
  2174. pm->assume_16_bit_calculations = 0;
  2175. pm->test_gamma_threshold = 0;
  2176. pm->test_gamma_transform = 0;
  2177. pm->test_gamma_sbit = 0;
  2178. pm->test_gamma_scale16 = 0;
  2179. pm->test_gamma_background = 0;
  2180. pm->test_gamma_alpha_mode = 0;
  2181. pm->test_gamma_expand16 = 0;
  2182. pm->test_lbg = 1;
  2183. pm->test_lbg_gamma_threshold = 1;
  2184. pm->test_lbg_gamma_transform = 1;
  2185. pm->test_lbg_gamma_sbit = 1;
  2186. pm->test_lbg_gamma_composition = 1;
  2187. pm->test_exhaustive = 0;
  2188. pm->log = 0;
  2189. /* Rely on the memset for all the other fields - there are no pointers */
  2190. }
  2191. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  2192. /* This controls use of checks that explicitly know how libpng digitizes the
  2193. * samples in calculations; setting this circumvents simple error limit checking
  2194. * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
  2195. * algorithm.
  2196. */
  2197. #define DIGITIZE PNG_LIBPNG_VER != 10700
  2198. /* If pm->calculations_use_input_precision is set then operations will happen
  2199. * with the precision of the input, not the precision of the output depth.
  2200. *
  2201. * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
  2202. * bit precision. This only affects those of the following limits that pertain
  2203. * to a calculation - not a digitization operation - unless the following API is
  2204. * called directly.
  2205. */
  2206. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  2207. #if DIGITIZE
  2208. static double digitize(double value, int depth, int do_round)
  2209. {
  2210. /* 'value' is in the range 0 to 1, the result is the same value rounded to a
  2211. * multiple of the digitization factor - 8 or 16 bits depending on both the
  2212. * sample depth and the 'assume' setting. Digitization is normally by
  2213. * rounding and 'do_round' should be 1, if it is 0 the digitized value will
  2214. * be truncated.
  2215. */
  2216. unsigned int digitization_factor = (1U << depth) - 1;
  2217. /* Limiting the range is done as a convenience to the caller - it's easier to
  2218. * do it once here than every time at the call site.
  2219. */
  2220. if (value <= 0)
  2221. value = 0;
  2222. else if (value >= 1)
  2223. value = 1;
  2224. value *= digitization_factor;
  2225. if (do_round) value += .5;
  2226. return floor(value)/digitization_factor;
  2227. }
  2228. #endif
  2229. #endif /* RGB_TO_GRAY */
  2230. #ifdef PNG_READ_GAMMA_SUPPORTED
  2231. static double abserr(const png_modifier *pm, int in_depth, int out_depth)
  2232. {
  2233. /* Absolute error permitted in linear values - affected by the bit depth of
  2234. * the calculations.
  2235. */
  2236. if (pm->assume_16_bit_calculations ||
  2237. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2238. return pm->maxabs16;
  2239. else
  2240. return pm->maxabs8;
  2241. }
  2242. static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
  2243. {
  2244. /* Error in the linear composition arithmetic - only relevant when
  2245. * composition actually happens (0 < alpha < 1).
  2246. */
  2247. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2248. return pm->maxcalc16;
  2249. else if (pm->assume_16_bit_calculations)
  2250. return pm->maxcalcG;
  2251. else
  2252. return pm->maxcalc8;
  2253. }
  2254. static double pcerr(const png_modifier *pm, int in_depth, int out_depth)
  2255. {
  2256. /* Percentage error permitted in the linear values. Note that the specified
  2257. * value is a percentage but this routine returns a simple number.
  2258. */
  2259. if (pm->assume_16_bit_calculations ||
  2260. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2261. return pm->maxpc16 * .01;
  2262. else
  2263. return pm->maxpc8 * .01;
  2264. }
  2265. /* Output error - the error in the encoded value. This is determined by the
  2266. * digitization of the output so can be +/-0.5 in the actual output value. In
  2267. * the expand_16 case with the current code in libpng the expand happens after
  2268. * all the calculations are done in 8 bit arithmetic, so even though the output
  2269. * depth is 16 the output error is determined by the 8 bit calculation.
  2270. *
  2271. * This limit is not determined by the bit depth of internal calculations.
  2272. *
  2273. * The specified parameter does *not* include the base .5 digitization error but
  2274. * it is added here.
  2275. */
  2276. static double outerr(const png_modifier *pm, int in_depth, int out_depth)
  2277. {
  2278. /* There is a serious error in the 2 and 4 bit grayscale transform because
  2279. * the gamma table value (8 bits) is simply shifted, not rounded, so the
  2280. * error in 4 bit grayscale gamma is up to the value below. This is a hack
  2281. * to allow pngvalid to succeed:
  2282. *
  2283. * TODO: fix this in libpng
  2284. */
  2285. if (out_depth == 2)
  2286. return .73182-.5;
  2287. if (out_depth == 4)
  2288. return .90644-.5;
  2289. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2290. return pm->maxout16;
  2291. /* This is the case where the value was calculated at 8-bit precision then
  2292. * scaled to 16 bits.
  2293. */
  2294. else if (out_depth == 16)
  2295. return pm->maxout8 * 257;
  2296. else
  2297. return pm->maxout8;
  2298. }
  2299. /* This does the same thing as the above however it returns the value to log,
  2300. * rather than raising a warning. This is useful for debugging to track down
  2301. * exactly what set of parameters cause high error values.
  2302. */
  2303. static double outlog(const png_modifier *pm, int in_depth, int out_depth)
  2304. {
  2305. /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
  2306. * and so must be adjusted for low bit depth grayscale:
  2307. */
  2308. if (out_depth <= 8)
  2309. {
  2310. if (pm->log8 == 0) /* switched off */
  2311. return 256;
  2312. if (out_depth < 8)
  2313. return pm->log8 / 255 * ((1<<out_depth)-1);
  2314. return pm->log8;
  2315. }
  2316. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2317. {
  2318. if (pm->log16 == 0)
  2319. return 65536;
  2320. return pm->log16;
  2321. }
  2322. /* This is the case where the value was calculated at 8-bit precision then
  2323. * scaled to 16 bits.
  2324. */
  2325. if (pm->log8 == 0)
  2326. return 65536;
  2327. return pm->log8 * 257;
  2328. }
  2329. /* This complements the above by providing the appropriate quantization for the
  2330. * final value. Normally this would just be quantization to an integral value,
  2331. * but in the 8 bit calculation case it's actually quantization to a multiple of
  2332. * 257!
  2333. */
  2334. static int output_quantization_factor(const png_modifier *pm, int in_depth,
  2335. int out_depth)
  2336. {
  2337. if (out_depth == 16 && in_depth != 16 &&
  2338. pm->calculations_use_input_precision)
  2339. return 257;
  2340. else
  2341. return 1;
  2342. }
  2343. #endif /* PNG_READ_GAMMA_SUPPORTED */
  2344. /* One modification structure must be provided for each chunk to be modified (in
  2345. * fact more than one can be provided if multiple separate changes are desired
  2346. * for a single chunk.) Modifications include adding a new chunk when a
  2347. * suitable chunk does not exist.
  2348. *
  2349. * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
  2350. * or 'added' as appropriate if the modify_fn returns 1 (true). If the
  2351. * modify_fn is NULL the chunk is simply removed.
  2352. */
  2353. typedef struct png_modification
  2354. {
  2355. struct png_modification *next;
  2356. png_uint_32 chunk;
  2357. /* If the following is NULL all matching chunks will be removed: */
  2358. int (*modify_fn)(struct png_modifier *pm,
  2359. struct png_modification *me, int add);
  2360. /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
  2361. * found and modified (and there is a modify_fn) the modify_fn will be called
  2362. * to add the chunk before the relevant chunk.
  2363. */
  2364. png_uint_32 add;
  2365. unsigned int modified :1; /* Chunk was modified */
  2366. unsigned int added :1; /* Chunk was added */
  2367. unsigned int removed :1; /* Chunk was removed */
  2368. } png_modification;
  2369. static void
  2370. modification_reset(png_modification *pmm)
  2371. {
  2372. if (pmm != NULL)
  2373. {
  2374. pmm->modified = 0;
  2375. pmm->added = 0;
  2376. pmm->removed = 0;
  2377. modification_reset(pmm->next);
  2378. }
  2379. }
  2380. static void
  2381. modification_init(png_modification *pmm)
  2382. {
  2383. memset(pmm, 0, sizeof *pmm);
  2384. pmm->next = NULL;
  2385. pmm->chunk = 0;
  2386. pmm->modify_fn = NULL;
  2387. pmm->add = 0;
  2388. modification_reset(pmm);
  2389. }
  2390. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  2391. static void
  2392. modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
  2393. {
  2394. if (pm->current_encoding != 0)
  2395. *ce = *pm->current_encoding;
  2396. else
  2397. memset(ce, 0, sizeof *ce);
  2398. ce->gamma = pm->current_gamma;
  2399. }
  2400. #endif
  2401. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  2402. static size_t
  2403. safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
  2404. const png_modifier *pm)
  2405. {
  2406. pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
  2407. pm->current_gamma);
  2408. if (pm->encoding_ignored)
  2409. pos = safecat(buffer, bufsize, pos, "[overridden]");
  2410. return pos;
  2411. }
  2412. #endif
  2413. /* Iterate through the usefully testable color encodings. An encoding is one
  2414. * of:
  2415. *
  2416. * 1) Nothing (no color space, no gamma).
  2417. * 2) Just a gamma value from the gamma array (including 1.0)
  2418. * 3) A color space from the encodings array with the corresponding gamma.
  2419. * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
  2420. *
  2421. * The iterator selects these in turn, the randomizer selects one at random,
  2422. * which is used depends on the setting of the 'test_exhaustive' flag. Notice
  2423. * that this function changes the colour space encoding so it must only be
  2424. * called on completion of the previous test. This is what 'modifier_reset'
  2425. * does, below.
  2426. *
  2427. * After the function has been called the 'repeat' flag will still be set; the
  2428. * caller of modifier_reset must reset it at the start of each run of the test!
  2429. */
  2430. static unsigned int
  2431. modifier_total_encodings(const png_modifier *pm)
  2432. {
  2433. return 1 + /* (1) nothing */
  2434. pm->ngammas + /* (2) gamma values to test */
  2435. pm->nencodings + /* (3) total number of encodings */
  2436. /* The following test only works after the first time through the
  2437. * png_modifier code because 'bit_depth' is set when the IHDR is read.
  2438. * modifier_reset, below, preserves the setting until after it has called
  2439. * the iterate function (also below.)
  2440. *
  2441. * For this reason do not rely on this function outside a call to
  2442. * modifier_reset.
  2443. */
  2444. ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
  2445. pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
  2446. }
  2447. static void
  2448. modifier_encoding_iterate(png_modifier *pm)
  2449. {
  2450. if (!pm->repeat && /* Else something needs the current encoding again. */
  2451. pm->test_uses_encoding) /* Some transform is encoding dependent */
  2452. {
  2453. if (pm->test_exhaustive)
  2454. {
  2455. if (++pm->encoding_counter >= modifier_total_encodings(pm))
  2456. pm->encoding_counter = 0; /* This will stop the repeat */
  2457. }
  2458. else
  2459. {
  2460. /* Not exhaustive - choose an encoding at random; generate a number in
  2461. * the range 1..(max-1), so the result is always non-zero:
  2462. */
  2463. if (pm->encoding_counter == 0)
  2464. pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
  2465. else
  2466. pm->encoding_counter = 0;
  2467. }
  2468. if (pm->encoding_counter > 0)
  2469. pm->repeat = 1;
  2470. }
  2471. else if (!pm->repeat)
  2472. pm->encoding_counter = 0;
  2473. }
  2474. static void
  2475. modifier_reset(png_modifier *pm)
  2476. {
  2477. store_read_reset(&pm->this);
  2478. pm->limit = 4E-3;
  2479. pm->pending_len = pm->pending_chunk = 0;
  2480. pm->flush = pm->buffer_count = pm->buffer_position = 0;
  2481. pm->modifications = NULL;
  2482. pm->state = modifier_start;
  2483. modifier_encoding_iterate(pm);
  2484. /* The following must be set in the next run. In particular
  2485. * test_uses_encodings must be set in the _ini function of each transform
  2486. * that looks at the encodings. (Not the 'add' function!)
  2487. */
  2488. pm->test_uses_encoding = 0;
  2489. pm->current_gamma = 0;
  2490. pm->current_encoding = 0;
  2491. pm->encoding_ignored = 0;
  2492. /* These only become value after IHDR is read: */
  2493. pm->bit_depth = pm->colour_type = 0;
  2494. }
  2495. /* The following must be called before anything else to get the encoding set up
  2496. * on the modifier. In particular it must be called before the transform init
  2497. * functions are called.
  2498. */
  2499. static void
  2500. modifier_set_encoding(png_modifier *pm)
  2501. {
  2502. /* Set the encoding to the one specified by the current encoding counter,
  2503. * first clear out all the settings - this corresponds to an encoding_counter
  2504. * of 0.
  2505. */
  2506. pm->current_gamma = 0;
  2507. pm->current_encoding = 0;
  2508. pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
  2509. /* Now, if required, set the gamma and encoding fields. */
  2510. if (pm->encoding_counter > 0)
  2511. {
  2512. /* The gammas[] array is an array of screen gammas, not encoding gammas,
  2513. * so we need the inverse:
  2514. */
  2515. if (pm->encoding_counter <= pm->ngammas)
  2516. pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
  2517. else
  2518. {
  2519. unsigned int i = pm->encoding_counter - pm->ngammas;
  2520. if (i >= pm->nencodings)
  2521. {
  2522. i %= pm->nencodings;
  2523. pm->current_gamma = 1; /* Linear, only in the 16 bit case */
  2524. }
  2525. else
  2526. pm->current_gamma = pm->encodings[i].gamma;
  2527. pm->current_encoding = pm->encodings + i;
  2528. }
  2529. }
  2530. }
  2531. /* Enquiry functions to find out what is set. Notice that there is an implicit
  2532. * assumption below that the first encoding in the list is the one for sRGB.
  2533. */
  2534. static int
  2535. modifier_color_encoding_is_sRGB(const png_modifier *pm)
  2536. {
  2537. return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
  2538. pm->current_encoding->gamma == pm->current_gamma;
  2539. }
  2540. static int
  2541. modifier_color_encoding_is_set(const png_modifier *pm)
  2542. {
  2543. return pm->current_gamma != 0;
  2544. }
  2545. /* The guts of modification are performed during a read. */
  2546. static void
  2547. modifier_crc(png_bytep buffer)
  2548. {
  2549. /* Recalculate the chunk CRC - a complete chunk must be in
  2550. * the buffer, at the start.
  2551. */
  2552. uInt datalen = png_get_uint_32(buffer);
  2553. uLong crc = crc32(0, buffer+4, datalen+4);
  2554. /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
  2555. */
  2556. png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
  2557. }
  2558. static void
  2559. modifier_setbuffer(png_modifier *pm)
  2560. {
  2561. modifier_crc(pm->buffer);
  2562. pm->buffer_count = png_get_uint_32(pm->buffer)+12;
  2563. pm->buffer_position = 0;
  2564. }
  2565. /* Separate the callback into the actual implementation (which is passed the
  2566. * png_modifier explicitly) and the callback, which gets the modifier from the
  2567. * png_struct.
  2568. */
  2569. static void
  2570. modifier_read_imp(png_modifier *pm, png_bytep pb, size_t st)
  2571. {
  2572. while (st > 0)
  2573. {
  2574. size_t cb;
  2575. png_uint_32 len, chunk;
  2576. png_modification *mod;
  2577. if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
  2578. {
  2579. static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
  2580. case modifier_start:
  2581. store_read_chunk(&pm->this, pm->buffer, 8, 8); /* signature. */
  2582. pm->buffer_count = 8;
  2583. pm->buffer_position = 0;
  2584. if (memcmp(pm->buffer, sign, 8) != 0)
  2585. png_error(pm->this.pread, "invalid PNG file signature");
  2586. pm->state = modifier_signature;
  2587. break;
  2588. case modifier_signature:
  2589. store_read_chunk(&pm->this, pm->buffer, 13+12, 13+12); /* IHDR */
  2590. pm->buffer_count = 13+12;
  2591. pm->buffer_position = 0;
  2592. if (png_get_uint_32(pm->buffer) != 13 ||
  2593. png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
  2594. png_error(pm->this.pread, "invalid IHDR");
  2595. /* Check the list of modifiers for modifications to the IHDR. */
  2596. mod = pm->modifications;
  2597. while (mod != NULL)
  2598. {
  2599. if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
  2600. (*mod->modify_fn)(pm, mod, 0))
  2601. {
  2602. mod->modified = 1;
  2603. modifier_setbuffer(pm);
  2604. }
  2605. /* Ignore removal or add if IHDR! */
  2606. mod = mod->next;
  2607. }
  2608. /* Cache information from the IHDR (the modified one.) */
  2609. pm->bit_depth = pm->buffer[8+8];
  2610. pm->colour_type = pm->buffer[8+8+1];
  2611. pm->state = modifier_IHDR;
  2612. pm->flush = 0;
  2613. break;
  2614. case modifier_IHDR:
  2615. default:
  2616. /* Read a new chunk and process it until we see PLTE, IDAT or
  2617. * IEND. 'flush' indicates that there is still some data to
  2618. * output from the preceding chunk.
  2619. */
  2620. if ((cb = pm->flush) > 0)
  2621. {
  2622. if (cb > st) cb = st;
  2623. pm->flush -= cb;
  2624. store_read_chunk(&pm->this, pb, cb, cb);
  2625. pb += cb;
  2626. st -= cb;
  2627. if (st == 0) return;
  2628. }
  2629. /* No more bytes to flush, read a header, or handle a pending
  2630. * chunk.
  2631. */
  2632. if (pm->pending_chunk != 0)
  2633. {
  2634. png_save_uint_32(pm->buffer, pm->pending_len);
  2635. png_save_uint_32(pm->buffer+4, pm->pending_chunk);
  2636. pm->pending_len = 0;
  2637. pm->pending_chunk = 0;
  2638. }
  2639. else
  2640. store_read_chunk(&pm->this, pm->buffer, 8, 8);
  2641. pm->buffer_count = 8;
  2642. pm->buffer_position = 0;
  2643. /* Check for something to modify or a terminator chunk. */
  2644. len = png_get_uint_32(pm->buffer);
  2645. chunk = png_get_uint_32(pm->buffer+4);
  2646. /* Terminators first, they may have to be delayed for added
  2647. * chunks
  2648. */
  2649. if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
  2650. chunk == CHUNK_IEND)
  2651. {
  2652. mod = pm->modifications;
  2653. while (mod != NULL)
  2654. {
  2655. if ((mod->add == chunk ||
  2656. (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
  2657. mod->modify_fn != NULL && !mod->modified && !mod->added)
  2658. {
  2659. /* Regardless of what the modify function does do not run
  2660. * this again.
  2661. */
  2662. mod->added = 1;
  2663. if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
  2664. {
  2665. /* Reset the CRC on a new chunk */
  2666. if (pm->buffer_count > 0)
  2667. modifier_setbuffer(pm);
  2668. else
  2669. {
  2670. pm->buffer_position = 0;
  2671. mod->removed = 1;
  2672. }
  2673. /* The buffer has been filled with something (we assume)
  2674. * so output this. Pend the current chunk.
  2675. */
  2676. pm->pending_len = len;
  2677. pm->pending_chunk = chunk;
  2678. break; /* out of while */
  2679. }
  2680. }
  2681. mod = mod->next;
  2682. }
  2683. /* Don't do any further processing if the buffer was modified -
  2684. * otherwise the code will end up modifying a chunk that was
  2685. * just added.
  2686. */
  2687. if (mod != NULL)
  2688. break; /* out of switch */
  2689. }
  2690. /* If we get to here then this chunk may need to be modified. To
  2691. * do this it must be less than 1024 bytes in total size, otherwise
  2692. * it just gets flushed.
  2693. */
  2694. if (len+12 <= sizeof pm->buffer)
  2695. {
  2696. size_t s = len+12-pm->buffer_count;
  2697. store_read_chunk(&pm->this, pm->buffer+pm->buffer_count, s, s);
  2698. pm->buffer_count = len+12;
  2699. /* Check for a modification, else leave it be. */
  2700. mod = pm->modifications;
  2701. while (mod != NULL)
  2702. {
  2703. if (mod->chunk == chunk)
  2704. {
  2705. if (mod->modify_fn == NULL)
  2706. {
  2707. /* Remove this chunk */
  2708. pm->buffer_count = pm->buffer_position = 0;
  2709. mod->removed = 1;
  2710. break; /* Terminate the while loop */
  2711. }
  2712. else if ((*mod->modify_fn)(pm, mod, 0))
  2713. {
  2714. mod->modified = 1;
  2715. /* The chunk may have been removed: */
  2716. if (pm->buffer_count == 0)
  2717. {
  2718. pm->buffer_position = 0;
  2719. break;
  2720. }
  2721. modifier_setbuffer(pm);
  2722. }
  2723. }
  2724. mod = mod->next;
  2725. }
  2726. }
  2727. else
  2728. pm->flush = len+12 - pm->buffer_count; /* data + crc */
  2729. /* Take the data from the buffer (if there is any). */
  2730. break;
  2731. }
  2732. /* Here to read from the modifier buffer (not directly from
  2733. * the store, as in the flush case above.)
  2734. */
  2735. cb = pm->buffer_count - pm->buffer_position;
  2736. if (cb > st)
  2737. cb = st;
  2738. memcpy(pb, pm->buffer + pm->buffer_position, cb);
  2739. st -= cb;
  2740. pb += cb;
  2741. pm->buffer_position += cb;
  2742. }
  2743. }
  2744. /* The callback: */
  2745. static void PNGCBAPI
  2746. modifier_read(png_structp ppIn, png_bytep pb, size_t st)
  2747. {
  2748. png_const_structp pp = ppIn;
  2749. png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
  2750. if (pm == NULL || pm->this.pread != pp)
  2751. png_error(pp, "bad modifier_read call");
  2752. modifier_read_imp(pm, pb, st);
  2753. }
  2754. /* Like store_progressive_read but the data is getting changed as we go so we
  2755. * need a local buffer.
  2756. */
  2757. static void
  2758. modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
  2759. {
  2760. if (pm->this.pread != pp || pm->this.current == NULL ||
  2761. pm->this.next == NULL)
  2762. png_error(pp, "store state damaged (progressive)");
  2763. /* This is another Horowitz and Hill random noise generator. In this case
  2764. * the aim is to stress the progressive reader with truly horrible variable
  2765. * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
  2766. * is generated. We could probably just count from 1 to 32767 and get as
  2767. * good a result.
  2768. */
  2769. for (;;)
  2770. {
  2771. static png_uint_32 noise = 1;
  2772. size_t cb, cbAvail;
  2773. png_byte buffer[512];
  2774. /* Generate 15 more bits of stuff: */
  2775. noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
  2776. cb = noise & 0x1ff;
  2777. /* Check that this number of bytes are available (in the current buffer.)
  2778. * (This doesn't quite work - the modifier might delete a chunk; unlikely
  2779. * but possible, it doesn't happen at present because the modifier only
  2780. * adds chunks to standard images.)
  2781. */
  2782. cbAvail = store_read_buffer_avail(&pm->this);
  2783. if (pm->buffer_count > pm->buffer_position)
  2784. cbAvail += pm->buffer_count - pm->buffer_position;
  2785. if (cb > cbAvail)
  2786. {
  2787. /* Check for EOF: */
  2788. if (cbAvail == 0)
  2789. break;
  2790. cb = cbAvail;
  2791. }
  2792. modifier_read_imp(pm, buffer, cb);
  2793. png_process_data(pp, pi, buffer, cb);
  2794. }
  2795. /* Check the invariants at the end (if this fails it's a problem in this
  2796. * file!)
  2797. */
  2798. if (pm->buffer_count > pm->buffer_position ||
  2799. pm->this.next != &pm->this.current->data ||
  2800. pm->this.readpos < pm->this.current->datacount)
  2801. png_error(pp, "progressive read implementation error");
  2802. }
  2803. /* Set up a modifier. */
  2804. static png_structp
  2805. set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
  2806. const char *name)
  2807. {
  2808. /* Do this first so that the modifier fields are cleared even if an error
  2809. * happens allocating the png_struct. No allocation is done here so no
  2810. * cleanup is required.
  2811. */
  2812. pm->state = modifier_start;
  2813. pm->bit_depth = 0;
  2814. pm->colour_type = 255;
  2815. pm->pending_len = 0;
  2816. pm->pending_chunk = 0;
  2817. pm->flush = 0;
  2818. pm->buffer_count = 0;
  2819. pm->buffer_position = 0;
  2820. return set_store_for_read(&pm->this, ppi, id, name);
  2821. }
  2822. /******************************** MODIFICATIONS *******************************/
  2823. /* Standard modifications to add chunks. These do not require the _SUPPORTED
  2824. * macros because the chunks can be there regardless of whether this specific
  2825. * libpng supports them.
  2826. */
  2827. typedef struct gama_modification
  2828. {
  2829. png_modification this;
  2830. png_fixed_point gamma;
  2831. } gama_modification;
  2832. static int
  2833. gama_modify(png_modifier *pm, png_modification *me, int add)
  2834. {
  2835. UNUSED(add)
  2836. /* This simply dumps the given gamma value into the buffer. */
  2837. png_save_uint_32(pm->buffer, 4);
  2838. png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
  2839. png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
  2840. return 1;
  2841. }
  2842. static void
  2843. gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
  2844. {
  2845. double g;
  2846. modification_init(&me->this);
  2847. me->this.chunk = CHUNK_gAMA;
  2848. me->this.modify_fn = gama_modify;
  2849. me->this.add = CHUNK_PLTE;
  2850. g = fix(gammad);
  2851. me->gamma = (png_fixed_point)g;
  2852. me->this.next = pm->modifications;
  2853. pm->modifications = &me->this;
  2854. }
  2855. typedef struct chrm_modification
  2856. {
  2857. png_modification this;
  2858. const color_encoding *encoding;
  2859. png_fixed_point wx, wy, rx, ry, gx, gy, bx, by;
  2860. } chrm_modification;
  2861. static int
  2862. chrm_modify(png_modifier *pm, png_modification *me, int add)
  2863. {
  2864. UNUSED(add)
  2865. /* As with gAMA this just adds the required cHRM chunk to the buffer. */
  2866. png_save_uint_32(pm->buffer , 32);
  2867. png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
  2868. png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
  2869. png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
  2870. png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
  2871. png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
  2872. png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
  2873. png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
  2874. png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
  2875. png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
  2876. return 1;
  2877. }
  2878. static void
  2879. chrm_modification_init(chrm_modification *me, png_modifier *pm,
  2880. const color_encoding *encoding)
  2881. {
  2882. CIE_color white = white_point(encoding);
  2883. /* Original end points: */
  2884. me->encoding = encoding;
  2885. /* Chromaticities (in fixed point): */
  2886. me->wx = fix(chromaticity_x(white));
  2887. me->wy = fix(chromaticity_y(white));
  2888. me->rx = fix(chromaticity_x(encoding->red));
  2889. me->ry = fix(chromaticity_y(encoding->red));
  2890. me->gx = fix(chromaticity_x(encoding->green));
  2891. me->gy = fix(chromaticity_y(encoding->green));
  2892. me->bx = fix(chromaticity_x(encoding->blue));
  2893. me->by = fix(chromaticity_y(encoding->blue));
  2894. modification_init(&me->this);
  2895. me->this.chunk = CHUNK_cHRM;
  2896. me->this.modify_fn = chrm_modify;
  2897. me->this.add = CHUNK_PLTE;
  2898. me->this.next = pm->modifications;
  2899. pm->modifications = &me->this;
  2900. }
  2901. typedef struct srgb_modification
  2902. {
  2903. png_modification this;
  2904. png_byte intent;
  2905. } srgb_modification;
  2906. static int
  2907. srgb_modify(png_modifier *pm, png_modification *me, int add)
  2908. {
  2909. UNUSED(add)
  2910. /* As above, ignore add and just make a new chunk */
  2911. png_save_uint_32(pm->buffer, 1);
  2912. png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
  2913. pm->buffer[8] = ((srgb_modification*)me)->intent;
  2914. return 1;
  2915. }
  2916. static void
  2917. srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
  2918. {
  2919. modification_init(&me->this);
  2920. me->this.chunk = CHUNK_sBIT;
  2921. if (intent <= 3) /* if valid, else *delete* sRGB chunks */
  2922. {
  2923. me->this.modify_fn = srgb_modify;
  2924. me->this.add = CHUNK_PLTE;
  2925. me->intent = intent;
  2926. }
  2927. else
  2928. {
  2929. me->this.modify_fn = 0;
  2930. me->this.add = 0;
  2931. me->intent = 0;
  2932. }
  2933. me->this.next = pm->modifications;
  2934. pm->modifications = &me->this;
  2935. }
  2936. #ifdef PNG_READ_GAMMA_SUPPORTED
  2937. typedef struct sbit_modification
  2938. {
  2939. png_modification this;
  2940. png_byte sbit;
  2941. } sbit_modification;
  2942. static int
  2943. sbit_modify(png_modifier *pm, png_modification *me, int add)
  2944. {
  2945. png_byte sbit = ((sbit_modification*)me)->sbit;
  2946. if (pm->bit_depth > sbit)
  2947. {
  2948. int cb = 0;
  2949. switch (pm->colour_type)
  2950. {
  2951. case 0:
  2952. cb = 1;
  2953. break;
  2954. case 2:
  2955. case 3:
  2956. cb = 3;
  2957. break;
  2958. case 4:
  2959. cb = 2;
  2960. break;
  2961. case 6:
  2962. cb = 4;
  2963. break;
  2964. default:
  2965. png_error(pm->this.pread,
  2966. "unexpected colour type in sBIT modification");
  2967. }
  2968. png_save_uint_32(pm->buffer, cb);
  2969. png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
  2970. while (cb > 0)
  2971. (pm->buffer+8)[--cb] = sbit;
  2972. return 1;
  2973. }
  2974. else if (!add)
  2975. {
  2976. /* Remove the sBIT chunk */
  2977. pm->buffer_count = pm->buffer_position = 0;
  2978. return 1;
  2979. }
  2980. else
  2981. return 0; /* do nothing */
  2982. }
  2983. static void
  2984. sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
  2985. {
  2986. modification_init(&me->this);
  2987. me->this.chunk = CHUNK_sBIT;
  2988. me->this.modify_fn = sbit_modify;
  2989. me->this.add = CHUNK_PLTE;
  2990. me->sbit = sbit;
  2991. me->this.next = pm->modifications;
  2992. pm->modifications = &me->this;
  2993. }
  2994. #endif /* PNG_READ_GAMMA_SUPPORTED */
  2995. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  2996. /***************************** STANDARD PNG FILES *****************************/
  2997. /* Standard files - write and save standard files. */
  2998. /* There are two basic forms of standard images. Those which attempt to have
  2999. * all the possible pixel values (not possible for 16bpp images, but a range of
  3000. * values are produced) and those which have a range of image sizes. The former
  3001. * are used for testing transforms, in particular gamma correction and bit
  3002. * reduction and increase. The latter are reserved for testing the behavior of
  3003. * libpng with respect to 'odd' image sizes - particularly small images where
  3004. * rows become 1 byte and interlace passes disappear.
  3005. *
  3006. * The first, most useful, set are the 'transform' images, the second set of
  3007. * small images are the 'size' images.
  3008. *
  3009. * The transform files are constructed with rows which fit into a 1024 byte row
  3010. * buffer. This makes allocation easier below. Further regardless of the file
  3011. * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
  3012. *
  3013. * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
  3014. * and with an ID derived from the colour type, bit depth and interlace type
  3015. * as above (FILEID). The width (128) and height (variable) are not stored in
  3016. * the FILEID - instead the fields are set to 0, indicating a transform file.
  3017. *
  3018. * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
  3019. * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum
  3020. * height of 16 rows. The width and height are stored in the FILEID and, being
  3021. * non-zero, indicate a size file.
  3022. *
  3023. * Because the PNG filter code is typically the largest CPU consumer within
  3024. * libpng itself there is a tendency to attempt to optimize it. This results in
  3025. * special case code which needs to be validated. To cause this to happen the
  3026. * 'size' images are made to use each possible filter, in so far as this is
  3027. * possible for smaller images.
  3028. *
  3029. * For palette image (colour type 3) multiple transform images are stored with
  3030. * the same bit depth to allow testing of more colour combinations -
  3031. * particularly important for testing the gamma code because libpng uses a
  3032. * different code path for palette images. For size images a single palette is
  3033. * used.
  3034. */
  3035. /* Make a 'standard' palette. Because there are only 256 entries in a palette
  3036. * (maximum) this actually makes a random palette in the hope that enough tests
  3037. * will catch enough errors. (Note that the same palette isn't produced every
  3038. * time for the same test - it depends on what previous tests have been run -
  3039. * but a given set of arguments to pngvalid will always produce the same palette
  3040. * at the same test! This is why pseudo-random number generators are useful for
  3041. * testing.)
  3042. *
  3043. * The store must be open for write when this is called, otherwise an internal
  3044. * error will occur. This routine contains its own magic number seed, so the
  3045. * palettes generated don't change if there are intervening errors (changing the
  3046. * calls to the store_mark seed.)
  3047. */
  3048. static store_palette_entry *
  3049. make_standard_palette(png_store* ps, int npalette, int do_tRNS)
  3050. {
  3051. static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
  3052. int i = 0;
  3053. png_byte values[256][4];
  3054. /* Always put in black and white plus the six primary and secondary colors.
  3055. */
  3056. for (; i<8; ++i)
  3057. {
  3058. values[i][1] = (png_byte)((i&1) ? 255U : 0U);
  3059. values[i][2] = (png_byte)((i&2) ? 255U : 0U);
  3060. values[i][3] = (png_byte)((i&4) ? 255U : 0U);
  3061. }
  3062. /* Then add 62 grays (one quarter of the remaining 256 slots). */
  3063. {
  3064. int j = 0;
  3065. png_byte random_bytes[4];
  3066. png_byte need[256];
  3067. need[0] = 0; /*got black*/
  3068. memset(need+1, 1, (sizeof need)-2); /*need these*/
  3069. need[255] = 0; /*but not white*/
  3070. while (i<70)
  3071. {
  3072. png_byte b;
  3073. if (j==0)
  3074. {
  3075. make_four_random_bytes(palette_seed, random_bytes);
  3076. j = 4;
  3077. }
  3078. b = random_bytes[--j];
  3079. if (need[b])
  3080. {
  3081. values[i][1] = b;
  3082. values[i][2] = b;
  3083. values[i++][3] = b;
  3084. }
  3085. }
  3086. }
  3087. /* Finally add 192 colors at random - don't worry about matches to things we
  3088. * already have, chance is less than 1/65536. Don't worry about grays,
  3089. * chance is the same, so we get a duplicate or extra gray less than 1 time
  3090. * in 170.
  3091. */
  3092. for (; i<256; ++i)
  3093. make_four_random_bytes(palette_seed, values[i]);
  3094. /* Fill in the alpha values in the first byte. Just use all possible values
  3095. * (0..255) in an apparently random order:
  3096. */
  3097. {
  3098. store_palette_entry *palette;
  3099. png_byte selector[4];
  3100. make_four_random_bytes(palette_seed, selector);
  3101. if (do_tRNS)
  3102. for (i=0; i<256; ++i)
  3103. values[i][0] = (png_byte)(i ^ selector[0]);
  3104. else
  3105. for (i=0; i<256; ++i)
  3106. values[i][0] = 255; /* no transparency/tRNS chunk */
  3107. /* 'values' contains 256 ARGB values, but we only need 'npalette'.
  3108. * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low
  3109. * bit depth cases select colors at random, else it is difficult to have
  3110. * a set of low bit depth palette test with any chance of a reasonable
  3111. * range of colors. Do this by randomly permuting values into the low
  3112. * 'npalette' entries using an XOR mask generated here. This also
  3113. * permutes the npalette == 256 case in a potentially useful way (there is
  3114. * no relationship between palette index and the color value therein!)
  3115. */
  3116. palette = store_write_palette(ps, npalette);
  3117. for (i=0; i<npalette; ++i)
  3118. {
  3119. palette[i].alpha = values[i ^ selector[1]][0];
  3120. palette[i].red = values[i ^ selector[1]][1];
  3121. palette[i].green = values[i ^ selector[1]][2];
  3122. palette[i].blue = values[i ^ selector[1]][3];
  3123. }
  3124. return palette;
  3125. }
  3126. }
  3127. /* Initialize a standard palette on a write stream. The 'do_tRNS' argument
  3128. * indicates whether or not to also set the tRNS chunk.
  3129. */
  3130. /* TODO: the png_structp here can probably be 'const' in the future */
  3131. static void
  3132. init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
  3133. int do_tRNS)
  3134. {
  3135. store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
  3136. {
  3137. int i;
  3138. png_color palette[256];
  3139. /* Set all entries to detect overread errors. */
  3140. for (i=0; i<npalette; ++i)
  3141. {
  3142. palette[i].red = ppal[i].red;
  3143. palette[i].green = ppal[i].green;
  3144. palette[i].blue = ppal[i].blue;
  3145. }
  3146. /* Just in case fill in the rest with detectable values: */
  3147. for (; i<256; ++i)
  3148. palette[i].red = palette[i].green = palette[i].blue = 42;
  3149. png_set_PLTE(pp, pi, palette, npalette);
  3150. }
  3151. if (do_tRNS)
  3152. {
  3153. int i, j;
  3154. png_byte tRNS[256];
  3155. /* Set all the entries, but skip trailing opaque entries */
  3156. for (i=j=0; i<npalette; ++i)
  3157. if ((tRNS[i] = ppal[i].alpha) < 255)
  3158. j = i+1;
  3159. /* Fill in the remainder with a detectable value: */
  3160. for (; i<256; ++i)
  3161. tRNS[i] = 24;
  3162. #ifdef PNG_WRITE_tRNS_SUPPORTED
  3163. if (j > 0)
  3164. png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
  3165. #endif
  3166. }
  3167. }
  3168. #ifdef PNG_WRITE_tRNS_SUPPORTED
  3169. static void
  3170. set_random_tRNS(png_structp pp, png_infop pi, png_byte colour_type,
  3171. int bit_depth)
  3172. {
  3173. /* To make this useful the tRNS color needs to match at least one pixel.
  3174. * Random values are fine for gray, including the 16-bit case where we know
  3175. * that the test image contains all the gray values. For RGB we need more
  3176. * method as only 65536 different RGB values are generated.
  3177. */
  3178. png_color_16 tRNS;
  3179. png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1);
  3180. R8(tRNS); /* makes unset fields random */
  3181. if (colour_type & 2/*RGB*/)
  3182. {
  3183. if (bit_depth == 8)
  3184. {
  3185. tRNS.red = random_u16();
  3186. tRNS.green = random_u16();
  3187. tRNS.blue = tRNS.red ^ tRNS.green;
  3188. tRNS.red &= mask;
  3189. tRNS.green &= mask;
  3190. tRNS.blue &= mask;
  3191. }
  3192. else /* bit_depth == 16 */
  3193. {
  3194. tRNS.red = random_u16();
  3195. tRNS.green = (png_uint_16)(tRNS.red * 257);
  3196. tRNS.blue = (png_uint_16)(tRNS.green * 17);
  3197. }
  3198. }
  3199. else
  3200. {
  3201. tRNS.gray = random_u16();
  3202. tRNS.gray &= mask;
  3203. }
  3204. png_set_tRNS(pp, pi, NULL, 0, &tRNS);
  3205. }
  3206. #endif
  3207. /* The number of passes is related to the interlace type. There was no libpng
  3208. * API to determine this prior to 1.5, so we need an inquiry function:
  3209. */
  3210. static int
  3211. npasses_from_interlace_type(png_const_structp pp, int interlace_type)
  3212. {
  3213. switch (interlace_type)
  3214. {
  3215. default:
  3216. png_error(pp, "invalid interlace type");
  3217. case PNG_INTERLACE_NONE:
  3218. return 1;
  3219. case PNG_INTERLACE_ADAM7:
  3220. return PNG_INTERLACE_ADAM7_PASSES;
  3221. }
  3222. }
  3223. static unsigned int
  3224. bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  3225. {
  3226. switch (colour_type)
  3227. {
  3228. default: png_error(pp, "invalid color type");
  3229. case 0: return bit_depth;
  3230. case 2: return 3*bit_depth;
  3231. case 3: return bit_depth;
  3232. case 4: return 2*bit_depth;
  3233. case 6: return 4*bit_depth;
  3234. }
  3235. }
  3236. #define TRANSFORM_WIDTH 128U
  3237. #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
  3238. #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
  3239. #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
  3240. #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
  3241. static size_t
  3242. transform_rowsize(png_const_structp pp, png_byte colour_type,
  3243. png_byte bit_depth)
  3244. {
  3245. return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
  3246. }
  3247. /* transform_width(pp, colour_type, bit_depth) current returns the same number
  3248. * every time, so just use a macro:
  3249. */
  3250. #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
  3251. static png_uint_32
  3252. transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  3253. {
  3254. switch (bit_size(pp, colour_type, bit_depth))
  3255. {
  3256. case 1:
  3257. case 2:
  3258. case 4:
  3259. return 1; /* Total of 128 pixels */
  3260. case 8:
  3261. return 2; /* Total of 256 pixels/bytes */
  3262. case 16:
  3263. return 512; /* Total of 65536 pixels */
  3264. case 24:
  3265. case 32:
  3266. return 512; /* 65536 pixels */
  3267. case 48:
  3268. case 64:
  3269. return 2048;/* 4 x 65536 pixels. */
  3270. # define TRANSFORM_HEIGHTMAX 2048
  3271. default:
  3272. return 0; /* Error, will be caught later */
  3273. }
  3274. }
  3275. #ifdef PNG_READ_SUPPORTED
  3276. /* The following can only be defined here, now we have the definitions
  3277. * of the transform image sizes.
  3278. */
  3279. static png_uint_32
  3280. standard_width(png_const_structp pp, png_uint_32 id)
  3281. {
  3282. png_uint_32 width = WIDTH_FROM_ID(id);
  3283. UNUSED(pp)
  3284. if (width == 0)
  3285. width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  3286. return width;
  3287. }
  3288. static png_uint_32
  3289. standard_height(png_const_structp pp, png_uint_32 id)
  3290. {
  3291. png_uint_32 height = HEIGHT_FROM_ID(id);
  3292. if (height == 0)
  3293. height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  3294. return height;
  3295. }
  3296. static png_uint_32
  3297. standard_rowsize(png_const_structp pp, png_uint_32 id)
  3298. {
  3299. png_uint_32 width = standard_width(pp, id);
  3300. /* This won't overflow: */
  3301. width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  3302. return (width + 7) / 8;
  3303. }
  3304. #endif /* PNG_READ_SUPPORTED */
  3305. static void
  3306. transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
  3307. png_byte colour_type, png_byte bit_depth, png_uint_32 y)
  3308. {
  3309. png_uint_32 v = y << 7;
  3310. png_uint_32 i = 0;
  3311. switch (bit_size(pp, colour_type, bit_depth))
  3312. {
  3313. case 1:
  3314. while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
  3315. return;
  3316. case 2:
  3317. while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
  3318. return;
  3319. case 4:
  3320. while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
  3321. return;
  3322. case 8:
  3323. /* 256 bytes total, 128 bytes in each row set as follows: */
  3324. while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
  3325. return;
  3326. case 16:
  3327. /* Generate all 65536 pixel values in order, which includes the 8 bit
  3328. * GA case as well as the 16 bit G case.
  3329. */
  3330. while (i<128)
  3331. {
  3332. buffer[2*i] = (png_byte)((v>>8) & 0xff);
  3333. buffer[2*i+1] = (png_byte)(v & 0xff);
  3334. ++v;
  3335. ++i;
  3336. }
  3337. return;
  3338. case 24:
  3339. /* 65535 pixels, but rotate the values. */
  3340. while (i<128)
  3341. {
  3342. /* Three bytes per pixel, r, g, b, make b by r^g */
  3343. buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
  3344. buffer[3*i+1] = (png_byte)(v & 0xff);
  3345. buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
  3346. ++v;
  3347. ++i;
  3348. }
  3349. return;
  3350. case 32:
  3351. /* 65535 pixels, r, g, b, a; just replicate */
  3352. while (i<128)
  3353. {
  3354. buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
  3355. buffer[4*i+1] = (png_byte)(v & 0xff);
  3356. buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
  3357. buffer[4*i+3] = (png_byte)(v & 0xff);
  3358. ++v;
  3359. ++i;
  3360. }
  3361. return;
  3362. case 48:
  3363. /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
  3364. * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
  3365. */
  3366. while (i<128)
  3367. {
  3368. png_uint_32 t = v++;
  3369. buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
  3370. buffer[6*i+1] = (png_byte)(t & 0xff);
  3371. t *= 257;
  3372. buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
  3373. buffer[6*i+3] = (png_byte)(t & 0xff);
  3374. t *= 17;
  3375. buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
  3376. buffer[6*i+5] = (png_byte)(t & 0xff);
  3377. ++i;
  3378. }
  3379. return;
  3380. case 64:
  3381. /* As above in the 32 bit case. */
  3382. while (i<128)
  3383. {
  3384. png_uint_32 t = v++;
  3385. buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
  3386. buffer[8*i+1] = (png_byte)(t & 0xff);
  3387. buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
  3388. buffer[8*i+5] = (png_byte)(t & 0xff);
  3389. t *= 257;
  3390. buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
  3391. buffer[8*i+3] = (png_byte)(t & 0xff);
  3392. buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
  3393. buffer[8*i+7] = (png_byte)(t & 0xff);
  3394. ++i;
  3395. }
  3396. return;
  3397. default:
  3398. break;
  3399. }
  3400. png_error(pp, "internal error");
  3401. }
  3402. /* This is just to do the right cast - could be changed to a function to check
  3403. * 'bd' but there isn't much point.
  3404. */
  3405. #define DEPTH(bd) ((png_byte)(1U << (bd)))
  3406. /* This is just a helper for compiling on minimal systems with no write
  3407. * interlacing support. If there is no write interlacing we can't generate test
  3408. * cases with interlace:
  3409. */
  3410. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  3411. # define INTERLACE_LAST PNG_INTERLACE_LAST
  3412. # define check_interlace_type(type) ((void)(type))
  3413. # define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp)
  3414. # define do_own_interlace 0
  3415. #elif PNG_LIBPNG_VER != 10700
  3416. # define set_write_interlace_handling(pp,type) (1)
  3417. static void
  3418. check_interlace_type(int const interlace_type)
  3419. {
  3420. /* Prior to 1.7.0 libpng does not support the write of an interlaced image
  3421. * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
  3422. * code here does the pixel interlace itself, so:
  3423. */
  3424. if (interlace_type != PNG_INTERLACE_NONE)
  3425. {
  3426. /* This is an internal error - --interlace tests should be skipped, not
  3427. * attempted.
  3428. */
  3429. fprintf(stderr, "pngvalid: no interlace support\n");
  3430. exit(99);
  3431. }
  3432. }
  3433. # define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
  3434. # define do_own_interlace 0
  3435. #else /* libpng 1.7+ */
  3436. # define set_write_interlace_handling(pp,type)\
  3437. npasses_from_interlace_type(pp,type)
  3438. # define check_interlace_type(type) ((void)(type))
  3439. # define INTERLACE_LAST PNG_INTERLACE_LAST
  3440. # define do_own_interlace 1
  3441. #endif /* WRITE_INTERLACING tests */
  3442. #if PNG_LIBPNG_VER == 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED
  3443. # define CAN_WRITE_INTERLACE 1
  3444. #else
  3445. # define CAN_WRITE_INTERLACE 0
  3446. #endif
  3447. /* Do the same thing for read interlacing; this controls whether read tests do
  3448. * their own de-interlace or use libpng.
  3449. */
  3450. #ifdef PNG_READ_INTERLACING_SUPPORTED
  3451. # define do_read_interlace 0
  3452. #else /* no libpng read interlace support */
  3453. # define do_read_interlace 1
  3454. #endif
  3455. /* The following two routines use the PNG interlace support macros from
  3456. * png.h to interlace or deinterlace rows.
  3457. */
  3458. static void
  3459. interlace_row(png_bytep buffer, png_const_bytep imageRow,
  3460. unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
  3461. {
  3462. png_uint_32 xin, xout, xstep;
  3463. /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
  3464. * code is presented this way to make it easier to understand. In practice
  3465. * consult the code in the libpng source to see other ways of doing this.
  3466. *
  3467. * It is OK for buffer and imageRow to be identical, because 'xin' moves
  3468. * faster than 'xout' and we copy up.
  3469. */
  3470. xin = PNG_PASS_START_COL(pass);
  3471. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3472. for (xout=0; xin<w; xin+=xstep)
  3473. {
  3474. pixel_copy(buffer, xout, imageRow, xin, pixel_size, littleendian);
  3475. ++xout;
  3476. }
  3477. }
  3478. #ifdef PNG_READ_SUPPORTED
  3479. static void
  3480. deinterlace_row(png_bytep buffer, png_const_bytep row,
  3481. unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
  3482. {
  3483. /* The inverse of the above, 'row' is part of row 'y' of the output image,
  3484. * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
  3485. * the pixels of row into buffer and return the number written (to allow
  3486. * this to be checked).
  3487. */
  3488. png_uint_32 xin, xout, xstep;
  3489. xout = PNG_PASS_START_COL(pass);
  3490. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3491. for (xin=0; xout<w; xout+=xstep)
  3492. {
  3493. pixel_copy(buffer, xout, row, xin, pixel_size, littleendian);
  3494. ++xin;
  3495. }
  3496. }
  3497. #endif /* PNG_READ_SUPPORTED */
  3498. /* Make a standardized image given an image colour type, bit depth and
  3499. * interlace type. The standard images have a very restricted range of
  3500. * rows and heights and are used for testing transforms rather than image
  3501. * layout details. See make_size_images below for a way to make images
  3502. * that test odd sizes along with the libpng interlace handling.
  3503. */
  3504. #ifdef PNG_WRITE_FILTER_SUPPORTED
  3505. static void
  3506. choose_random_filter(png_structp pp, int start)
  3507. {
  3508. /* Choose filters randomly except that on the very first row ensure that
  3509. * there is at least one previous row filter.
  3510. */
  3511. int filters = PNG_ALL_FILTERS & random_mod(256U);
  3512. /* There may be no filters; skip the setting. */
  3513. if (filters != 0)
  3514. {
  3515. if (start && filters < PNG_FILTER_UP)
  3516. filters |= PNG_FILTER_UP;
  3517. png_set_filter(pp, 0/*method*/, filters);
  3518. }
  3519. }
  3520. #else /* !WRITE_FILTER */
  3521. # define choose_random_filter(pp, start) ((void)0)
  3522. #endif /* !WRITE_FILTER */
  3523. static void
  3524. make_transform_image(png_store* const ps, png_byte const colour_type,
  3525. png_byte const bit_depth, unsigned int palette_number,
  3526. int interlace_type, png_const_charp name)
  3527. {
  3528. context(ps, fault);
  3529. check_interlace_type(interlace_type);
  3530. Try
  3531. {
  3532. png_infop pi;
  3533. png_structp pp = set_store_for_write(ps, &pi, name);
  3534. png_uint_32 h, w;
  3535. /* In the event of a problem return control to the Catch statement below
  3536. * to do the clean up - it is not possible to 'return' directly from a Try
  3537. * block.
  3538. */
  3539. if (pp == NULL)
  3540. Throw ps;
  3541. w = transform_width(pp, colour_type, bit_depth);
  3542. h = transform_height(pp, colour_type, bit_depth);
  3543. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3544. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3545. #ifdef PNG_TEXT_SUPPORTED
  3546. # if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
  3547. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
  3548. # else
  3549. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
  3550. # endif
  3551. {
  3552. static char key[] = "image name"; /* must be writeable */
  3553. size_t pos;
  3554. png_text text;
  3555. char copy[FILE_NAME_SIZE];
  3556. /* Use a compressed text string to test the correct interaction of text
  3557. * compression and IDAT compression.
  3558. */
  3559. text.compression = TEXT_COMPRESSION;
  3560. text.key = key;
  3561. /* Yuck: the text must be writable! */
  3562. pos = safecat(copy, sizeof copy, 0, ps->wname);
  3563. text.text = copy;
  3564. text.text_length = pos;
  3565. text.itxt_length = 0;
  3566. text.lang = 0;
  3567. text.lang_key = 0;
  3568. png_set_text(pp, pi, &text, 1);
  3569. }
  3570. #endif
  3571. if (colour_type == 3) /* palette */
  3572. init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
  3573. # ifdef PNG_WRITE_tRNS_SUPPORTED
  3574. else if (palette_number)
  3575. set_random_tRNS(pp, pi, colour_type, bit_depth);
  3576. # endif
  3577. png_write_info(pp, pi);
  3578. if (png_get_rowbytes(pp, pi) !=
  3579. transform_rowsize(pp, colour_type, bit_depth))
  3580. png_error(pp, "transform row size incorrect");
  3581. else
  3582. {
  3583. /* Somewhat confusingly this must be called *after* png_write_info
  3584. * because if it is called before, the information in *pp has not been
  3585. * updated to reflect the interlaced image.
  3586. */
  3587. int npasses = set_write_interlace_handling(pp, interlace_type);
  3588. int pass;
  3589. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  3590. png_error(pp, "write: png_set_interlace_handling failed");
  3591. for (pass=0; pass<npasses; ++pass)
  3592. {
  3593. png_uint_32 y;
  3594. /* do_own_interlace is a pre-defined boolean (a #define) which is
  3595. * set if we have to work out the interlaced rows here.
  3596. */
  3597. for (y=0; y<h; ++y)
  3598. {
  3599. png_byte buffer[TRANSFORM_ROWMAX];
  3600. transform_row(pp, buffer, colour_type, bit_depth, y);
  3601. # if do_own_interlace
  3602. /* If do_own_interlace *and* the image is interlaced we need a
  3603. * reduced interlace row; this may be reduced to empty.
  3604. */
  3605. if (interlace_type == PNG_INTERLACE_ADAM7)
  3606. {
  3607. /* The row must not be written if it doesn't exist, notice
  3608. * that there are two conditions here, either the row isn't
  3609. * ever in the pass or the row would be but isn't wide
  3610. * enough to contribute any pixels. In fact the wPass test
  3611. * can be used to skip the whole y loop in this case.
  3612. */
  3613. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  3614. PNG_PASS_COLS(w, pass) > 0)
  3615. interlace_row(buffer, buffer,
  3616. bit_size(pp, colour_type, bit_depth), w, pass,
  3617. 0/*data always bigendian*/);
  3618. else
  3619. continue;
  3620. }
  3621. # endif /* do_own_interlace */
  3622. choose_random_filter(pp, pass == 0 && y == 0);
  3623. png_write_row(pp, buffer);
  3624. }
  3625. }
  3626. }
  3627. #ifdef PNG_TEXT_SUPPORTED
  3628. {
  3629. static char key[] = "end marker";
  3630. static char comment[] = "end";
  3631. png_text text;
  3632. /* Use a compressed text string to test the correct interaction of text
  3633. * compression and IDAT compression.
  3634. */
  3635. text.compression = TEXT_COMPRESSION;
  3636. text.key = key;
  3637. text.text = comment;
  3638. text.text_length = (sizeof comment)-1;
  3639. text.itxt_length = 0;
  3640. text.lang = 0;
  3641. text.lang_key = 0;
  3642. png_set_text(pp, pi, &text, 1);
  3643. }
  3644. #endif
  3645. png_write_end(pp, pi);
  3646. /* And store this under the appropriate id, then clean up. */
  3647. store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
  3648. interlace_type, 0, 0, 0));
  3649. store_write_reset(ps);
  3650. }
  3651. Catch(fault)
  3652. {
  3653. /* Use the png_store returned by the exception. This may help the compiler
  3654. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3655. * and ps will always be the same value.
  3656. */
  3657. store_write_reset(fault);
  3658. }
  3659. }
  3660. static void
  3661. make_transform_images(png_modifier *pm)
  3662. {
  3663. png_byte colour_type = 0;
  3664. png_byte bit_depth = 0;
  3665. unsigned int palette_number = 0;
  3666. /* This is in case of errors. */
  3667. safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
  3668. /* Use next_format to enumerate all the combinations we test, including
  3669. * generating multiple low bit depth palette images. Non-A images (palette
  3670. * and direct) are created with and without tRNS chunks.
  3671. */
  3672. while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
  3673. {
  3674. int interlace_type;
  3675. for (interlace_type = PNG_INTERLACE_NONE;
  3676. interlace_type < INTERLACE_LAST; ++interlace_type)
  3677. {
  3678. char name[FILE_NAME_SIZE];
  3679. standard_name(name, sizeof name, 0, colour_type, bit_depth,
  3680. palette_number, interlace_type, 0, 0, do_own_interlace);
  3681. make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
  3682. interlace_type, name);
  3683. }
  3684. }
  3685. }
  3686. /* Build a single row for the 'size' test images; this fills in only the
  3687. * first bit_width bits of the sample row.
  3688. */
  3689. static void
  3690. size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
  3691. {
  3692. /* height is in the range 1 to 16, so: */
  3693. y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
  3694. /* the following ensures bits are set in small images: */
  3695. y ^= 0xA5;
  3696. while (bit_width >= 8)
  3697. *buffer++ = (png_byte)y++, bit_width -= 8;
  3698. /* There may be up to 7 remaining bits, these go in the most significant
  3699. * bits of the byte.
  3700. */
  3701. if (bit_width > 0)
  3702. {
  3703. png_uint_32 mask = (1U<<(8-bit_width))-1;
  3704. *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
  3705. }
  3706. }
  3707. static void
  3708. make_size_image(png_store* const ps, png_byte const colour_type,
  3709. png_byte const bit_depth, int const interlace_type,
  3710. png_uint_32 const w, png_uint_32 const h,
  3711. int const do_interlace)
  3712. {
  3713. context(ps, fault);
  3714. check_interlace_type(interlace_type);
  3715. Try
  3716. {
  3717. png_infop pi;
  3718. png_structp pp;
  3719. unsigned int pixel_size;
  3720. /* Make a name and get an appropriate id for the store: */
  3721. char name[FILE_NAME_SIZE];
  3722. png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
  3723. interlace_type, w, h, do_interlace);
  3724. standard_name_from_id(name, sizeof name, 0, id);
  3725. pp = set_store_for_write(ps, &pi, name);
  3726. /* In the event of a problem return control to the Catch statement below
  3727. * to do the clean up - it is not possible to 'return' directly from a Try
  3728. * block.
  3729. */
  3730. if (pp == NULL)
  3731. Throw ps;
  3732. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3733. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3734. #ifdef PNG_TEXT_SUPPORTED
  3735. {
  3736. static char key[] = "image name"; /* must be writeable */
  3737. size_t pos;
  3738. png_text text;
  3739. char copy[FILE_NAME_SIZE];
  3740. /* Use a compressed text string to test the correct interaction of text
  3741. * compression and IDAT compression.
  3742. */
  3743. text.compression = TEXT_COMPRESSION;
  3744. text.key = key;
  3745. /* Yuck: the text must be writable! */
  3746. pos = safecat(copy, sizeof copy, 0, ps->wname);
  3747. text.text = copy;
  3748. text.text_length = pos;
  3749. text.itxt_length = 0;
  3750. text.lang = 0;
  3751. text.lang_key = 0;
  3752. png_set_text(pp, pi, &text, 1);
  3753. }
  3754. #endif
  3755. if (colour_type == 3) /* palette */
  3756. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  3757. png_write_info(pp, pi);
  3758. /* Calculate the bit size, divide by 8 to get the byte size - this won't
  3759. * overflow because we know the w values are all small enough even for
  3760. * a system where 'unsigned int' is only 16 bits.
  3761. */
  3762. pixel_size = bit_size(pp, colour_type, bit_depth);
  3763. if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
  3764. png_error(pp, "size row size incorrect");
  3765. else
  3766. {
  3767. int npasses = npasses_from_interlace_type(pp, interlace_type);
  3768. png_uint_32 y;
  3769. int pass;
  3770. png_byte image[16][SIZE_ROWMAX];
  3771. /* To help consistent error detection make the parts of this buffer
  3772. * that aren't set below all '1':
  3773. */
  3774. memset(image, 0xff, sizeof image);
  3775. if (!do_interlace &&
  3776. npasses != set_write_interlace_handling(pp, interlace_type))
  3777. png_error(pp, "write: png_set_interlace_handling failed");
  3778. /* Prepare the whole image first to avoid making it 7 times: */
  3779. for (y=0; y<h; ++y)
  3780. size_row(image[y], w * pixel_size, y);
  3781. for (pass=0; pass<npasses; ++pass)
  3782. {
  3783. /* The following two are for checking the macros: */
  3784. png_uint_32 wPass = PNG_PASS_COLS(w, pass);
  3785. /* If do_interlace is set we don't call png_write_row for every
  3786. * row because some of them are empty. In fact, for a 1x1 image,
  3787. * most of them are empty!
  3788. */
  3789. for (y=0; y<h; ++y)
  3790. {
  3791. png_const_bytep row = image[y];
  3792. png_byte tempRow[SIZE_ROWMAX];
  3793. /* If do_interlace *and* the image is interlaced we
  3794. * need a reduced interlace row; this may be reduced
  3795. * to empty.
  3796. */
  3797. if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
  3798. {
  3799. /* The row must not be written if it doesn't exist, notice
  3800. * that there are two conditions here, either the row isn't
  3801. * ever in the pass or the row would be but isn't wide
  3802. * enough to contribute any pixels. In fact the wPass test
  3803. * can be used to skip the whole y loop in this case.
  3804. */
  3805. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
  3806. {
  3807. /* Set to all 1's for error detection (libpng tends to
  3808. * set unset things to 0).
  3809. */
  3810. memset(tempRow, 0xff, sizeof tempRow);
  3811. interlace_row(tempRow, row, pixel_size, w, pass,
  3812. 0/*data always bigendian*/);
  3813. row = tempRow;
  3814. }
  3815. else
  3816. continue;
  3817. }
  3818. # ifdef PNG_WRITE_FILTER_SUPPORTED
  3819. /* Only get to here if the row has some pixels in it, set the
  3820. * filters to 'all' for the very first row and thereafter to a
  3821. * single filter. It isn't well documented, but png_set_filter
  3822. * does accept a filter number (per the spec) as well as a bit
  3823. * mask.
  3824. *
  3825. * The code now uses filters at random, except that on the first
  3826. * row of an image it ensures that a previous row filter is in
  3827. * the set so that libpng allocates the row buffer.
  3828. */
  3829. {
  3830. int filters = 8 << random_mod(PNG_FILTER_VALUE_LAST);
  3831. if (pass == 0 && y == 0 &&
  3832. (filters < PNG_FILTER_UP || w == 1U))
  3833. filters |= PNG_FILTER_UP;
  3834. png_set_filter(pp, 0/*method*/, filters);
  3835. }
  3836. # endif
  3837. png_write_row(pp, row);
  3838. }
  3839. }
  3840. }
  3841. #ifdef PNG_TEXT_SUPPORTED
  3842. {
  3843. static char key[] = "end marker";
  3844. static char comment[] = "end";
  3845. png_text text;
  3846. /* Use a compressed text string to test the correct interaction of text
  3847. * compression and IDAT compression.
  3848. */
  3849. text.compression = TEXT_COMPRESSION;
  3850. text.key = key;
  3851. text.text = comment;
  3852. text.text_length = (sizeof comment)-1;
  3853. text.itxt_length = 0;
  3854. text.lang = 0;
  3855. text.lang_key = 0;
  3856. png_set_text(pp, pi, &text, 1);
  3857. }
  3858. #endif
  3859. png_write_end(pp, pi);
  3860. /* And store this under the appropriate id, then clean up. */
  3861. store_storefile(ps, id);
  3862. store_write_reset(ps);
  3863. }
  3864. Catch(fault)
  3865. {
  3866. /* Use the png_store returned by the exception. This may help the compiler
  3867. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3868. * and ps will always be the same value.
  3869. */
  3870. store_write_reset(fault);
  3871. }
  3872. }
  3873. static void
  3874. make_size(png_store* const ps, png_byte const colour_type, int bdlo,
  3875. int const bdhi)
  3876. {
  3877. for (; bdlo <= bdhi; ++bdlo)
  3878. {
  3879. png_uint_32 width;
  3880. for (width = 1; width <= 16; ++width)
  3881. {
  3882. png_uint_32 height;
  3883. for (height = 1; height <= 16; ++height)
  3884. {
  3885. /* The four combinations of DIY interlace and interlace or not -
  3886. * no interlace + DIY should be identical to no interlace with
  3887. * libpng doing it.
  3888. */
  3889. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3890. width, height, 0);
  3891. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3892. width, height, 1);
  3893. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  3894. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3895. width, height, 0);
  3896. # endif
  3897. # if CAN_WRITE_INTERLACE
  3898. /* 1.7.0 removes the hack that prevented app write of an interlaced
  3899. * image if WRITE_INTERLACE was not supported
  3900. */
  3901. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3902. width, height, 1);
  3903. # endif
  3904. }
  3905. }
  3906. }
  3907. }
  3908. static void
  3909. make_size_images(png_store *ps)
  3910. {
  3911. /* This is in case of errors. */
  3912. safecat(ps->test, sizeof ps->test, 0, "make size images");
  3913. /* Arguments are colour_type, low bit depth, high bit depth
  3914. */
  3915. make_size(ps, 0, 0, WRITE_BDHI);
  3916. make_size(ps, 2, 3, WRITE_BDHI);
  3917. make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
  3918. make_size(ps, 4, 3, WRITE_BDHI);
  3919. make_size(ps, 6, 3, WRITE_BDHI);
  3920. }
  3921. #ifdef PNG_READ_SUPPORTED
  3922. /* Return a row based on image id and 'y' for checking: */
  3923. static void
  3924. standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
  3925. png_uint_32 id, png_uint_32 y)
  3926. {
  3927. if (WIDTH_FROM_ID(id) == 0)
  3928. transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
  3929. else
  3930. size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
  3931. DEPTH_FROM_ID(id)), y);
  3932. }
  3933. #endif /* PNG_READ_SUPPORTED */
  3934. /* Tests - individual test cases */
  3935. /* Like 'make_standard' but errors are deliberately introduced into the calls
  3936. * to ensure that they get detected - it should not be possible to write an
  3937. * invalid image with libpng!
  3938. */
  3939. /* TODO: the 'set' functions can probably all be made to take a
  3940. * png_const_structp rather than a modifiable one.
  3941. */
  3942. #ifdef PNG_WARNINGS_SUPPORTED
  3943. static void
  3944. sBIT0_error_fn(png_structp pp, png_infop pi)
  3945. {
  3946. /* 0 is invalid... */
  3947. png_color_8 bad;
  3948. bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
  3949. png_set_sBIT(pp, pi, &bad);
  3950. }
  3951. static void
  3952. sBIT_error_fn(png_structp pp, png_infop pi)
  3953. {
  3954. png_byte bit_depth;
  3955. png_color_8 bad;
  3956. if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
  3957. bit_depth = 8;
  3958. else
  3959. bit_depth = png_get_bit_depth(pp, pi);
  3960. /* Now we know the bit depth we can easily generate an invalid sBIT entry */
  3961. bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
  3962. (png_byte)(bit_depth+1);
  3963. png_set_sBIT(pp, pi, &bad);
  3964. }
  3965. static const struct
  3966. {
  3967. void (*fn)(png_structp, png_infop);
  3968. const char *msg;
  3969. unsigned int warning :1; /* the error is a warning... */
  3970. } error_test[] =
  3971. {
  3972. /* no warnings makes these errors undetectable prior to 1.7.0 */
  3973. { sBIT0_error_fn, "sBIT(0): failed to detect error",
  3974. PNG_LIBPNG_VER != 10700 },
  3975. { sBIT_error_fn, "sBIT(too big): failed to detect error",
  3976. PNG_LIBPNG_VER != 10700 },
  3977. };
  3978. static void
  3979. make_error(png_store* const ps, png_byte const colour_type,
  3980. png_byte bit_depth, int interlace_type, int test, png_const_charp name)
  3981. {
  3982. context(ps, fault);
  3983. check_interlace_type(interlace_type);
  3984. Try
  3985. {
  3986. png_infop pi;
  3987. png_structp pp = set_store_for_write(ps, &pi, name);
  3988. png_uint_32 w, h;
  3989. gnu_volatile(pp)
  3990. if (pp == NULL)
  3991. Throw ps;
  3992. w = transform_width(pp, colour_type, bit_depth);
  3993. gnu_volatile(w)
  3994. h = transform_height(pp, colour_type, bit_depth);
  3995. gnu_volatile(h)
  3996. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3997. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3998. if (colour_type == 3) /* palette */
  3999. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  4000. /* Time for a few errors; these are in various optional chunks, the
  4001. * standard tests test the standard chunks pretty well.
  4002. */
  4003. # define exception__prev exception_prev_1
  4004. # define exception__env exception_env_1
  4005. Try
  4006. {
  4007. gnu_volatile(exception__prev)
  4008. /* Expect this to throw: */
  4009. ps->expect_error = !error_test[test].warning;
  4010. ps->expect_warning = error_test[test].warning;
  4011. ps->saw_warning = 0;
  4012. error_test[test].fn(pp, pi);
  4013. /* Normally the error is only detected here: */
  4014. png_write_info(pp, pi);
  4015. /* And handle the case where it was only a warning: */
  4016. if (ps->expect_warning && ps->saw_warning)
  4017. Throw ps;
  4018. /* If we get here there is a problem, we have success - no error or
  4019. * no warning - when we shouldn't have success. Log an error.
  4020. */
  4021. store_log(ps, pp, error_test[test].msg, 1 /*error*/);
  4022. }
  4023. Catch (fault)
  4024. { /* expected exit */
  4025. }
  4026. #undef exception__prev
  4027. #undef exception__env
  4028. /* And clear these flags */
  4029. ps->expect_warning = 0;
  4030. if (ps->expect_error)
  4031. ps->expect_error = 0;
  4032. else
  4033. {
  4034. /* Now write the whole image, just to make sure that the detected, or
  4035. * undetected, error has not created problems inside libpng. This
  4036. * doesn't work if there was a png_error in png_write_info because that
  4037. * can abort before PLTE was written.
  4038. */
  4039. if (png_get_rowbytes(pp, pi) !=
  4040. transform_rowsize(pp, colour_type, bit_depth))
  4041. png_error(pp, "row size incorrect");
  4042. else
  4043. {
  4044. int npasses = set_write_interlace_handling(pp, interlace_type);
  4045. int pass;
  4046. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  4047. png_error(pp, "write: png_set_interlace_handling failed");
  4048. for (pass=0; pass<npasses; ++pass)
  4049. {
  4050. png_uint_32 y;
  4051. for (y=0; y<h; ++y)
  4052. {
  4053. png_byte buffer[TRANSFORM_ROWMAX];
  4054. transform_row(pp, buffer, colour_type, bit_depth, y);
  4055. # if do_own_interlace
  4056. /* If do_own_interlace *and* the image is interlaced we
  4057. * need a reduced interlace row; this may be reduced to
  4058. * empty.
  4059. */
  4060. if (interlace_type == PNG_INTERLACE_ADAM7)
  4061. {
  4062. /* The row must not be written if it doesn't exist,
  4063. * notice that there are two conditions here, either the
  4064. * row isn't ever in the pass or the row would be but
  4065. * isn't wide enough to contribute any pixels. In fact
  4066. * the wPass test can be used to skip the whole y loop
  4067. * in this case.
  4068. */
  4069. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  4070. PNG_PASS_COLS(w, pass) > 0)
  4071. interlace_row(buffer, buffer,
  4072. bit_size(pp, colour_type, bit_depth), w, pass,
  4073. 0/*data always bigendian*/);
  4074. else
  4075. continue;
  4076. }
  4077. # endif /* do_own_interlace */
  4078. png_write_row(pp, buffer);
  4079. }
  4080. }
  4081. } /* image writing */
  4082. png_write_end(pp, pi);
  4083. }
  4084. /* The following deletes the file that was just written. */
  4085. store_write_reset(ps);
  4086. }
  4087. Catch(fault)
  4088. {
  4089. store_write_reset(fault);
  4090. }
  4091. }
  4092. static int
  4093. make_errors(png_modifier* const pm, png_byte const colour_type,
  4094. int bdlo, int const bdhi)
  4095. {
  4096. for (; bdlo <= bdhi; ++bdlo)
  4097. {
  4098. int interlace_type;
  4099. for (interlace_type = PNG_INTERLACE_NONE;
  4100. interlace_type < INTERLACE_LAST; ++interlace_type)
  4101. {
  4102. unsigned int test;
  4103. char name[FILE_NAME_SIZE];
  4104. standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
  4105. interlace_type, 0, 0, do_own_interlace);
  4106. for (test=0; test<ARRAY_SIZE(error_test); ++test)
  4107. {
  4108. make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
  4109. test, name);
  4110. if (fail(pm))
  4111. return 0;
  4112. }
  4113. }
  4114. }
  4115. return 1; /* keep going */
  4116. }
  4117. #endif /* PNG_WARNINGS_SUPPORTED */
  4118. static void
  4119. perform_error_test(png_modifier *pm)
  4120. {
  4121. #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
  4122. /* Need to do this here because we just write in this test. */
  4123. safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
  4124. if (!make_errors(pm, 0, 0, WRITE_BDHI))
  4125. return;
  4126. if (!make_errors(pm, 2, 3, WRITE_BDHI))
  4127. return;
  4128. if (!make_errors(pm, 3, 0, 3))
  4129. return;
  4130. if (!make_errors(pm, 4, 3, WRITE_BDHI))
  4131. return;
  4132. if (!make_errors(pm, 6, 3, WRITE_BDHI))
  4133. return;
  4134. #else
  4135. UNUSED(pm)
  4136. #endif
  4137. }
  4138. /* This is just to validate the internal PNG formatting code - if this fails
  4139. * then the warning messages the library outputs will probably be garbage.
  4140. */
  4141. static void
  4142. perform_formatting_test(png_store *ps)
  4143. {
  4144. #ifdef PNG_TIME_RFC1123_SUPPORTED
  4145. /* The handle into the formatting code is the RFC1123 support; this test does
  4146. * nothing if that is compiled out.
  4147. */
  4148. context(ps, fault);
  4149. Try
  4150. {
  4151. png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
  4152. png_const_charp result;
  4153. # if PNG_LIBPNG_VER >= 10600
  4154. char timestring[29];
  4155. # endif
  4156. png_structp pp;
  4157. png_time pt;
  4158. pp = set_store_for_write(ps, NULL, "libpng formatting test");
  4159. if (pp == NULL)
  4160. Throw ps;
  4161. /* Arbitrary settings: */
  4162. pt.year = 2079;
  4163. pt.month = 8;
  4164. pt.day = 29;
  4165. pt.hour = 13;
  4166. pt.minute = 53;
  4167. pt.second = 60; /* a leap second */
  4168. # if PNG_LIBPNG_VER < 10600
  4169. result = png_convert_to_rfc1123(pp, &pt);
  4170. # else
  4171. if (png_convert_to_rfc1123_buffer(timestring, &pt))
  4172. result = timestring;
  4173. else
  4174. result = NULL;
  4175. # endif
  4176. if (result == NULL)
  4177. png_error(pp, "png_convert_to_rfc1123 failed");
  4178. if (strcmp(result, correct) != 0)
  4179. {
  4180. size_t pos = 0;
  4181. char msg[128];
  4182. pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
  4183. pos = safecat(msg, sizeof msg, pos, correct);
  4184. pos = safecat(msg, sizeof msg, pos, ") returned: '");
  4185. pos = safecat(msg, sizeof msg, pos, result);
  4186. pos = safecat(msg, sizeof msg, pos, "'");
  4187. png_error(pp, msg);
  4188. }
  4189. store_write_reset(ps);
  4190. }
  4191. Catch(fault)
  4192. {
  4193. store_write_reset(fault);
  4194. }
  4195. #else
  4196. UNUSED(ps)
  4197. #endif
  4198. }
  4199. #ifdef PNG_READ_SUPPORTED
  4200. /* Because we want to use the same code in both the progressive reader and the
  4201. * sequential reader it is necessary to deal with the fact that the progressive
  4202. * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
  4203. * must contain all the test parameters and all the local variables directly
  4204. * accessible to the sequential reader implementation.
  4205. *
  4206. * The technique adopted is to reinvent part of what Dijkstra termed a
  4207. * 'display'; an array of pointers to the stack frames of enclosing functions so
  4208. * that a nested function definition can access the local (C auto) variables of
  4209. * the functions that contain its definition. In fact C provides the first
  4210. * pointer (the local variables - the stack frame pointer) and the last (the
  4211. * global variables - the BCPL global vector typically implemented as global
  4212. * addresses), this code requires one more pointer to make the display - the
  4213. * local variables (and function call parameters) of the function that actually
  4214. * invokes either the progressive or sequential reader.
  4215. *
  4216. * Perhaps confusingly this technique is confounded with classes - the
  4217. * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
  4218. * A gamma_display is a standard_display, taking advantage of the ANSI-C
  4219. * requirement that the pointer to the first member of a structure must be the
  4220. * same as the pointer to the structure. This allows us to reuse standard_
  4221. * functions in the gamma test code; something that could not be done with
  4222. * nested functions!
  4223. */
  4224. typedef struct standard_display
  4225. {
  4226. png_store* ps; /* Test parameters (passed to the function) */
  4227. png_byte colour_type;
  4228. png_byte bit_depth;
  4229. png_byte red_sBIT; /* Input data sBIT values. */
  4230. png_byte green_sBIT;
  4231. png_byte blue_sBIT;
  4232. png_byte alpha_sBIT;
  4233. png_byte interlace_type;
  4234. png_byte filler; /* Output has a filler */
  4235. png_uint_32 id; /* Calculated file ID */
  4236. png_uint_32 w; /* Width of image */
  4237. png_uint_32 h; /* Height of image */
  4238. int npasses; /* Number of interlaced passes */
  4239. png_uint_32 pixel_size; /* Width of one pixel in bits */
  4240. png_uint_32 bit_width; /* Width of output row in bits */
  4241. size_t cbRow; /* Bytes in a row of the output image */
  4242. int do_interlace; /* Do interlacing internally */
  4243. int littleendian; /* App (row) data is little endian */
  4244. int is_transparent; /* Transparency information was present. */
  4245. int has_tRNS; /* color type GRAY or RGB with a tRNS chunk. */
  4246. int speed; /* Doing a speed test */
  4247. int use_update_info;/* Call update_info, not start_image */
  4248. struct
  4249. {
  4250. png_uint_16 red;
  4251. png_uint_16 green;
  4252. png_uint_16 blue;
  4253. } transparent; /* The transparent color, if set. */
  4254. int npalette; /* Number of entries in the palette. */
  4255. store_palette
  4256. palette;
  4257. } standard_display;
  4258. static void
  4259. standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
  4260. int do_interlace, int use_update_info)
  4261. {
  4262. memset(dp, 0, sizeof *dp);
  4263. dp->ps = ps;
  4264. dp->colour_type = COL_FROM_ID(id);
  4265. dp->bit_depth = DEPTH_FROM_ID(id);
  4266. if (dp->bit_depth < 1 || dp->bit_depth > 16)
  4267. internal_error(ps, "internal: bad bit depth");
  4268. if (dp->colour_type == 3)
  4269. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
  4270. else
  4271. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
  4272. dp->bit_depth;
  4273. dp->interlace_type = INTERLACE_FROM_ID(id);
  4274. check_interlace_type(dp->interlace_type);
  4275. dp->id = id;
  4276. /* All the rest are filled in after the read_info: */
  4277. dp->w = 0;
  4278. dp->h = 0;
  4279. dp->npasses = 0;
  4280. dp->pixel_size = 0;
  4281. dp->bit_width = 0;
  4282. dp->cbRow = 0;
  4283. dp->do_interlace = do_interlace;
  4284. dp->littleendian = 0;
  4285. dp->is_transparent = 0;
  4286. dp->speed = ps->speed;
  4287. dp->use_update_info = use_update_info;
  4288. dp->npalette = 0;
  4289. /* Preset the transparent color to black: */
  4290. memset(&dp->transparent, 0, sizeof dp->transparent);
  4291. /* Preset the palette to full intensity/opaque throughout: */
  4292. memset(dp->palette, 0xff, sizeof dp->palette);
  4293. }
  4294. /* Initialize the palette fields - this must be done later because the palette
  4295. * comes from the particular png_store_file that is selected.
  4296. */
  4297. static void
  4298. standard_palette_init(standard_display *dp)
  4299. {
  4300. store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
  4301. /* The remaining entries remain white/opaque. */
  4302. if (dp->npalette > 0)
  4303. {
  4304. int i = dp->npalette;
  4305. memcpy(dp->palette, palette, i * sizeof *palette);
  4306. /* Check for a non-opaque palette entry: */
  4307. while (--i >= 0)
  4308. if (palette[i].alpha < 255)
  4309. break;
  4310. # ifdef __GNUC__
  4311. /* GCC can't handle the more obviously optimizable version. */
  4312. if (i >= 0)
  4313. dp->is_transparent = 1;
  4314. else
  4315. dp->is_transparent = 0;
  4316. # else
  4317. dp->is_transparent = (i >= 0);
  4318. # endif
  4319. }
  4320. }
  4321. /* Utility to read the palette from the PNG file and convert it into
  4322. * store_palette format. This returns 1 if there is any transparency in the
  4323. * palette (it does not check for a transparent colour in the non-palette case.)
  4324. */
  4325. static int
  4326. read_palette(store_palette palette, int *npalette, png_const_structp pp,
  4327. png_infop pi)
  4328. {
  4329. png_colorp pal;
  4330. png_bytep trans_alpha;
  4331. int num;
  4332. pal = 0;
  4333. *npalette = -1;
  4334. if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
  4335. {
  4336. int i = *npalette;
  4337. if (i <= 0 || i > 256)
  4338. png_error(pp, "validate: invalid PLTE count");
  4339. while (--i >= 0)
  4340. {
  4341. palette[i].red = pal[i].red;
  4342. palette[i].green = pal[i].green;
  4343. palette[i].blue = pal[i].blue;
  4344. }
  4345. /* Mark the remainder of the entries with a flag value (other than
  4346. * white/opaque which is the flag value stored above.)
  4347. */
  4348. memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
  4349. }
  4350. else /* !png_get_PLTE */
  4351. {
  4352. if (*npalette != (-1))
  4353. png_error(pp, "validate: invalid PLTE result");
  4354. /* But there is no palette, so record this: */
  4355. *npalette = 0;
  4356. memset(palette, 113, sizeof (store_palette));
  4357. }
  4358. trans_alpha = 0;
  4359. num = 2; /* force error below */
  4360. if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
  4361. (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
  4362. /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
  4363. * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
  4364. * so in the above call we get a success, we get a pointer (who knows what
  4365. * to) and we get num_trans == 0:
  4366. */
  4367. !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
  4368. {
  4369. int i;
  4370. /* Any of these are crash-worthy - given the implementation of
  4371. * png_get_tRNS up to 1.5 an app won't crash if it just checks the
  4372. * result above and fails to check that the variables it passed have
  4373. * actually been filled in! Note that if the app were to pass the
  4374. * last, png_color_16p, variable too it couldn't rely on this.
  4375. */
  4376. if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
  4377. png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
  4378. for (i=0; i<num; ++i)
  4379. palette[i].alpha = trans_alpha[i];
  4380. for (num=*npalette; i<num; ++i)
  4381. palette[i].alpha = 255;
  4382. for (; i<256; ++i)
  4383. palette[i].alpha = 33; /* flag value */
  4384. return 1; /* transparency */
  4385. }
  4386. else
  4387. {
  4388. /* No palette transparency - just set the alpha channel to opaque. */
  4389. int i;
  4390. for (i=0, num=*npalette; i<num; ++i)
  4391. palette[i].alpha = 255;
  4392. for (; i<256; ++i)
  4393. palette[i].alpha = 55; /* flag value */
  4394. return 0; /* no transparency */
  4395. }
  4396. }
  4397. /* Utility to validate the palette if it should not have changed (the
  4398. * non-transform case).
  4399. */
  4400. static void
  4401. standard_palette_validate(standard_display *dp, png_const_structp pp,
  4402. png_infop pi)
  4403. {
  4404. int npalette;
  4405. store_palette palette;
  4406. if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
  4407. png_error(pp, "validate: palette transparency changed");
  4408. if (npalette != dp->npalette)
  4409. {
  4410. size_t pos = 0;
  4411. char msg[64];
  4412. pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
  4413. pos = safecatn(msg, sizeof msg, pos, dp->npalette);
  4414. pos = safecat(msg, sizeof msg, pos, " -> ");
  4415. pos = safecatn(msg, sizeof msg, pos, npalette);
  4416. png_error(pp, msg);
  4417. }
  4418. {
  4419. int i = npalette; /* npalette is aliased */
  4420. while (--i >= 0)
  4421. if (palette[i].red != dp->palette[i].red ||
  4422. palette[i].green != dp->palette[i].green ||
  4423. palette[i].blue != dp->palette[i].blue ||
  4424. palette[i].alpha != dp->palette[i].alpha)
  4425. png_error(pp, "validate: PLTE or tRNS chunk changed");
  4426. }
  4427. }
  4428. /* By passing a 'standard_display' the progressive callbacks can be used
  4429. * directly by the sequential code, the functions suffixed "_imp" are the
  4430. * implementations, the functions without the suffix are the callbacks.
  4431. *
  4432. * The code for the info callback is split into two because this callback calls
  4433. * png_read_update_info or png_start_read_image and what gets called depends on
  4434. * whether the info needs updating (we want to test both calls in pngvalid.)
  4435. */
  4436. static void
  4437. standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
  4438. {
  4439. if (png_get_bit_depth(pp, pi) != dp->bit_depth)
  4440. png_error(pp, "validate: bit depth changed");
  4441. if (png_get_color_type(pp, pi) != dp->colour_type)
  4442. png_error(pp, "validate: color type changed");
  4443. if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
  4444. png_error(pp, "validate: filter type changed");
  4445. if (png_get_interlace_type(pp, pi) != dp->interlace_type)
  4446. png_error(pp, "validate: interlacing changed");
  4447. if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
  4448. png_error(pp, "validate: compression type changed");
  4449. dp->w = png_get_image_width(pp, pi);
  4450. if (dp->w != standard_width(pp, dp->id))
  4451. png_error(pp, "validate: image width changed");
  4452. dp->h = png_get_image_height(pp, pi);
  4453. if (dp->h != standard_height(pp, dp->id))
  4454. png_error(pp, "validate: image height changed");
  4455. /* Record (but don't check at present) the input sBIT according to the colour
  4456. * type information.
  4457. */
  4458. {
  4459. png_color_8p sBIT = 0;
  4460. if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
  4461. {
  4462. int sBIT_invalid = 0;
  4463. if (sBIT == 0)
  4464. png_error(pp, "validate: unexpected png_get_sBIT result");
  4465. if (dp->colour_type & PNG_COLOR_MASK_COLOR)
  4466. {
  4467. if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
  4468. sBIT_invalid = 1;
  4469. else
  4470. dp->red_sBIT = sBIT->red;
  4471. if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
  4472. sBIT_invalid = 1;
  4473. else
  4474. dp->green_sBIT = sBIT->green;
  4475. if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
  4476. sBIT_invalid = 1;
  4477. else
  4478. dp->blue_sBIT = sBIT->blue;
  4479. }
  4480. else /* !COLOR */
  4481. {
  4482. if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
  4483. sBIT_invalid = 1;
  4484. else
  4485. dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
  4486. }
  4487. /* All 8 bits in tRNS for a palette image are significant - see the
  4488. * spec.
  4489. */
  4490. if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
  4491. {
  4492. if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
  4493. sBIT_invalid = 1;
  4494. else
  4495. dp->alpha_sBIT = sBIT->alpha;
  4496. }
  4497. if (sBIT_invalid)
  4498. png_error(pp, "validate: sBIT value out of range");
  4499. }
  4500. }
  4501. /* Important: this is validating the value *before* any transforms have been
  4502. * put in place. It doesn't matter for the standard tests, where there are
  4503. * no transforms, but it does for other tests where rowbytes may change after
  4504. * png_read_update_info.
  4505. */
  4506. if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
  4507. png_error(pp, "validate: row size changed");
  4508. /* Validate the colour type 3 palette (this can be present on other color
  4509. * types.)
  4510. */
  4511. standard_palette_validate(dp, pp, pi);
  4512. /* In any case always check for a transparent color (notice that the
  4513. * colour type 3 case must not give a successful return on the get_tRNS call
  4514. * with these arguments!)
  4515. */
  4516. {
  4517. png_color_16p trans_color = 0;
  4518. if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
  4519. {
  4520. if (trans_color == 0)
  4521. png_error(pp, "validate: unexpected png_get_tRNS (color) result");
  4522. switch (dp->colour_type)
  4523. {
  4524. case 0:
  4525. dp->transparent.red = dp->transparent.green = dp->transparent.blue =
  4526. trans_color->gray;
  4527. dp->has_tRNS = 1;
  4528. break;
  4529. case 2:
  4530. dp->transparent.red = trans_color->red;
  4531. dp->transparent.green = trans_color->green;
  4532. dp->transparent.blue = trans_color->blue;
  4533. dp->has_tRNS = 1;
  4534. break;
  4535. case 3:
  4536. /* Not expected because it should result in the array case
  4537. * above.
  4538. */
  4539. png_error(pp, "validate: unexpected png_get_tRNS result");
  4540. break;
  4541. default:
  4542. png_error(pp, "validate: invalid tRNS chunk with alpha image");
  4543. }
  4544. }
  4545. }
  4546. /* Read the number of passes - expected to match the value used when
  4547. * creating the image (interlaced or not). This has the side effect of
  4548. * turning on interlace handling (if do_interlace is not set.)
  4549. */
  4550. dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
  4551. if (!dp->do_interlace)
  4552. {
  4553. # ifdef PNG_READ_INTERLACING_SUPPORTED
  4554. if (dp->npasses != png_set_interlace_handling(pp))
  4555. png_error(pp, "validate: file changed interlace type");
  4556. # else /* !READ_INTERLACING */
  4557. /* This should never happen: the relevant tests (!do_interlace) should
  4558. * not be run.
  4559. */
  4560. if (dp->npasses > 1)
  4561. png_error(pp, "validate: no libpng interlace support");
  4562. # endif /* !READ_INTERLACING */
  4563. }
  4564. /* Caller calls png_read_update_info or png_start_read_image now, then calls
  4565. * part2.
  4566. */
  4567. }
  4568. /* This must be called *after* the png_read_update_info call to get the correct
  4569. * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
  4570. * image.
  4571. */
  4572. static void
  4573. standard_info_part2(standard_display *dp, png_const_structp pp,
  4574. png_const_infop pi, int nImages)
  4575. {
  4576. /* Record cbRow now that it can be found. */
  4577. {
  4578. png_byte ct = png_get_color_type(pp, pi);
  4579. png_byte bd = png_get_bit_depth(pp, pi);
  4580. if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
  4581. dp->filler)
  4582. ct |= 4; /* handle filler as faked alpha channel */
  4583. dp->pixel_size = bit_size(pp, ct, bd);
  4584. }
  4585. dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
  4586. dp->cbRow = png_get_rowbytes(pp, pi);
  4587. /* Validate the rowbytes here again. */
  4588. if (dp->cbRow != (dp->bit_width+7)/8)
  4589. png_error(pp, "bad png_get_rowbytes calculation");
  4590. /* Then ensure there is enough space for the output image(s). */
  4591. store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
  4592. }
  4593. static void
  4594. standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
  4595. int nImages)
  4596. {
  4597. /* Note that the validation routine has the side effect of turning on
  4598. * interlace handling in the subsequent code.
  4599. */
  4600. standard_info_part1(dp, pp, pi);
  4601. /* And the info callback has to call this (or png_read_update_info - see
  4602. * below in the png_modifier code for that variant.
  4603. */
  4604. if (dp->use_update_info)
  4605. {
  4606. /* For debugging the effect of multiple calls: */
  4607. int i = dp->use_update_info;
  4608. while (i-- > 0)
  4609. png_read_update_info(pp, pi);
  4610. }
  4611. else
  4612. png_start_read_image(pp);
  4613. /* Validate the height, width and rowbytes plus ensure that sufficient buffer
  4614. * exists for decoding the image.
  4615. */
  4616. standard_info_part2(dp, pp, pi, nImages);
  4617. }
  4618. static void PNGCBAPI
  4619. standard_info(png_structp pp, png_infop pi)
  4620. {
  4621. standard_display *dp = voidcast(standard_display*,
  4622. png_get_progressive_ptr(pp));
  4623. /* Call with nImages==1 because the progressive reader can only produce one
  4624. * image.
  4625. */
  4626. standard_info_imp(dp, pp, pi, 1 /*only one image*/);
  4627. }
  4628. static void PNGCBAPI
  4629. progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
  4630. {
  4631. png_const_structp pp = ppIn;
  4632. const standard_display *dp = voidcast(standard_display*,
  4633. png_get_progressive_ptr(pp));
  4634. /* When handling interlacing some rows will be absent in each pass, the
  4635. * callback still gets called, but with a NULL pointer. This is checked
  4636. * in the 'else' clause below. We need our own 'cbRow', but we can't call
  4637. * png_get_rowbytes because we got no info structure.
  4638. */
  4639. if (new_row != NULL)
  4640. {
  4641. png_bytep row;
  4642. /* In the case where the reader doesn't do the interlace it gives
  4643. * us the y in the sub-image:
  4644. */
  4645. if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
  4646. {
  4647. #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
  4648. /* Use this opportunity to validate the png 'current' APIs: */
  4649. if (y != png_get_current_row_number(pp))
  4650. png_error(pp, "png_get_current_row_number is broken");
  4651. if (pass != png_get_current_pass_number(pp))
  4652. png_error(pp, "png_get_current_pass_number is broken");
  4653. #endif /* USER_TRANSFORM_INFO */
  4654. y = PNG_ROW_FROM_PASS_ROW(y, pass);
  4655. }
  4656. /* Validate this just in case. */
  4657. if (y >= dp->h)
  4658. png_error(pp, "invalid y to progressive row callback");
  4659. row = store_image_row(dp->ps, pp, 0, y);
  4660. /* Combine the new row into the old: */
  4661. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4662. if (dp->do_interlace)
  4663. #endif /* READ_INTERLACING */
  4664. {
  4665. if (dp->interlace_type == PNG_INTERLACE_ADAM7)
  4666. deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass,
  4667. dp->littleendian);
  4668. else
  4669. row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian);
  4670. }
  4671. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4672. else
  4673. png_progressive_combine_row(pp, row, new_row);
  4674. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  4675. }
  4676. else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
  4677. PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  4678. PNG_PASS_COLS(dp->w, pass) > 0)
  4679. png_error(pp, "missing row in progressive de-interlacing");
  4680. }
  4681. static void
  4682. sequential_row(standard_display *dp, png_structp pp, png_infop pi,
  4683. int iImage, int iDisplay)
  4684. {
  4685. int npasses = dp->npasses;
  4686. int do_interlace = dp->do_interlace &&
  4687. dp->interlace_type == PNG_INTERLACE_ADAM7;
  4688. png_uint_32 height = standard_height(pp, dp->id);
  4689. png_uint_32 width = standard_width(pp, dp->id);
  4690. const png_store* ps = dp->ps;
  4691. int pass;
  4692. for (pass=0; pass<npasses; ++pass)
  4693. {
  4694. png_uint_32 y;
  4695. png_uint_32 wPass = PNG_PASS_COLS(width, pass);
  4696. for (y=0; y<height; ++y)
  4697. {
  4698. if (do_interlace)
  4699. {
  4700. /* wPass may be zero or this row may not be in this pass.
  4701. * png_read_row must not be called in either case.
  4702. */
  4703. if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
  4704. {
  4705. /* Read the row into a pair of temporary buffers, then do the
  4706. * merge here into the output rows.
  4707. */
  4708. png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
  4709. /* The following aids (to some extent) error detection - we can
  4710. * see where png_read_row wrote. Use opposite values in row and
  4711. * display to make this easier. Don't use 0xff (which is used in
  4712. * the image write code to fill unused bits) or 0 (which is a
  4713. * likely value to overwrite unused bits with).
  4714. */
  4715. memset(row, 0xc5, sizeof row);
  4716. memset(display, 0x5c, sizeof display);
  4717. png_read_row(pp, row, display);
  4718. if (iImage >= 0)
  4719. deinterlace_row(store_image_row(ps, pp, iImage, y), row,
  4720. dp->pixel_size, dp->w, pass, dp->littleendian);
  4721. if (iDisplay >= 0)
  4722. deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
  4723. dp->pixel_size, dp->w, pass, dp->littleendian);
  4724. }
  4725. }
  4726. else
  4727. png_read_row(pp,
  4728. iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
  4729. iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
  4730. }
  4731. }
  4732. /* And finish the read operation (only really necessary if the caller wants
  4733. * to find additional data in png_info from chunks after the last IDAT.)
  4734. */
  4735. png_read_end(pp, pi);
  4736. }
  4737. #ifdef PNG_TEXT_SUPPORTED
  4738. static void
  4739. standard_check_text(png_const_structp pp, png_const_textp tp,
  4740. png_const_charp keyword, png_const_charp text)
  4741. {
  4742. char msg[1024];
  4743. size_t pos = safecat(msg, sizeof msg, 0, "text: ");
  4744. size_t ok;
  4745. pos = safecat(msg, sizeof msg, pos, keyword);
  4746. pos = safecat(msg, sizeof msg, pos, ": ");
  4747. ok = pos;
  4748. if (tp->compression != TEXT_COMPRESSION)
  4749. {
  4750. char buf[64];
  4751. sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
  4752. tp->compression);
  4753. pos = safecat(msg, sizeof msg, pos, buf);
  4754. }
  4755. if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
  4756. {
  4757. pos = safecat(msg, sizeof msg, pos, "keyword \"");
  4758. if (tp->key != NULL)
  4759. {
  4760. pos = safecat(msg, sizeof msg, pos, tp->key);
  4761. pos = safecat(msg, sizeof msg, pos, "\", ");
  4762. }
  4763. else
  4764. pos = safecat(msg, sizeof msg, pos, "null, ");
  4765. }
  4766. if (tp->text == NULL)
  4767. pos = safecat(msg, sizeof msg, pos, "text lost, ");
  4768. else
  4769. {
  4770. if (tp->text_length != strlen(text))
  4771. {
  4772. char buf[64];
  4773. sprintf(buf, "text length changed[%lu->%lu], ",
  4774. (unsigned long)strlen(text), (unsigned long)tp->text_length);
  4775. pos = safecat(msg, sizeof msg, pos, buf);
  4776. }
  4777. if (strcmp(tp->text, text) != 0)
  4778. {
  4779. pos = safecat(msg, sizeof msg, pos, "text becomes \"");
  4780. pos = safecat(msg, sizeof msg, pos, tp->text);
  4781. pos = safecat(msg, sizeof msg, pos, "\" (was \"");
  4782. pos = safecat(msg, sizeof msg, pos, text);
  4783. pos = safecat(msg, sizeof msg, pos, "\"), ");
  4784. }
  4785. }
  4786. if (tp->itxt_length != 0)
  4787. pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
  4788. if (tp->lang != NULL)
  4789. {
  4790. pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
  4791. pos = safecat(msg, sizeof msg, pos, tp->lang);
  4792. pos = safecat(msg, sizeof msg, pos, "\", ");
  4793. }
  4794. if (tp->lang_key != NULL)
  4795. {
  4796. pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
  4797. pos = safecat(msg, sizeof msg, pos, tp->lang_key);
  4798. pos = safecat(msg, sizeof msg, pos, "\", ");
  4799. }
  4800. if (pos > ok)
  4801. {
  4802. msg[pos-2] = '\0'; /* Remove the ", " at the end */
  4803. png_error(pp, msg);
  4804. }
  4805. }
  4806. static void
  4807. standard_text_validate(standard_display *dp, png_const_structp pp,
  4808. png_infop pi, int check_end)
  4809. {
  4810. png_textp tp = NULL;
  4811. png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
  4812. if (num_text == 2 && tp != NULL)
  4813. {
  4814. standard_check_text(pp, tp, "image name", dp->ps->current->name);
  4815. /* This exists because prior to 1.5.18 the progressive reader left the
  4816. * png_struct z_stream unreset at the end of the image, so subsequent
  4817. * attempts to use it simply returns Z_STREAM_END.
  4818. */
  4819. if (check_end)
  4820. standard_check_text(pp, tp+1, "end marker", "end");
  4821. }
  4822. else
  4823. {
  4824. char msg[64];
  4825. sprintf(msg, "expected two text items, got %lu",
  4826. (unsigned long)num_text);
  4827. png_error(pp, msg);
  4828. }
  4829. }
  4830. #else
  4831. # define standard_text_validate(dp,pp,pi,check_end) ((void)0)
  4832. #endif
  4833. static void
  4834. standard_row_validate(standard_display *dp, png_const_structp pp,
  4835. int iImage, int iDisplay, png_uint_32 y)
  4836. {
  4837. int where;
  4838. png_byte std[STANDARD_ROWMAX];
  4839. /* The row must be pre-initialized to the magic number here for the size
  4840. * tests to pass:
  4841. */
  4842. memset(std, 178, sizeof std);
  4843. standard_row(pp, std, dp->id, y);
  4844. /* At the end both the 'row' and 'display' arrays should end up identical.
  4845. * In earlier passes 'row' will be partially filled in, with only the pixels
  4846. * that have been read so far, but 'display' will have those pixels
  4847. * replicated to fill the unread pixels while reading an interlaced image.
  4848. */
  4849. if (iImage >= 0 &&
  4850. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
  4851. dp->bit_width)) != 0)
  4852. {
  4853. char msg[64];
  4854. sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
  4855. (unsigned long)y, where-1, std[where-1],
  4856. store_image_row(dp->ps, pp, iImage, y)[where-1]);
  4857. png_error(pp, msg);
  4858. }
  4859. if (iDisplay >= 0 &&
  4860. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
  4861. dp->bit_width)) != 0)
  4862. {
  4863. char msg[64];
  4864. sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
  4865. (unsigned long)y, where-1, std[where-1],
  4866. store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
  4867. png_error(pp, msg);
  4868. }
  4869. }
  4870. static void
  4871. standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
  4872. int iDisplay)
  4873. {
  4874. png_uint_32 y;
  4875. if (iImage >= 0)
  4876. store_image_check(dp->ps, pp, iImage);
  4877. if (iDisplay >= 0)
  4878. store_image_check(dp->ps, pp, iDisplay);
  4879. for (y=0; y<dp->h; ++y)
  4880. standard_row_validate(dp, pp, iImage, iDisplay, y);
  4881. /* This avoids false positives if the validation code is never called! */
  4882. dp->ps->validated = 1;
  4883. }
  4884. static void PNGCBAPI
  4885. standard_end(png_structp ppIn, png_infop pi)
  4886. {
  4887. png_const_structp pp = ppIn;
  4888. standard_display *dp = voidcast(standard_display*,
  4889. png_get_progressive_ptr(pp));
  4890. UNUSED(pi)
  4891. /* Validate the image - progressive reading only produces one variant for
  4892. * interlaced images.
  4893. */
  4894. standard_text_validate(dp, pp, pi,
  4895. PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
  4896. standard_image_validate(dp, pp, 0, -1);
  4897. }
  4898. /* A single test run checking the standard image to ensure it is not damaged. */
  4899. static void
  4900. standard_test(png_store* const psIn, png_uint_32 const id,
  4901. int do_interlace, int use_update_info)
  4902. {
  4903. standard_display d;
  4904. context(psIn, fault);
  4905. /* Set up the display (stack frame) variables from the arguments to the
  4906. * function and initialize the locals that are filled in later.
  4907. */
  4908. standard_display_init(&d, psIn, id, do_interlace, use_update_info);
  4909. /* Everything is protected by a Try/Catch. The functions called also
  4910. * typically have local Try/Catch blocks.
  4911. */
  4912. Try
  4913. {
  4914. png_structp pp;
  4915. png_infop pi;
  4916. /* Get a png_struct for reading the image. This will throw an error if it
  4917. * fails, so we don't need to check the result.
  4918. */
  4919. pp = set_store_for_read(d.ps, &pi, d.id,
  4920. d.do_interlace ? (d.ps->progressive ?
  4921. "pngvalid progressive deinterlacer" :
  4922. "pngvalid sequential deinterlacer") : (d.ps->progressive ?
  4923. "progressive reader" : "sequential reader"));
  4924. /* Initialize the palette correctly from the png_store_file. */
  4925. standard_palette_init(&d);
  4926. /* Introduce the correct read function. */
  4927. if (d.ps->progressive)
  4928. {
  4929. png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
  4930. standard_end);
  4931. /* Now feed data into the reader until we reach the end: */
  4932. store_progressive_read(d.ps, pp, pi);
  4933. }
  4934. else
  4935. {
  4936. /* Note that this takes the store, not the display. */
  4937. png_set_read_fn(pp, d.ps, store_read);
  4938. /* Check the header values: */
  4939. png_read_info(pp, pi);
  4940. /* The code tests both versions of the images that the sequential
  4941. * reader can produce.
  4942. */
  4943. standard_info_imp(&d, pp, pi, 2 /*images*/);
  4944. /* Need the total bytes in the image below; we can't get to this point
  4945. * unless the PNG file values have been checked against the expected
  4946. * values.
  4947. */
  4948. {
  4949. sequential_row(&d, pp, pi, 0, 1);
  4950. /* After the last pass loop over the rows again to check that the
  4951. * image is correct.
  4952. */
  4953. if (!d.speed)
  4954. {
  4955. standard_text_validate(&d, pp, pi, 1/*check_end*/);
  4956. standard_image_validate(&d, pp, 0, 1);
  4957. }
  4958. else
  4959. d.ps->validated = 1;
  4960. }
  4961. }
  4962. /* Check for validation. */
  4963. if (!d.ps->validated)
  4964. png_error(pp, "image read failed silently");
  4965. /* Successful completion. */
  4966. }
  4967. Catch(fault)
  4968. d.ps = fault; /* make sure this hasn't been clobbered. */
  4969. /* In either case clean up the store. */
  4970. store_read_reset(d.ps);
  4971. }
  4972. static int
  4973. test_standard(png_modifier* const pm, png_byte const colour_type,
  4974. int bdlo, int const bdhi)
  4975. {
  4976. for (; bdlo <= bdhi; ++bdlo)
  4977. {
  4978. int interlace_type;
  4979. for (interlace_type = PNG_INTERLACE_NONE;
  4980. interlace_type < INTERLACE_LAST; ++interlace_type)
  4981. {
  4982. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  4983. 0/*palette*/, interlace_type, 0, 0, 0), do_read_interlace,
  4984. pm->use_update_info);
  4985. if (fail(pm))
  4986. return 0;
  4987. }
  4988. }
  4989. return 1; /* keep going */
  4990. }
  4991. static void
  4992. perform_standard_test(png_modifier *pm)
  4993. {
  4994. /* Test each colour type over the valid range of bit depths (expressed as
  4995. * log2(bit_depth) in turn, stop as soon as any error is detected.
  4996. */
  4997. if (!test_standard(pm, 0, 0, READ_BDHI))
  4998. return;
  4999. if (!test_standard(pm, 2, 3, READ_BDHI))
  5000. return;
  5001. if (!test_standard(pm, 3, 0, 3))
  5002. return;
  5003. if (!test_standard(pm, 4, 3, READ_BDHI))
  5004. return;
  5005. if (!test_standard(pm, 6, 3, READ_BDHI))
  5006. return;
  5007. }
  5008. /********************************** SIZE TESTS ********************************/
  5009. static int
  5010. test_size(png_modifier* const pm, png_byte const colour_type,
  5011. int bdlo, int const bdhi)
  5012. {
  5013. /* Run the tests on each combination.
  5014. *
  5015. * NOTE: on my 32 bit x86 each of the following blocks takes
  5016. * a total of 3.5 seconds if done across every combo of bit depth
  5017. * width and height. This is a waste of time in practice, hence the
  5018. * hinc and winc stuff:
  5019. */
  5020. static const png_byte hinc[] = {1, 3, 11, 1, 5};
  5021. static const png_byte winc[] = {1, 9, 5, 7, 1};
  5022. int save_bdlo = bdlo;
  5023. for (; bdlo <= bdhi; ++bdlo)
  5024. {
  5025. png_uint_32 h, w;
  5026. for (h=1; h<=16; h+=hinc[bdlo])
  5027. {
  5028. for (w=1; w<=16; w+=winc[bdlo])
  5029. {
  5030. /* First test all the 'size' images against the sequential
  5031. * reader using libpng to deinterlace (where required.) This
  5032. * validates the write side of libpng. There are four possibilities
  5033. * to validate.
  5034. */
  5035. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  5036. 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
  5037. pm->use_update_info);
  5038. if (fail(pm))
  5039. return 0;
  5040. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  5041. 0/*palette*/, PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
  5042. pm->use_update_info);
  5043. if (fail(pm))
  5044. return 0;
  5045. /* Now validate the interlaced read side - do_interlace true,
  5046. * in the progressive case this does actually make a difference
  5047. * to the code used in the non-interlaced case too.
  5048. */
  5049. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  5050. 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
  5051. pm->use_update_info);
  5052. if (fail(pm))
  5053. return 0;
  5054. # if CAN_WRITE_INTERLACE
  5055. /* Validate the pngvalid code itself: */
  5056. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  5057. 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
  5058. pm->use_update_info);
  5059. if (fail(pm))
  5060. return 0;
  5061. # endif
  5062. }
  5063. }
  5064. }
  5065. /* Now do the tests of libpng interlace handling, after we have made sure
  5066. * that the pngvalid version works:
  5067. */
  5068. for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
  5069. {
  5070. png_uint_32 h, w;
  5071. for (h=1; h<=16; h+=hinc[bdlo])
  5072. {
  5073. for (w=1; w<=16; w+=winc[bdlo])
  5074. {
  5075. # ifdef PNG_READ_INTERLACING_SUPPORTED
  5076. /* Test with pngvalid generated interlaced images first; we have
  5077. * already verify these are ok (unless pngvalid has self-consistent
  5078. * read/write errors, which is unlikely), so this detects errors in
  5079. * the read side first:
  5080. */
  5081. # if CAN_WRITE_INTERLACE
  5082. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  5083. 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
  5084. pm->use_update_info);
  5085. if (fail(pm))
  5086. return 0;
  5087. # endif
  5088. # endif /* READ_INTERLACING */
  5089. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  5090. /* Test the libpng write side against the pngvalid read side: */
  5091. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  5092. 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
  5093. pm->use_update_info);
  5094. if (fail(pm))
  5095. return 0;
  5096. # endif
  5097. # ifdef PNG_READ_INTERLACING_SUPPORTED
  5098. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  5099. /* Test both together: */
  5100. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo),
  5101. 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
  5102. pm->use_update_info);
  5103. if (fail(pm))
  5104. return 0;
  5105. # endif
  5106. # endif /* READ_INTERLACING */
  5107. }
  5108. }
  5109. }
  5110. return 1; /* keep going */
  5111. }
  5112. static void
  5113. perform_size_test(png_modifier *pm)
  5114. {
  5115. /* Test each colour type over the valid range of bit depths (expressed as
  5116. * log2(bit_depth) in turn, stop as soon as any error is detected.
  5117. */
  5118. if (!test_size(pm, 0, 0, READ_BDHI))
  5119. return;
  5120. if (!test_size(pm, 2, 3, READ_BDHI))
  5121. return;
  5122. /* For the moment don't do the palette test - it's a waste of time when
  5123. * compared to the grayscale test.
  5124. */
  5125. #if 0
  5126. if (!test_size(pm, 3, 0, 3))
  5127. return;
  5128. #endif
  5129. if (!test_size(pm, 4, 3, READ_BDHI))
  5130. return;
  5131. if (!test_size(pm, 6, 3, READ_BDHI))
  5132. return;
  5133. }
  5134. /******************************* TRANSFORM TESTS ******************************/
  5135. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  5136. /* A set of tests to validate libpng image transforms. The possibilities here
  5137. * are legion because the transforms can be combined in a combinatorial
  5138. * fashion. To deal with this some measure of restraint is required, otherwise
  5139. * the tests would take forever.
  5140. */
  5141. typedef struct image_pixel
  5142. {
  5143. /* A local (pngvalid) representation of a PNG pixel, in all its
  5144. * various forms.
  5145. */
  5146. unsigned int red, green, blue, alpha; /* For non-palette images. */
  5147. unsigned int palette_index; /* For a palette image. */
  5148. png_byte colour_type; /* As in the spec. */
  5149. png_byte bit_depth; /* Defines bit size in row */
  5150. png_byte sample_depth; /* Scale of samples */
  5151. unsigned int have_tRNS :1; /* tRNS chunk may need processing */
  5152. unsigned int swap_rgb :1; /* RGB swapped to BGR */
  5153. unsigned int alpha_first :1; /* Alpha at start, not end */
  5154. unsigned int alpha_inverted :1; /* Alpha channel inverted */
  5155. unsigned int mono_inverted :1; /* Gray channel inverted */
  5156. unsigned int swap16 :1; /* Byte swap 16-bit components */
  5157. unsigned int littleendian :1; /* High bits on right */
  5158. unsigned int sig_bits :1; /* Pixel shifted (sig bits only) */
  5159. /* For checking the code calculates double precision floating point values
  5160. * along with an error value, accumulated from the transforms. Because an
  5161. * sBIT setting allows larger error bounds (indeed, by the spec, apparently
  5162. * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
  5163. * channel is stored. This sBIT value is folded in to the stored error value
  5164. * at the end of the application of the transforms to the pixel.
  5165. *
  5166. * If sig_bits is set above the red, green, blue and alpha values have been
  5167. * scaled so they only contain the significant bits of the component values.
  5168. */
  5169. double redf, greenf, bluef, alphaf;
  5170. double rede, greene, bluee, alphae;
  5171. png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
  5172. } image_pixel;
  5173. /* Shared utility function, see below. */
  5174. static void
  5175. image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
  5176. unsigned int bMax, unsigned int aMax)
  5177. {
  5178. this->redf = this->red / (double)rMax;
  5179. this->greenf = this->green / (double)gMax;
  5180. this->bluef = this->blue / (double)bMax;
  5181. this->alphaf = this->alpha / (double)aMax;
  5182. if (this->red < rMax)
  5183. this->rede = this->redf * DBL_EPSILON;
  5184. else
  5185. this->rede = 0;
  5186. if (this->green < gMax)
  5187. this->greene = this->greenf * DBL_EPSILON;
  5188. else
  5189. this->greene = 0;
  5190. if (this->blue < bMax)
  5191. this->bluee = this->bluef * DBL_EPSILON;
  5192. else
  5193. this->bluee = 0;
  5194. if (this->alpha < aMax)
  5195. this->alphae = this->alphaf * DBL_EPSILON;
  5196. else
  5197. this->alphae = 0;
  5198. }
  5199. /* Initialize the structure for the next pixel - call this before doing any
  5200. * transforms and call it for each pixel since all the fields may need to be
  5201. * reset.
  5202. */
  5203. static void
  5204. image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
  5205. png_byte bit_depth, png_uint_32 x, store_palette palette,
  5206. const image_pixel *format /*from pngvalid transform of input*/)
  5207. {
  5208. png_byte sample_depth =
  5209. (png_byte)(colour_type == PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
  5210. unsigned int max = (1U<<sample_depth)-1;
  5211. int swap16 = (format != 0 && format->swap16);
  5212. int littleendian = (format != 0 && format->littleendian);
  5213. int sig_bits = (format != 0 && format->sig_bits);
  5214. /* Initially just set everything to the same number and the alpha to opaque.
  5215. * Note that this currently assumes a simple palette where entry x has colour
  5216. * rgb(x,x,x)!
  5217. */
  5218. this->palette_index = this->red = this->green = this->blue =
  5219. sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
  5220. this->alpha = max;
  5221. this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
  5222. sample_depth;
  5223. /* Then override as appropriate: */
  5224. if (colour_type == 3) /* palette */
  5225. {
  5226. /* This permits the caller to default to the sample value. */
  5227. if (palette != 0)
  5228. {
  5229. unsigned int i = this->palette_index;
  5230. this->red = palette[i].red;
  5231. this->green = palette[i].green;
  5232. this->blue = palette[i].blue;
  5233. this->alpha = palette[i].alpha;
  5234. }
  5235. }
  5236. else /* not palette */
  5237. {
  5238. unsigned int i = 0;
  5239. if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
  5240. {
  5241. this->alpha = this->red;
  5242. /* This handles the gray case for 'AG' pixels */
  5243. this->palette_index = this->red = this->green = this->blue =
  5244. sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
  5245. i = 1;
  5246. }
  5247. if (colour_type & 2)
  5248. {
  5249. /* Green is second for both BGR and RGB: */
  5250. this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5251. littleendian);
  5252. if (format != 0 && format->swap_rgb) /* BGR */
  5253. this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5254. littleendian);
  5255. else
  5256. this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5257. littleendian);
  5258. }
  5259. else /* grayscale */ if (format != 0 && format->mono_inverted)
  5260. this->red = this->green = this->blue = this->red ^ max;
  5261. if ((colour_type & 4) != 0) /* alpha */
  5262. {
  5263. if (format == 0 || !format->alpha_first)
  5264. this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5265. littleendian);
  5266. if (format != 0 && format->alpha_inverted)
  5267. this->alpha ^= max;
  5268. }
  5269. }
  5270. /* Calculate the scaled values, these are simply the values divided by
  5271. * 'max' and the error is initialized to the double precision epsilon value
  5272. * from the header file.
  5273. */
  5274. image_pixel_setf(this,
  5275. sig_bits ? (1U << format->red_sBIT)-1 : max,
  5276. sig_bits ? (1U << format->green_sBIT)-1 : max,
  5277. sig_bits ? (1U << format->blue_sBIT)-1 : max,
  5278. sig_bits ? (1U << format->alpha_sBIT)-1 : max);
  5279. /* Store the input information for use in the transforms - these will
  5280. * modify the information.
  5281. */
  5282. this->colour_type = colour_type;
  5283. this->bit_depth = bit_depth;
  5284. this->sample_depth = sample_depth;
  5285. this->have_tRNS = 0;
  5286. this->swap_rgb = 0;
  5287. this->alpha_first = 0;
  5288. this->alpha_inverted = 0;
  5289. this->mono_inverted = 0;
  5290. this->swap16 = 0;
  5291. this->littleendian = 0;
  5292. this->sig_bits = 0;
  5293. }
  5294. #if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\
  5295. || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\
  5296. || defined PNG_READ_BACKGROUND_SUPPORTED
  5297. /* Convert a palette image to an rgb image. This necessarily converts the tRNS
  5298. * chunk at the same time, because the tRNS will be in palette form. The way
  5299. * palette validation works means that the original palette is never updated,
  5300. * instead the image_pixel value from the row contains the RGB of the
  5301. * corresponding palette entry and *this* is updated. Consequently this routine
  5302. * only needs to change the colour type information.
  5303. */
  5304. static void
  5305. image_pixel_convert_PLTE(image_pixel *this)
  5306. {
  5307. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  5308. {
  5309. if (this->have_tRNS)
  5310. {
  5311. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  5312. this->have_tRNS = 0;
  5313. }
  5314. else
  5315. this->colour_type = PNG_COLOR_TYPE_RGB;
  5316. /* The bit depth of the row changes at this point too (notice that this is
  5317. * the row format, not the sample depth, which is separate.)
  5318. */
  5319. this->bit_depth = 8;
  5320. }
  5321. }
  5322. /* Add an alpha channel; this will import the tRNS information because tRNS is
  5323. * not valid in an alpha image. The bit depth will invariably be set to at
  5324. * least 8 prior to 1.7.0. Palette images will be converted to alpha (using
  5325. * the above API). With png_set_background the alpha channel is never expanded
  5326. * but this routine is used by pngvalid to simplify code; 'for_background'
  5327. * records this.
  5328. */
  5329. static void
  5330. image_pixel_add_alpha(image_pixel *this, const standard_display *display,
  5331. int for_background)
  5332. {
  5333. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  5334. image_pixel_convert_PLTE(this);
  5335. if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
  5336. {
  5337. if (this->colour_type == PNG_COLOR_TYPE_GRAY)
  5338. {
  5339. # if PNG_LIBPNG_VER != 10700
  5340. if (!for_background && this->bit_depth < 8)
  5341. this->bit_depth = this->sample_depth = 8;
  5342. # endif
  5343. if (this->have_tRNS)
  5344. {
  5345. /* After 1.7 the expansion of bit depth only happens if there is a
  5346. * tRNS chunk to expand at this point.
  5347. */
  5348. # if PNG_LIBPNG_VER == 10700
  5349. if (!for_background && this->bit_depth < 8)
  5350. this->bit_depth = this->sample_depth = 8;
  5351. # endif
  5352. this->have_tRNS = 0;
  5353. /* Check the input, original, channel value here against the
  5354. * original tRNS gray chunk valie.
  5355. */
  5356. if (this->red == display->transparent.red)
  5357. this->alphaf = 0;
  5358. else
  5359. this->alphaf = 1;
  5360. }
  5361. else
  5362. this->alphaf = 1;
  5363. this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  5364. }
  5365. else if (this->colour_type == PNG_COLOR_TYPE_RGB)
  5366. {
  5367. if (this->have_tRNS)
  5368. {
  5369. this->have_tRNS = 0;
  5370. /* Again, check the exact input values, not the current transformed
  5371. * value!
  5372. */
  5373. if (this->red == display->transparent.red &&
  5374. this->green == display->transparent.green &&
  5375. this->blue == display->transparent.blue)
  5376. this->alphaf = 0;
  5377. else
  5378. this->alphaf = 1;
  5379. }
  5380. else
  5381. this->alphaf = 1;
  5382. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  5383. }
  5384. /* The error in the alpha is zero and the sBIT value comes from the
  5385. * original sBIT data (actually it will always be the original bit depth).
  5386. */
  5387. this->alphae = 0;
  5388. this->alpha_sBIT = display->alpha_sBIT;
  5389. }
  5390. }
  5391. #endif /* transforms that need image_pixel_add_alpha */
  5392. struct transform_display;
  5393. typedef struct image_transform
  5394. {
  5395. /* The name of this transform: a string. */
  5396. const char *name;
  5397. /* Each transform can be disabled from the command line: */
  5398. int enable;
  5399. /* The global list of transforms; read only. */
  5400. struct image_transform *const list;
  5401. /* The global count of the number of times this transform has been set on an
  5402. * image.
  5403. */
  5404. unsigned int global_use;
  5405. /* The local count of the number of times this transform has been set. */
  5406. unsigned int local_use;
  5407. /* The next transform in the list, each transform must call its own next
  5408. * transform after it has processed the pixel successfully.
  5409. */
  5410. const struct image_transform *next;
  5411. /* A single transform for the image, expressed as a series of function
  5412. * callbacks and some space for values.
  5413. *
  5414. * First a callback to add any required modifications to the png_modifier;
  5415. * this gets called just before the modifier is set up for read.
  5416. */
  5417. void (*ini)(const struct image_transform *this,
  5418. struct transform_display *that);
  5419. /* And a callback to set the transform on the current png_read_struct:
  5420. */
  5421. void (*set)(const struct image_transform *this,
  5422. struct transform_display *that, png_structp pp, png_infop pi);
  5423. /* Then a transform that takes an input pixel in one PNG format or another
  5424. * and modifies it by a pngvalid implementation of the transform (thus
  5425. * duplicating the libpng intent without, we hope, duplicating the bugs
  5426. * in the libpng implementation!) The png_structp is solely to allow error
  5427. * reporting via png_error and png_warning.
  5428. */
  5429. void (*mod)(const struct image_transform *this, image_pixel *that,
  5430. png_const_structp pp, const struct transform_display *display);
  5431. /* Add this transform to the list and return true if the transform is
  5432. * meaningful for this colour type and bit depth - if false then the
  5433. * transform should have no effect on the image so there's not a lot of
  5434. * point running it.
  5435. */
  5436. int (*add)(struct image_transform *this,
  5437. const struct image_transform **that, png_byte colour_type,
  5438. png_byte bit_depth);
  5439. } image_transform;
  5440. typedef struct transform_display
  5441. {
  5442. standard_display this;
  5443. /* Parameters */
  5444. png_modifier* pm;
  5445. const image_transform* transform_list;
  5446. unsigned int max_gamma_8;
  5447. /* Local variables */
  5448. png_byte output_colour_type;
  5449. png_byte output_bit_depth;
  5450. png_byte unpacked;
  5451. /* Modifications (not necessarily used.) */
  5452. gama_modification gama_mod;
  5453. chrm_modification chrm_mod;
  5454. srgb_modification srgb_mod;
  5455. } transform_display;
  5456. /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
  5457. static void
  5458. transform_set_encoding(transform_display *this)
  5459. {
  5460. /* Set up the png_modifier '_current' fields then use these to determine how
  5461. * to add appropriate chunks.
  5462. */
  5463. png_modifier *pm = this->pm;
  5464. modifier_set_encoding(pm);
  5465. if (modifier_color_encoding_is_set(pm))
  5466. {
  5467. if (modifier_color_encoding_is_sRGB(pm))
  5468. srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
  5469. else
  5470. {
  5471. /* Set gAMA and cHRM separately. */
  5472. gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
  5473. if (pm->current_encoding != 0)
  5474. chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
  5475. }
  5476. }
  5477. }
  5478. /* Three functions to end the list: */
  5479. static void
  5480. image_transform_ini_end(const image_transform *this,
  5481. transform_display *that)
  5482. {
  5483. UNUSED(this)
  5484. UNUSED(that)
  5485. }
  5486. static void
  5487. image_transform_set_end(const image_transform *this,
  5488. transform_display *that, png_structp pp, png_infop pi)
  5489. {
  5490. UNUSED(this)
  5491. UNUSED(that)
  5492. UNUSED(pp)
  5493. UNUSED(pi)
  5494. }
  5495. /* At the end of the list recalculate the output image pixel value from the
  5496. * double precision values set up by the preceding 'mod' calls:
  5497. */
  5498. static unsigned int
  5499. sample_scale(double sample_value, unsigned int scale)
  5500. {
  5501. sample_value = floor(sample_value * scale + .5);
  5502. /* Return NaN as 0: */
  5503. if (!(sample_value > 0))
  5504. sample_value = 0;
  5505. else if (sample_value > scale)
  5506. sample_value = scale;
  5507. return (unsigned int)sample_value;
  5508. }
  5509. static void
  5510. image_transform_mod_end(const image_transform *this, image_pixel *that,
  5511. png_const_structp pp, const transform_display *display)
  5512. {
  5513. unsigned int scale = (1U<<that->sample_depth)-1;
  5514. int sig_bits = that->sig_bits;
  5515. UNUSED(this)
  5516. UNUSED(pp)
  5517. UNUSED(display)
  5518. /* At the end recalculate the digitized red green and blue values according
  5519. * to the current sample_depth of the pixel.
  5520. *
  5521. * The sample value is simply scaled to the maximum, checking for over
  5522. * and underflow (which can both happen for some image transforms,
  5523. * including simple size scaling, though libpng doesn't do that at present.
  5524. */
  5525. that->red = sample_scale(that->redf, scale);
  5526. /* This is a bit bogus; really the above calculation should use the red_sBIT
  5527. * value, not sample_depth, but because libpng does png_set_shift by just
  5528. * shifting the bits we get errors if we don't do it the same way.
  5529. */
  5530. if (sig_bits && that->red_sBIT < that->sample_depth)
  5531. that->red >>= that->sample_depth - that->red_sBIT;
  5532. /* The error value is increased, at the end, according to the lowest sBIT
  5533. * value seen. Common sense tells us that the intermediate integer
  5534. * representations are no more accurate than +/- 0.5 in the integral values,
  5535. * the sBIT allows the implementation to be worse than this. In addition the
  5536. * PNG specification actually permits any error within the range (-1..+1),
  5537. * but that is ignored here. Instead the final digitized value is compared,
  5538. * below to the digitized value of the error limits - this has the net effect
  5539. * of allowing (almost) +/-1 in the output value. It's difficult to see how
  5540. * any algorithm that digitizes intermediate results can be more accurate.
  5541. */
  5542. that->rede += 1./(2*((1U<<that->red_sBIT)-1));
  5543. if (that->colour_type & PNG_COLOR_MASK_COLOR)
  5544. {
  5545. that->green = sample_scale(that->greenf, scale);
  5546. if (sig_bits && that->green_sBIT < that->sample_depth)
  5547. that->green >>= that->sample_depth - that->green_sBIT;
  5548. that->blue = sample_scale(that->bluef, scale);
  5549. if (sig_bits && that->blue_sBIT < that->sample_depth)
  5550. that->blue >>= that->sample_depth - that->blue_sBIT;
  5551. that->greene += 1./(2*((1U<<that->green_sBIT)-1));
  5552. that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
  5553. }
  5554. else
  5555. {
  5556. that->blue = that->green = that->red;
  5557. that->bluef = that->greenf = that->redf;
  5558. that->bluee = that->greene = that->rede;
  5559. }
  5560. if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
  5561. that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5562. {
  5563. that->alpha = sample_scale(that->alphaf, scale);
  5564. that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
  5565. }
  5566. else
  5567. {
  5568. that->alpha = scale; /* opaque */
  5569. that->alphaf = 1; /* Override this. */
  5570. that->alphae = 0; /* It's exact ;-) */
  5571. }
  5572. if (sig_bits && that->alpha_sBIT < that->sample_depth)
  5573. that->alpha >>= that->sample_depth - that->alpha_sBIT;
  5574. }
  5575. /* Static 'end' structure: */
  5576. static image_transform image_transform_end =
  5577. {
  5578. "(end)", /* name */
  5579. 1, /* enable */
  5580. 0, /* list */
  5581. 0, /* global_use */
  5582. 0, /* local_use */
  5583. 0, /* next */
  5584. image_transform_ini_end,
  5585. image_transform_set_end,
  5586. image_transform_mod_end,
  5587. 0 /* never called, I want it to crash if it is! */
  5588. };
  5589. /* Reader callbacks and implementations, where they differ from the standard
  5590. * ones.
  5591. */
  5592. static void
  5593. transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
  5594. const image_transform *transform_list)
  5595. {
  5596. memset(dp, 0, sizeof *dp);
  5597. /* Standard fields */
  5598. standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
  5599. pm->use_update_info);
  5600. /* Parameter fields */
  5601. dp->pm = pm;
  5602. dp->transform_list = transform_list;
  5603. dp->max_gamma_8 = 16;
  5604. /* Local variable fields */
  5605. dp->output_colour_type = 255; /* invalid */
  5606. dp->output_bit_depth = 255; /* invalid */
  5607. dp->unpacked = 0; /* not unpacked */
  5608. }
  5609. static void
  5610. transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
  5611. {
  5612. /* Reuse the standard stuff as appropriate. */
  5613. standard_info_part1(&dp->this, pp, pi);
  5614. /* Now set the list of transforms. */
  5615. dp->transform_list->set(dp->transform_list, dp, pp, pi);
  5616. /* Update the info structure for these transforms: */
  5617. {
  5618. int i = dp->this.use_update_info;
  5619. /* Always do one call, even if use_update_info is 0. */
  5620. do
  5621. png_read_update_info(pp, pi);
  5622. while (--i > 0);
  5623. }
  5624. /* And get the output information into the standard_display */
  5625. standard_info_part2(&dp->this, pp, pi, 1/*images*/);
  5626. /* Plus the extra stuff we need for the transform tests: */
  5627. dp->output_colour_type = png_get_color_type(pp, pi);
  5628. dp->output_bit_depth = png_get_bit_depth(pp, pi);
  5629. /* If png_set_filler is in action then fake the output color type to include
  5630. * an alpha channel where appropriate.
  5631. */
  5632. if (dp->output_bit_depth >= 8 &&
  5633. (dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
  5634. dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
  5635. dp->output_colour_type |= 4;
  5636. /* Validate the combination of colour type and bit depth that we are getting
  5637. * out of libpng; the semantics of something not in the PNG spec are, at
  5638. * best, unclear.
  5639. */
  5640. switch (dp->output_colour_type)
  5641. {
  5642. case PNG_COLOR_TYPE_PALETTE:
  5643. if (dp->output_bit_depth > 8) goto error;
  5644. /* FALLTHROUGH */
  5645. case PNG_COLOR_TYPE_GRAY:
  5646. if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
  5647. dp->output_bit_depth == 4)
  5648. break;
  5649. /* FALLTHROUGH */
  5650. default:
  5651. if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
  5652. break;
  5653. /* FALLTHROUGH */
  5654. error:
  5655. {
  5656. char message[128];
  5657. size_t pos;
  5658. pos = safecat(message, sizeof message, 0,
  5659. "invalid final bit depth: colour type(");
  5660. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  5661. pos = safecat(message, sizeof message, pos, ") with bit depth: ");
  5662. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5663. png_error(pp, message);
  5664. }
  5665. }
  5666. /* Use a test pixel to check that the output agrees with what we expect -
  5667. * this avoids running the whole test if the output is unexpected. This also
  5668. * checks for internal errors.
  5669. */
  5670. {
  5671. image_pixel test_pixel;
  5672. memset(&test_pixel, 0, sizeof test_pixel);
  5673. test_pixel.colour_type = dp->this.colour_type; /* input */
  5674. test_pixel.bit_depth = dp->this.bit_depth;
  5675. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
  5676. test_pixel.sample_depth = 8;
  5677. else
  5678. test_pixel.sample_depth = test_pixel.bit_depth;
  5679. /* Don't need sBIT here, but it must be set to non-zero to avoid
  5680. * arithmetic overflows.
  5681. */
  5682. test_pixel.have_tRNS = dp->this.is_transparent != 0;
  5683. test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
  5684. test_pixel.alpha_sBIT = test_pixel.sample_depth;
  5685. dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
  5686. if (test_pixel.colour_type != dp->output_colour_type)
  5687. {
  5688. char message[128];
  5689. size_t pos = safecat(message, sizeof message, 0, "colour type ");
  5690. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  5691. pos = safecat(message, sizeof message, pos, " expected ");
  5692. pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
  5693. png_error(pp, message);
  5694. }
  5695. if (test_pixel.bit_depth != dp->output_bit_depth)
  5696. {
  5697. char message[128];
  5698. size_t pos = safecat(message, sizeof message, 0, "bit depth ");
  5699. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5700. pos = safecat(message, sizeof message, pos, " expected ");
  5701. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5702. png_error(pp, message);
  5703. }
  5704. /* If both bit depth and colour type are correct check the sample depth.
  5705. */
  5706. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
  5707. test_pixel.sample_depth != 8) /* oops - internal error! */
  5708. png_error(pp, "pngvalid: internal: palette sample depth not 8");
  5709. else if (dp->unpacked && test_pixel.bit_depth != 8)
  5710. png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
  5711. else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
  5712. && test_pixel.bit_depth != test_pixel.sample_depth)
  5713. {
  5714. char message[128];
  5715. size_t pos = safecat(message, sizeof message, 0,
  5716. "internal: sample depth ");
  5717. /* Because unless something has set 'unpacked' or the image is palette
  5718. * mapped we expect the transform to keep sample depth and bit depth
  5719. * the same.
  5720. */
  5721. pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
  5722. pos = safecat(message, sizeof message, pos, " expected ");
  5723. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5724. png_error(pp, message);
  5725. }
  5726. else if (test_pixel.bit_depth != dp->output_bit_depth)
  5727. {
  5728. /* This could be a libpng error too; libpng has not produced what we
  5729. * expect for the output bit depth.
  5730. */
  5731. char message[128];
  5732. size_t pos = safecat(message, sizeof message, 0,
  5733. "internal: bit depth ");
  5734. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5735. pos = safecat(message, sizeof message, pos, " expected ");
  5736. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5737. png_error(pp, message);
  5738. }
  5739. }
  5740. }
  5741. static void PNGCBAPI
  5742. transform_info(png_structp pp, png_infop pi)
  5743. {
  5744. transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
  5745. pp, pi);
  5746. }
  5747. static void
  5748. transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
  5749. unsigned int b, unsigned int a, unsigned int in_digitized, double in,
  5750. unsigned int out, png_byte sample_depth, double err, double limit,
  5751. const char *name, double digitization_error)
  5752. {
  5753. /* Compare the scaled, digitized, values of our local calculation (in+-err)
  5754. * with the digitized values libpng produced; 'sample_depth' is the actual
  5755. * digitization depth of the libpng output colors (the bit depth except for
  5756. * palette images where it is always 8.) The check on 'err' is to detect
  5757. * internal errors in pngvalid itself.
  5758. */
  5759. unsigned int max = (1U<<sample_depth)-1;
  5760. double in_min = ceil((in-err)*max - digitization_error);
  5761. double in_max = floor((in+err)*max + digitization_error);
  5762. if (debugonly(err > limit ||) !(out >= in_min && out <= in_max))
  5763. {
  5764. char message[256];
  5765. size_t pos;
  5766. pos = safecat(message, sizeof message, 0, name);
  5767. pos = safecat(message, sizeof message, pos, " output value error: rgba(");
  5768. pos = safecatn(message, sizeof message, pos, r);
  5769. pos = safecat(message, sizeof message, pos, ",");
  5770. pos = safecatn(message, sizeof message, pos, g);
  5771. pos = safecat(message, sizeof message, pos, ",");
  5772. pos = safecatn(message, sizeof message, pos, b);
  5773. pos = safecat(message, sizeof message, pos, ",");
  5774. pos = safecatn(message, sizeof message, pos, a);
  5775. pos = safecat(message, sizeof message, pos, "): ");
  5776. pos = safecatn(message, sizeof message, pos, out);
  5777. pos = safecat(message, sizeof message, pos, " expected: ");
  5778. pos = safecatn(message, sizeof message, pos, in_digitized);
  5779. pos = safecat(message, sizeof message, pos, " (");
  5780. pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
  5781. pos = safecat(message, sizeof message, pos, "..");
  5782. pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
  5783. pos = safecat(message, sizeof message, pos, ")");
  5784. png_error(pp, message);
  5785. }
  5786. UNUSED(limit)
  5787. }
  5788. static void
  5789. transform_image_validate(transform_display *dp, png_const_structp pp,
  5790. png_infop pi)
  5791. {
  5792. /* Constants for the loop below: */
  5793. const png_store* const ps = dp->this.ps;
  5794. png_byte in_ct = dp->this.colour_type;
  5795. png_byte in_bd = dp->this.bit_depth;
  5796. png_uint_32 w = dp->this.w;
  5797. png_uint_32 h = dp->this.h;
  5798. png_byte out_ct = dp->output_colour_type;
  5799. png_byte out_bd = dp->output_bit_depth;
  5800. png_byte sample_depth =
  5801. (png_byte)(out_ct == PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
  5802. png_byte red_sBIT = dp->this.red_sBIT;
  5803. png_byte green_sBIT = dp->this.green_sBIT;
  5804. png_byte blue_sBIT = dp->this.blue_sBIT;
  5805. png_byte alpha_sBIT = dp->this.alpha_sBIT;
  5806. int have_tRNS = dp->this.is_transparent;
  5807. double digitization_error;
  5808. store_palette out_palette;
  5809. png_uint_32 y;
  5810. UNUSED(pi)
  5811. /* Check for row overwrite errors */
  5812. store_image_check(dp->this.ps, pp, 0);
  5813. /* Read the palette corresponding to the output if the output colour type
  5814. * indicates a palette, otherwise set out_palette to garbage.
  5815. */
  5816. if (out_ct == PNG_COLOR_TYPE_PALETTE)
  5817. {
  5818. /* Validate that the palette count itself has not changed - this is not
  5819. * expected.
  5820. */
  5821. int npalette = (-1);
  5822. (void)read_palette(out_palette, &npalette, pp, pi);
  5823. if (npalette != dp->this.npalette)
  5824. png_error(pp, "unexpected change in palette size");
  5825. digitization_error = .5;
  5826. }
  5827. else
  5828. {
  5829. png_byte in_sample_depth;
  5830. memset(out_palette, 0x5e, sizeof out_palette);
  5831. /* use-input-precision means assume that if the input has 8 bit (or less)
  5832. * samples and the output has 16 bit samples the calculations will be done
  5833. * with 8 bit precision, not 16.
  5834. */
  5835. if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
  5836. in_sample_depth = 8;
  5837. else
  5838. in_sample_depth = in_bd;
  5839. if (sample_depth != 16 || in_sample_depth > 8 ||
  5840. !dp->pm->calculations_use_input_precision)
  5841. digitization_error = .5;
  5842. /* Else calculations are at 8 bit precision, and the output actually
  5843. * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
  5844. */
  5845. else
  5846. digitization_error = .5 * 257;
  5847. }
  5848. for (y=0; y<h; ++y)
  5849. {
  5850. png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
  5851. png_uint_32 x;
  5852. /* The original, standard, row pre-transforms. */
  5853. png_byte std[STANDARD_ROWMAX];
  5854. transform_row(pp, std, in_ct, in_bd, y);
  5855. /* Go through each original pixel transforming it and comparing with what
  5856. * libpng did to the same pixel.
  5857. */
  5858. for (x=0; x<w; ++x)
  5859. {
  5860. image_pixel in_pixel, out_pixel;
  5861. unsigned int r, g, b, a;
  5862. /* Find out what we think the pixel should be: */
  5863. image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
  5864. NULL);
  5865. in_pixel.red_sBIT = red_sBIT;
  5866. in_pixel.green_sBIT = green_sBIT;
  5867. in_pixel.blue_sBIT = blue_sBIT;
  5868. in_pixel.alpha_sBIT = alpha_sBIT;
  5869. in_pixel.have_tRNS = have_tRNS != 0;
  5870. /* For error detection, below. */
  5871. r = in_pixel.red;
  5872. g = in_pixel.green;
  5873. b = in_pixel.blue;
  5874. a = in_pixel.alpha;
  5875. /* This applies the transforms to the input data, including output
  5876. * format operations which must be used when reading the output
  5877. * pixel that libpng produces.
  5878. */
  5879. dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
  5880. /* Read the output pixel and compare it to what we got, we don't
  5881. * use the error field here, so no need to update sBIT. in_pixel
  5882. * says whether we expect libpng to change the output format.
  5883. */
  5884. image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
  5885. &in_pixel);
  5886. /* We don't expect changes to the index here even if the bit depth is
  5887. * changed.
  5888. */
  5889. if (in_ct == PNG_COLOR_TYPE_PALETTE &&
  5890. out_ct == PNG_COLOR_TYPE_PALETTE)
  5891. {
  5892. if (in_pixel.palette_index != out_pixel.palette_index)
  5893. png_error(pp, "unexpected transformed palette index");
  5894. }
  5895. /* Check the colours for palette images too - in fact the palette could
  5896. * be separately verified itself in most cases.
  5897. */
  5898. if (in_pixel.red != out_pixel.red)
  5899. transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
  5900. out_pixel.red, sample_depth, in_pixel.rede,
  5901. dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
  5902. digitization_error);
  5903. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5904. in_pixel.green != out_pixel.green)
  5905. transform_range_check(pp, r, g, b, a, in_pixel.green,
  5906. in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
  5907. dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
  5908. digitization_error);
  5909. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5910. in_pixel.blue != out_pixel.blue)
  5911. transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
  5912. out_pixel.blue, sample_depth, in_pixel.bluee,
  5913. dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
  5914. digitization_error);
  5915. if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
  5916. in_pixel.alpha != out_pixel.alpha)
  5917. transform_range_check(pp, r, g, b, a, in_pixel.alpha,
  5918. in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
  5919. dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
  5920. digitization_error);
  5921. } /* pixel (x) loop */
  5922. } /* row (y) loop */
  5923. /* Record that something was actually checked to avoid a false positive. */
  5924. dp->this.ps->validated = 1;
  5925. }
  5926. static void PNGCBAPI
  5927. transform_end(png_structp ppIn, png_infop pi)
  5928. {
  5929. png_const_structp pp = ppIn;
  5930. transform_display *dp = voidcast(transform_display*,
  5931. png_get_progressive_ptr(pp));
  5932. if (!dp->this.speed)
  5933. transform_image_validate(dp, pp, pi);
  5934. else
  5935. dp->this.ps->validated = 1;
  5936. }
  5937. /* A single test run. */
  5938. static void
  5939. transform_test(png_modifier *pmIn, png_uint_32 idIn,
  5940. const image_transform* transform_listIn, const char * const name)
  5941. {
  5942. transform_display d;
  5943. context(&pmIn->this, fault);
  5944. transform_display_init(&d, pmIn, idIn, transform_listIn);
  5945. Try
  5946. {
  5947. size_t pos = 0;
  5948. png_structp pp;
  5949. png_infop pi;
  5950. char full_name[256];
  5951. /* Make sure the encoding fields are correct and enter the required
  5952. * modifications.
  5953. */
  5954. transform_set_encoding(&d);
  5955. /* Add any modifications required by the transform list. */
  5956. d.transform_list->ini(d.transform_list, &d);
  5957. /* Add the color space information, if any, to the name. */
  5958. pos = safecat(full_name, sizeof full_name, pos, name);
  5959. pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
  5960. /* Get a png_struct for reading the image. */
  5961. pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
  5962. standard_palette_init(&d.this);
  5963. # if 0
  5964. /* Logging (debugging only) */
  5965. {
  5966. char buffer[256];
  5967. (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
  5968. "running test");
  5969. fprintf(stderr, "%s\n", buffer);
  5970. }
  5971. # endif
  5972. /* Introduce the correct read function. */
  5973. if (d.pm->this.progressive)
  5974. {
  5975. /* Share the row function with the standard implementation. */
  5976. png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
  5977. transform_end);
  5978. /* Now feed data into the reader until we reach the end: */
  5979. modifier_progressive_read(d.pm, pp, pi);
  5980. }
  5981. else
  5982. {
  5983. /* modifier_read expects a png_modifier* */
  5984. png_set_read_fn(pp, d.pm, modifier_read);
  5985. /* Check the header values: */
  5986. png_read_info(pp, pi);
  5987. /* Process the 'info' requirements. Only one image is generated */
  5988. transform_info_imp(&d, pp, pi);
  5989. sequential_row(&d.this, pp, pi, -1, 0);
  5990. if (!d.this.speed)
  5991. transform_image_validate(&d, pp, pi);
  5992. else
  5993. d.this.ps->validated = 1;
  5994. }
  5995. modifier_reset(d.pm);
  5996. }
  5997. Catch(fault)
  5998. {
  5999. modifier_reset(voidcast(png_modifier*,(void*)fault));
  6000. }
  6001. }
  6002. /* The transforms: */
  6003. #define ITSTRUCT(name) image_transform_##name
  6004. #define ITDATA(name) image_transform_data_##name
  6005. #define image_transform_ini image_transform_default_ini
  6006. #define IT(name)\
  6007. static image_transform ITSTRUCT(name) =\
  6008. {\
  6009. #name,\
  6010. 1, /*enable*/\
  6011. &PT, /*list*/\
  6012. 0, /*global_use*/\
  6013. 0, /*local_use*/\
  6014. 0, /*next*/\
  6015. image_transform_ini,\
  6016. image_transform_png_set_##name##_set,\
  6017. image_transform_png_set_##name##_mod,\
  6018. image_transform_png_set_##name##_add\
  6019. }
  6020. #define PT ITSTRUCT(end) /* stores the previous transform */
  6021. /* To save code: */
  6022. extern void image_transform_default_ini(const image_transform *this,
  6023. transform_display *that); /* silence GCC warnings */
  6024. void /* private, but almost always needed */
  6025. image_transform_default_ini(const image_transform *this,
  6026. transform_display *that)
  6027. {
  6028. this->next->ini(this->next, that);
  6029. }
  6030. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  6031. static int
  6032. image_transform_default_add(image_transform *this,
  6033. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6034. {
  6035. UNUSED(colour_type)
  6036. UNUSED(bit_depth)
  6037. this->next = *that;
  6038. *that = this;
  6039. return 1;
  6040. }
  6041. #endif
  6042. #ifdef PNG_READ_EXPAND_SUPPORTED
  6043. /* png_set_palette_to_rgb */
  6044. static void
  6045. image_transform_png_set_palette_to_rgb_set(const image_transform *this,
  6046. transform_display *that, png_structp pp, png_infop pi)
  6047. {
  6048. png_set_palette_to_rgb(pp);
  6049. this->next->set(this->next, that, pp, pi);
  6050. }
  6051. static void
  6052. image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
  6053. image_pixel *that, png_const_structp pp,
  6054. const transform_display *display)
  6055. {
  6056. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6057. image_pixel_convert_PLTE(that);
  6058. this->next->mod(this->next, that, pp, display);
  6059. }
  6060. static int
  6061. image_transform_png_set_palette_to_rgb_add(image_transform *this,
  6062. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6063. {
  6064. UNUSED(bit_depth)
  6065. this->next = *that;
  6066. *that = this;
  6067. return colour_type == PNG_COLOR_TYPE_PALETTE;
  6068. }
  6069. IT(palette_to_rgb);
  6070. #undef PT
  6071. #define PT ITSTRUCT(palette_to_rgb)
  6072. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6073. #ifdef PNG_READ_EXPAND_SUPPORTED
  6074. /* png_set_tRNS_to_alpha */
  6075. static void
  6076. image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
  6077. transform_display *that, png_structp pp, png_infop pi)
  6078. {
  6079. png_set_tRNS_to_alpha(pp);
  6080. /* If there was a tRNS chunk that would get expanded and add an alpha
  6081. * channel is_transparent must be updated:
  6082. */
  6083. if (that->this.has_tRNS)
  6084. that->this.is_transparent = 1;
  6085. this->next->set(this->next, that, pp, pi);
  6086. }
  6087. static void
  6088. image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
  6089. image_pixel *that, png_const_structp pp,
  6090. const transform_display *display)
  6091. {
  6092. #if PNG_LIBPNG_VER != 10700
  6093. /* LIBPNG BUG: this always forces palette images to RGB. */
  6094. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6095. image_pixel_convert_PLTE(that);
  6096. #endif
  6097. /* This effectively does an 'expand' only if there is some transparency to
  6098. * convert to an alpha channel.
  6099. */
  6100. if (that->have_tRNS)
  6101. # if PNG_LIBPNG_VER == 10700
  6102. if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
  6103. (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
  6104. # endif
  6105. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6106. #if PNG_LIBPNG_VER != 10700
  6107. /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
  6108. else
  6109. {
  6110. if (that->bit_depth < 8)
  6111. that->bit_depth =8;
  6112. if (that->sample_depth < 8)
  6113. that->sample_depth = 8;
  6114. }
  6115. #endif
  6116. this->next->mod(this->next, that, pp, display);
  6117. }
  6118. static int
  6119. image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
  6120. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6121. {
  6122. UNUSED(bit_depth)
  6123. this->next = *that;
  6124. *that = this;
  6125. /* We don't know yet whether there will be a tRNS chunk, but we know that
  6126. * this transformation should do nothing if there already is an alpha
  6127. * channel. In addition, after the bug fix in 1.7.0, there is no longer
  6128. * any action on a palette image.
  6129. */
  6130. return
  6131. # if PNG_LIBPNG_VER == 10700
  6132. colour_type != PNG_COLOR_TYPE_PALETTE &&
  6133. # endif
  6134. (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  6135. }
  6136. IT(tRNS_to_alpha);
  6137. #undef PT
  6138. #define PT ITSTRUCT(tRNS_to_alpha)
  6139. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6140. #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
  6141. /* png_set_gray_to_rgb */
  6142. static void
  6143. image_transform_png_set_gray_to_rgb_set(const image_transform *this,
  6144. transform_display *that, png_structp pp, png_infop pi)
  6145. {
  6146. png_set_gray_to_rgb(pp);
  6147. /* NOTE: this doesn't result in tRNS expansion. */
  6148. this->next->set(this->next, that, pp, pi);
  6149. }
  6150. static void
  6151. image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
  6152. image_pixel *that, png_const_structp pp,
  6153. const transform_display *display)
  6154. {
  6155. /* NOTE: we can actually pend the tRNS processing at this point because we
  6156. * can correctly recognize the original pixel value even though we have
  6157. * mapped the one gray channel to the three RGB ones, but in fact libpng
  6158. * doesn't do this, so we don't either.
  6159. */
  6160. if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
  6161. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6162. /* Simply expand the bit depth and alter the colour type as required. */
  6163. if (that->colour_type == PNG_COLOR_TYPE_GRAY)
  6164. {
  6165. /* RGB images have a bit depth at least equal to '8' */
  6166. if (that->bit_depth < 8)
  6167. that->sample_depth = that->bit_depth = 8;
  6168. /* And just changing the colour type works here because the green and blue
  6169. * channels are being maintained in lock-step with the red/gray:
  6170. */
  6171. that->colour_type = PNG_COLOR_TYPE_RGB;
  6172. }
  6173. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  6174. that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  6175. this->next->mod(this->next, that, pp, display);
  6176. }
  6177. static int
  6178. image_transform_png_set_gray_to_rgb_add(image_transform *this,
  6179. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6180. {
  6181. UNUSED(bit_depth)
  6182. this->next = *that;
  6183. *that = this;
  6184. return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
  6185. }
  6186. IT(gray_to_rgb);
  6187. #undef PT
  6188. #define PT ITSTRUCT(gray_to_rgb)
  6189. #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
  6190. #ifdef PNG_READ_EXPAND_SUPPORTED
  6191. /* png_set_expand */
  6192. static void
  6193. image_transform_png_set_expand_set(const image_transform *this,
  6194. transform_display *that, png_structp pp, png_infop pi)
  6195. {
  6196. png_set_expand(pp);
  6197. if (that->this.has_tRNS)
  6198. that->this.is_transparent = 1;
  6199. this->next->set(this->next, that, pp, pi);
  6200. }
  6201. static void
  6202. image_transform_png_set_expand_mod(const image_transform *this,
  6203. image_pixel *that, png_const_structp pp,
  6204. const transform_display *display)
  6205. {
  6206. /* The general expand case depends on what the colour type is: */
  6207. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6208. image_pixel_convert_PLTE(that);
  6209. else if (that->bit_depth < 8) /* grayscale */
  6210. that->sample_depth = that->bit_depth = 8;
  6211. if (that->have_tRNS)
  6212. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6213. this->next->mod(this->next, that, pp, display);
  6214. }
  6215. static int
  6216. image_transform_png_set_expand_add(image_transform *this,
  6217. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6218. {
  6219. UNUSED(bit_depth)
  6220. this->next = *that;
  6221. *that = this;
  6222. /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
  6223. * depth is at least 8 already.
  6224. */
  6225. return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  6226. }
  6227. IT(expand);
  6228. #undef PT
  6229. #define PT ITSTRUCT(expand)
  6230. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6231. #ifdef PNG_READ_EXPAND_SUPPORTED
  6232. /* png_set_expand_gray_1_2_4_to_8
  6233. * Pre 1.7.0 LIBPNG BUG: this just does an 'expand'
  6234. */
  6235. static void
  6236. image_transform_png_set_expand_gray_1_2_4_to_8_set(
  6237. const image_transform *this, transform_display *that, png_structp pp,
  6238. png_infop pi)
  6239. {
  6240. png_set_expand_gray_1_2_4_to_8(pp);
  6241. /* NOTE: don't expect this to expand tRNS */
  6242. this->next->set(this->next, that, pp, pi);
  6243. }
  6244. static void
  6245. image_transform_png_set_expand_gray_1_2_4_to_8_mod(
  6246. const image_transform *this, image_pixel *that, png_const_structp pp,
  6247. const transform_display *display)
  6248. {
  6249. #if PNG_LIBPNG_VER != 10700
  6250. image_transform_png_set_expand_mod(this, that, pp, display);
  6251. #else
  6252. /* Only expand grayscale of bit depth less than 8: */
  6253. if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
  6254. that->bit_depth < 8)
  6255. that->sample_depth = that->bit_depth = 8;
  6256. this->next->mod(this->next, that, pp, display);
  6257. #endif /* 1.7 or later */
  6258. }
  6259. static int
  6260. image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
  6261. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6262. {
  6263. #if PNG_LIBPNG_VER != 10700
  6264. return image_transform_png_set_expand_add(this, that, colour_type,
  6265. bit_depth);
  6266. #else
  6267. UNUSED(bit_depth)
  6268. this->next = *that;
  6269. *that = this;
  6270. /* This should do nothing unless the color type is gray and the bit depth is
  6271. * less than 8:
  6272. */
  6273. return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
  6274. #endif /* 1.7 or later */
  6275. }
  6276. IT(expand_gray_1_2_4_to_8);
  6277. #undef PT
  6278. #define PT ITSTRUCT(expand_gray_1_2_4_to_8)
  6279. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6280. #ifdef PNG_READ_EXPAND_16_SUPPORTED
  6281. /* png_set_expand_16 */
  6282. static void
  6283. image_transform_png_set_expand_16_set(const image_transform *this,
  6284. transform_display *that, png_structp pp, png_infop pi)
  6285. {
  6286. png_set_expand_16(pp);
  6287. /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
  6288. # if PNG_LIBPNG_VER != 10700
  6289. if (that->this.has_tRNS)
  6290. that->this.is_transparent = 1;
  6291. # endif
  6292. this->next->set(this->next, that, pp, pi);
  6293. }
  6294. static void
  6295. image_transform_png_set_expand_16_mod(const image_transform *this,
  6296. image_pixel *that, png_const_structp pp,
  6297. const transform_display *display)
  6298. {
  6299. /* Expect expand_16 to expand everything to 16 bits as a result of also
  6300. * causing 'expand' to happen.
  6301. */
  6302. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6303. image_pixel_convert_PLTE(that);
  6304. if (that->have_tRNS)
  6305. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6306. if (that->bit_depth < 16)
  6307. that->sample_depth = that->bit_depth = 16;
  6308. this->next->mod(this->next, that, pp, display);
  6309. }
  6310. static int
  6311. image_transform_png_set_expand_16_add(image_transform *this,
  6312. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6313. {
  6314. UNUSED(colour_type)
  6315. this->next = *that;
  6316. *that = this;
  6317. /* expand_16 does something unless the bit depth is already 16. */
  6318. return bit_depth < 16;
  6319. }
  6320. IT(expand_16);
  6321. #undef PT
  6322. #define PT ITSTRUCT(expand_16)
  6323. #endif /* PNG_READ_EXPAND_16_SUPPORTED */
  6324. #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */
  6325. /* png_set_scale_16 */
  6326. static void
  6327. image_transform_png_set_scale_16_set(const image_transform *this,
  6328. transform_display *that, png_structp pp, png_infop pi)
  6329. {
  6330. png_set_scale_16(pp);
  6331. # if PNG_LIBPNG_VER != 10700
  6332. /* libpng will limit the gamma table size: */
  6333. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  6334. # endif
  6335. this->next->set(this->next, that, pp, pi);
  6336. }
  6337. static void
  6338. image_transform_png_set_scale_16_mod(const image_transform *this,
  6339. image_pixel *that, png_const_structp pp,
  6340. const transform_display *display)
  6341. {
  6342. if (that->bit_depth == 16)
  6343. {
  6344. that->sample_depth = that->bit_depth = 8;
  6345. if (that->red_sBIT > 8) that->red_sBIT = 8;
  6346. if (that->green_sBIT > 8) that->green_sBIT = 8;
  6347. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  6348. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  6349. }
  6350. this->next->mod(this->next, that, pp, display);
  6351. }
  6352. static int
  6353. image_transform_png_set_scale_16_add(image_transform *this,
  6354. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6355. {
  6356. UNUSED(colour_type)
  6357. this->next = *that;
  6358. *that = this;
  6359. return bit_depth > 8;
  6360. }
  6361. IT(scale_16);
  6362. #undef PT
  6363. #define PT ITSTRUCT(scale_16)
  6364. #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
  6365. #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
  6366. /* png_set_strip_16 */
  6367. static void
  6368. image_transform_png_set_strip_16_set(const image_transform *this,
  6369. transform_display *that, png_structp pp, png_infop pi)
  6370. {
  6371. png_set_strip_16(pp);
  6372. # if PNG_LIBPNG_VER != 10700
  6373. /* libpng will limit the gamma table size: */
  6374. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  6375. # endif
  6376. this->next->set(this->next, that, pp, pi);
  6377. }
  6378. static void
  6379. image_transform_png_set_strip_16_mod(const image_transform *this,
  6380. image_pixel *that, png_const_structp pp,
  6381. const transform_display *display)
  6382. {
  6383. if (that->bit_depth == 16)
  6384. {
  6385. that->sample_depth = that->bit_depth = 8;
  6386. if (that->red_sBIT > 8) that->red_sBIT = 8;
  6387. if (that->green_sBIT > 8) that->green_sBIT = 8;
  6388. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  6389. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  6390. /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
  6391. * configuration option is set. From 1.5.4 the flag is never set and the
  6392. * 'scale' API (above) must be used.
  6393. */
  6394. # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
  6395. # if PNG_LIBPNG_VER >= 10504
  6396. # error PNG_READ_ACCURATE_SCALE should not be set
  6397. # endif
  6398. /* The strip 16 algorithm drops the low 8 bits rather than calculating
  6399. * 1/257, so we need to adjust the permitted errors appropriately:
  6400. * Notice that this is only relevant prior to the addition of the
  6401. * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
  6402. */
  6403. {
  6404. const double d = (255-128.5)/65535;
  6405. that->rede += d;
  6406. that->greene += d;
  6407. that->bluee += d;
  6408. that->alphae += d;
  6409. }
  6410. # endif
  6411. }
  6412. this->next->mod(this->next, that, pp, display);
  6413. }
  6414. static int
  6415. image_transform_png_set_strip_16_add(image_transform *this,
  6416. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6417. {
  6418. UNUSED(colour_type)
  6419. this->next = *that;
  6420. *that = this;
  6421. return bit_depth > 8;
  6422. }
  6423. IT(strip_16);
  6424. #undef PT
  6425. #define PT ITSTRUCT(strip_16)
  6426. #endif /* PNG_READ_16_TO_8_SUPPORTED */
  6427. #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
  6428. /* png_set_strip_alpha */
  6429. static void
  6430. image_transform_png_set_strip_alpha_set(const image_transform *this,
  6431. transform_display *that, png_structp pp, png_infop pi)
  6432. {
  6433. png_set_strip_alpha(pp);
  6434. this->next->set(this->next, that, pp, pi);
  6435. }
  6436. static void
  6437. image_transform_png_set_strip_alpha_mod(const image_transform *this,
  6438. image_pixel *that, png_const_structp pp,
  6439. const transform_display *display)
  6440. {
  6441. if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  6442. that->colour_type = PNG_COLOR_TYPE_GRAY;
  6443. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  6444. that->colour_type = PNG_COLOR_TYPE_RGB;
  6445. that->have_tRNS = 0;
  6446. that->alphaf = 1;
  6447. this->next->mod(this->next, that, pp, display);
  6448. }
  6449. static int
  6450. image_transform_png_set_strip_alpha_add(image_transform *this,
  6451. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6452. {
  6453. UNUSED(bit_depth)
  6454. this->next = *that;
  6455. *that = this;
  6456. return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
  6457. }
  6458. IT(strip_alpha);
  6459. #undef PT
  6460. #define PT ITSTRUCT(strip_alpha)
  6461. #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
  6462. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  6463. /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
  6464. * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
  6465. * png_fixed_point green)
  6466. * png_get_rgb_to_gray_status
  6467. *
  6468. * The 'default' test here uses values known to be used inside libpng prior to
  6469. * 1.7.0:
  6470. *
  6471. * red: 6968
  6472. * green: 23434
  6473. * blue: 2366
  6474. *
  6475. * These values are being retained for compatibility, along with the somewhat
  6476. * broken truncation calculation in the fast-and-inaccurate code path. Older
  6477. * versions of libpng will fail the accuracy tests below because they use the
  6478. * truncation algorithm everywhere.
  6479. */
  6480. #define data ITDATA(rgb_to_gray)
  6481. static struct
  6482. {
  6483. double gamma; /* File gamma to use in processing */
  6484. /* The following are the parameters for png_set_rgb_to_gray: */
  6485. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6486. double red_to_set;
  6487. double green_to_set;
  6488. # else
  6489. png_fixed_point red_to_set;
  6490. png_fixed_point green_to_set;
  6491. # endif
  6492. /* The actual coefficients: */
  6493. double red_coefficient;
  6494. double green_coefficient;
  6495. double blue_coefficient;
  6496. /* Set if the coeefficients have been overridden. */
  6497. int coefficients_overridden;
  6498. } data;
  6499. #undef image_transform_ini
  6500. #define image_transform_ini image_transform_png_set_rgb_to_gray_ini
  6501. static void
  6502. image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
  6503. transform_display *that)
  6504. {
  6505. png_modifier *pm = that->pm;
  6506. const color_encoding *e = pm->current_encoding;
  6507. UNUSED(this)
  6508. /* Since we check the encoding this flag must be set: */
  6509. pm->test_uses_encoding = 1;
  6510. /* If 'e' is not NULL chromaticity information is present and either a cHRM
  6511. * or an sRGB chunk will be inserted.
  6512. */
  6513. if (e != 0)
  6514. {
  6515. /* Coefficients come from the encoding, but may need to be normalized to a
  6516. * white point Y of 1.0
  6517. */
  6518. const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
  6519. data.red_coefficient = e->red.Y;
  6520. data.green_coefficient = e->green.Y;
  6521. data.blue_coefficient = e->blue.Y;
  6522. if (whiteY != 1)
  6523. {
  6524. data.red_coefficient /= whiteY;
  6525. data.green_coefficient /= whiteY;
  6526. data.blue_coefficient /= whiteY;
  6527. }
  6528. }
  6529. else
  6530. {
  6531. /* The default (built in) coefficients, as above: */
  6532. # if PNG_LIBPNG_VER != 10700
  6533. data.red_coefficient = 6968 / 32768.;
  6534. data.green_coefficient = 23434 / 32768.;
  6535. data.blue_coefficient = 2366 / 32768.;
  6536. # else
  6537. data.red_coefficient = .2126;
  6538. data.green_coefficient = .7152;
  6539. data.blue_coefficient = .0722;
  6540. # endif
  6541. }
  6542. data.gamma = pm->current_gamma;
  6543. /* If not set then the calculations assume linear encoding (implicitly): */
  6544. if (data.gamma == 0)
  6545. data.gamma = 1;
  6546. /* The arguments to png_set_rgb_to_gray can override the coefficients implied
  6547. * by the color space encoding. If doing exhaustive checks do the override
  6548. * in each case, otherwise do it randomly.
  6549. */
  6550. if (pm->test_exhaustive)
  6551. {
  6552. /* First time in coefficients_overridden is 0, the following sets it to 1,
  6553. * so repeat if it is set. If a test fails this may mean we subsequently
  6554. * skip a non-override test, ignore that.
  6555. */
  6556. data.coefficients_overridden = !data.coefficients_overridden;
  6557. pm->repeat = data.coefficients_overridden != 0;
  6558. }
  6559. else
  6560. data.coefficients_overridden = random_choice();
  6561. if (data.coefficients_overridden)
  6562. {
  6563. /* These values override the color encoding defaults, simply use random
  6564. * numbers.
  6565. */
  6566. png_uint_32 ru;
  6567. double total;
  6568. ru = random_u32();
  6569. data.green_coefficient = total = (ru & 0xffff) / 65535.;
  6570. ru >>= 16;
  6571. data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
  6572. total += data.red_coefficient;
  6573. data.blue_coefficient = 1 - total;
  6574. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6575. data.red_to_set = data.red_coefficient;
  6576. data.green_to_set = data.green_coefficient;
  6577. # else
  6578. data.red_to_set = fix(data.red_coefficient);
  6579. data.green_to_set = fix(data.green_coefficient);
  6580. # endif
  6581. /* The following just changes the error messages: */
  6582. pm->encoding_ignored = 1;
  6583. }
  6584. else
  6585. {
  6586. data.red_to_set = -1;
  6587. data.green_to_set = -1;
  6588. }
  6589. /* Adjust the error limit in the png_modifier because of the larger errors
  6590. * produced in the digitization during the gamma handling.
  6591. */
  6592. if (data.gamma != 1) /* Use gamma tables */
  6593. {
  6594. if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
  6595. {
  6596. /* The computations have the form:
  6597. *
  6598. * r * rc + g * gc + b * bc
  6599. *
  6600. * Each component of which is +/-1/65535 from the gamma_to_1 table
  6601. * lookup, resulting in a base error of +/-6. The gamma_from_1
  6602. * conversion adds another +/-2 in the 16-bit case and
  6603. * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
  6604. */
  6605. # if PNG_LIBPNG_VER != 10700
  6606. if (that->this.bit_depth < 16)
  6607. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  6608. # endif
  6609. that->pm->limit += pow(
  6610. (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
  6611. 8. :
  6612. 6. + (1<<(15-that->max_gamma_8))
  6613. )/65535, data.gamma);
  6614. }
  6615. else
  6616. {
  6617. /* Rounding to 8 bits in the linear space causes massive errors which
  6618. * will trigger the error check in transform_range_check. Fix that
  6619. * here by taking the gamma encoding into account.
  6620. *
  6621. * When DIGITIZE is set because a pre-1.7 version of libpng is being
  6622. * tested allow a bigger slack.
  6623. *
  6624. * NOTE: this number only affects the internal limit check in pngvalid,
  6625. * it has no effect on the limits applied to the libpng values.
  6626. */
  6627. #if DIGITIZE
  6628. that->pm->limit += pow( 2.0/255, data.gamma);
  6629. #else
  6630. that->pm->limit += pow( 1.0/255, data.gamma);
  6631. #endif
  6632. }
  6633. }
  6634. else
  6635. {
  6636. /* With no gamma correction a large error comes from the truncation of the
  6637. * calculation in the 8 bit case, allow for that here.
  6638. */
  6639. if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
  6640. that->pm->limit += 4E-3;
  6641. }
  6642. }
  6643. static void
  6644. image_transform_png_set_rgb_to_gray_set(const image_transform *this,
  6645. transform_display *that, png_structp pp, png_infop pi)
  6646. {
  6647. int error_action = 1; /* no error, no defines in png.h */
  6648. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6649. png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
  6650. # else
  6651. png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
  6652. data.green_to_set);
  6653. # endif
  6654. # ifdef PNG_READ_cHRM_SUPPORTED
  6655. if (that->pm->current_encoding != 0)
  6656. {
  6657. /* We have an encoding so a cHRM chunk may have been set; if so then
  6658. * check that the libpng APIs give the correct (X,Y,Z) values within
  6659. * some margin of error for the round trip through the chromaticity
  6660. * form.
  6661. */
  6662. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6663. # define API_function png_get_cHRM_XYZ
  6664. # define API_form "FP"
  6665. # define API_type double
  6666. # define API_cvt(x) (x)
  6667. # else
  6668. # define API_function png_get_cHRM_XYZ_fixed
  6669. # define API_form "fixed"
  6670. # define API_type png_fixed_point
  6671. # define API_cvt(x) ((double)(x)/PNG_FP_1)
  6672. # endif
  6673. API_type rX, gX, bX;
  6674. API_type rY, gY, bY;
  6675. API_type rZ, gZ, bZ;
  6676. if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
  6677. & PNG_INFO_cHRM) != 0)
  6678. {
  6679. double maxe;
  6680. const char *el;
  6681. color_encoding e, o;
  6682. /* Expect libpng to return a normalized result, but the original
  6683. * color space encoding may not be normalized.
  6684. */
  6685. modifier_current_encoding(that->pm, &o);
  6686. normalize_color_encoding(&o);
  6687. /* Sanity check the pngvalid code - the coefficients should match
  6688. * the normalized Y values of the encoding unless they were
  6689. * overridden.
  6690. */
  6691. if (data.red_to_set == -1 && data.green_to_set == -1 &&
  6692. (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
  6693. fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
  6694. fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
  6695. png_error(pp, "internal pngvalid cHRM coefficient error");
  6696. /* Generate a colour space encoding. */
  6697. e.gamma = o.gamma; /* not used */
  6698. e.red.X = API_cvt(rX);
  6699. e.red.Y = API_cvt(rY);
  6700. e.red.Z = API_cvt(rZ);
  6701. e.green.X = API_cvt(gX);
  6702. e.green.Y = API_cvt(gY);
  6703. e.green.Z = API_cvt(gZ);
  6704. e.blue.X = API_cvt(bX);
  6705. e.blue.Y = API_cvt(bY);
  6706. e.blue.Z = API_cvt(bZ);
  6707. /* This should match the original one from the png_modifier, within
  6708. * the range permitted by the libpng fixed point representation.
  6709. */
  6710. maxe = 0;
  6711. el = "-"; /* Set to element name with error */
  6712. # define CHECK(col,x)\
  6713. {\
  6714. double err = fabs(o.col.x - e.col.x);\
  6715. if (err > maxe)\
  6716. {\
  6717. maxe = err;\
  6718. el = #col "(" #x ")";\
  6719. }\
  6720. }
  6721. CHECK(red,X)
  6722. CHECK(red,Y)
  6723. CHECK(red,Z)
  6724. CHECK(green,X)
  6725. CHECK(green,Y)
  6726. CHECK(green,Z)
  6727. CHECK(blue,X)
  6728. CHECK(blue,Y)
  6729. CHECK(blue,Z)
  6730. /* Here in both fixed and floating cases to check the values read
  6731. * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
  6732. * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
  6733. */
  6734. if (maxe >= 1E-5)
  6735. {
  6736. size_t pos = 0;
  6737. char buffer[256];
  6738. pos = safecat(buffer, sizeof buffer, pos, API_form);
  6739. pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
  6740. pos = safecat(buffer, sizeof buffer, pos, el);
  6741. pos = safecat(buffer, sizeof buffer, pos, " error: ");
  6742. pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
  6743. pos = safecat(buffer, sizeof buffer, pos, " ");
  6744. /* Print the color space without the gamma value: */
  6745. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
  6746. pos = safecat(buffer, sizeof buffer, pos, " -> ");
  6747. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
  6748. png_error(pp, buffer);
  6749. }
  6750. }
  6751. }
  6752. # endif /* READ_cHRM */
  6753. this->next->set(this->next, that, pp, pi);
  6754. }
  6755. static void
  6756. image_transform_png_set_rgb_to_gray_mod(const image_transform *this,
  6757. image_pixel *that, png_const_structp pp,
  6758. const transform_display *display)
  6759. {
  6760. if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
  6761. {
  6762. double gray, err;
  6763. # if PNG_LIBPNG_VER != 10700
  6764. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6765. image_pixel_convert_PLTE(that);
  6766. # endif
  6767. /* Image now has RGB channels... */
  6768. # if DIGITIZE
  6769. {
  6770. png_modifier *pm = display->pm;
  6771. unsigned int sample_depth = that->sample_depth;
  6772. unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
  6773. sample_depth);
  6774. unsigned int gamma_depth =
  6775. (sample_depth == 16 ?
  6776. display->max_gamma_8 :
  6777. (pm->assume_16_bit_calculations ?
  6778. display->max_gamma_8 :
  6779. sample_depth));
  6780. int isgray;
  6781. double r, g, b;
  6782. double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
  6783. /* Do this using interval arithmetic, otherwise it is too difficult to
  6784. * handle the errors correctly.
  6785. *
  6786. * To handle the gamma correction work out the upper and lower bounds
  6787. * of the digitized value. Assume rounding here - normally the values
  6788. * will be identical after this operation if there is only one
  6789. * transform, feel free to delete the png_error checks on this below in
  6790. * the future (this is just me trying to ensure it works!)
  6791. *
  6792. * Interval arithmetic is exact, but to implement it it must be
  6793. * possible to control the floating point implementation rounding mode.
  6794. * This cannot be done in ANSI-C, so instead I reduce the 'lo' values
  6795. * by DBL_EPSILON and increase the 'hi' values by the same.
  6796. */
  6797. # define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON))
  6798. # define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON))
  6799. r = rlo = rhi = that->redf;
  6800. rlo -= that->rede;
  6801. rlo = DD(rlo, calc_depth, 1/*round*/);
  6802. rhi += that->rede;
  6803. rhi = DU(rhi, calc_depth, 1/*round*/);
  6804. g = glo = ghi = that->greenf;
  6805. glo -= that->greene;
  6806. glo = DD(glo, calc_depth, 1/*round*/);
  6807. ghi += that->greene;
  6808. ghi = DU(ghi, calc_depth, 1/*round*/);
  6809. b = blo = bhi = that->bluef;
  6810. blo -= that->bluee;
  6811. blo = DD(blo, calc_depth, 1/*round*/);
  6812. bhi += that->bluee;
  6813. bhi = DU(bhi, calc_depth, 1/*round*/);
  6814. isgray = r==g && g==b;
  6815. if (data.gamma != 1)
  6816. {
  6817. const double power = 1/data.gamma;
  6818. const double abse = .5/(sample_depth == 16 ? 65535 : 255);
  6819. /* If a gamma calculation is done it is done using lookup tables of
  6820. * precision gamma_depth, so the already digitized value above may
  6821. * need to be further digitized here.
  6822. */
  6823. if (gamma_depth != calc_depth)
  6824. {
  6825. rlo = DD(rlo, gamma_depth, 0/*truncate*/);
  6826. rhi = DU(rhi, gamma_depth, 0/*truncate*/);
  6827. glo = DD(glo, gamma_depth, 0/*truncate*/);
  6828. ghi = DU(ghi, gamma_depth, 0/*truncate*/);
  6829. blo = DD(blo, gamma_depth, 0/*truncate*/);
  6830. bhi = DU(bhi, gamma_depth, 0/*truncate*/);
  6831. }
  6832. /* 'abse' is the error in the gamma table calculation itself. */
  6833. r = pow(r, power);
  6834. rlo = DD(pow(rlo, power)-abse, calc_depth, 1);
  6835. rhi = DU(pow(rhi, power)+abse, calc_depth, 1);
  6836. g = pow(g, power);
  6837. glo = DD(pow(glo, power)-abse, calc_depth, 1);
  6838. ghi = DU(pow(ghi, power)+abse, calc_depth, 1);
  6839. b = pow(b, power);
  6840. blo = DD(pow(blo, power)-abse, calc_depth, 1);
  6841. bhi = DU(pow(bhi, power)+abse, calc_depth, 1);
  6842. }
  6843. /* Now calculate the actual gray values. Although the error in the
  6844. * coefficients depends on whether they were specified on the command
  6845. * line (in which case truncation to 15 bits happened) or not (rounding
  6846. * was used) the maximum error in an individual coefficient is always
  6847. * 2/32768, because even in the rounding case the requirement that
  6848. * coefficients add up to 32768 can cause a larger rounding error.
  6849. *
  6850. * The only time when rounding doesn't occur in 1.5.5 and later is when
  6851. * the non-gamma code path is used for less than 16 bit data.
  6852. */
  6853. gray = r * data.red_coefficient + g * data.green_coefficient +
  6854. b * data.blue_coefficient;
  6855. {
  6856. int do_round = data.gamma != 1 || calc_depth == 16;
  6857. const double ce = 2. / 32768;
  6858. graylo = DD(rlo * (data.red_coefficient-ce) +
  6859. glo * (data.green_coefficient-ce) +
  6860. blo * (data.blue_coefficient-ce), calc_depth, do_round);
  6861. if (graylo > gray) /* always accept the right answer */
  6862. graylo = gray;
  6863. grayhi = DU(rhi * (data.red_coefficient+ce) +
  6864. ghi * (data.green_coefficient+ce) +
  6865. bhi * (data.blue_coefficient+ce), calc_depth, do_round);
  6866. if (grayhi < gray)
  6867. grayhi = gray;
  6868. }
  6869. /* And invert the gamma. */
  6870. if (data.gamma != 1)
  6871. {
  6872. const double power = data.gamma;
  6873. /* And this happens yet again, shifting the values once more. */
  6874. if (gamma_depth != sample_depth)
  6875. {
  6876. rlo = DD(rlo, gamma_depth, 0/*truncate*/);
  6877. rhi = DU(rhi, gamma_depth, 0/*truncate*/);
  6878. glo = DD(glo, gamma_depth, 0/*truncate*/);
  6879. ghi = DU(ghi, gamma_depth, 0/*truncate*/);
  6880. blo = DD(blo, gamma_depth, 0/*truncate*/);
  6881. bhi = DU(bhi, gamma_depth, 0/*truncate*/);
  6882. }
  6883. gray = pow(gray, power);
  6884. graylo = DD(pow(graylo, power), sample_depth, 1);
  6885. grayhi = DU(pow(grayhi, power), sample_depth, 1);
  6886. }
  6887. # undef DD
  6888. # undef DU
  6889. /* Now the error can be calculated.
  6890. *
  6891. * If r==g==b because there is no overall gamma correction libpng
  6892. * currently preserves the original value.
  6893. */
  6894. if (isgray)
  6895. err = (that->rede + that->greene + that->bluee)/3;
  6896. else
  6897. {
  6898. err = fabs(grayhi-gray);
  6899. if (fabs(gray - graylo) > err)
  6900. err = fabs(graylo-gray);
  6901. #if !RELEASE_BUILD
  6902. /* Check that this worked: */
  6903. if (err > pm->limit)
  6904. {
  6905. size_t pos = 0;
  6906. char buffer[128];
  6907. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  6908. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  6909. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  6910. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  6911. png_warning(pp, buffer);
  6912. pm->limit = err;
  6913. }
  6914. #endif /* !RELEASE_BUILD */
  6915. }
  6916. }
  6917. # else /* !DIGITIZE */
  6918. {
  6919. double r = that->redf;
  6920. double re = that->rede;
  6921. double g = that->greenf;
  6922. double ge = that->greene;
  6923. double b = that->bluef;
  6924. double be = that->bluee;
  6925. # if PNG_LIBPNG_VER != 10700
  6926. /* The true gray case involves no math in earlier versions (not
  6927. * true, there was some if gamma correction was happening too.)
  6928. */
  6929. if (r == g && r == b)
  6930. {
  6931. gray = r;
  6932. err = re;
  6933. if (err < ge) err = ge;
  6934. if (err < be) err = be;
  6935. }
  6936. else
  6937. # endif /* before 1.7 */
  6938. if (data.gamma == 1)
  6939. {
  6940. /* There is no need to do the conversions to and from linear space,
  6941. * so the calculation should be a lot more accurate. There is a
  6942. * built in error in the coefficients because they only have 15 bits
  6943. * and are adjusted to make sure they add up to 32768. This
  6944. * involves a integer calculation with truncation of the form:
  6945. *
  6946. * ((int)(coefficient * 100000) * 32768)/100000
  6947. *
  6948. * This is done to the red and green coefficients (the ones
  6949. * provided to the API) then blue is calculated from them so the
  6950. * result adds up to 32768. In the worst case this can result in
  6951. * a -1 error in red and green and a +2 error in blue. Consequently
  6952. * the worst case in the calculation below is 2/32768 error.
  6953. *
  6954. * TODO: consider fixing this in libpng by rounding the calculation
  6955. * limiting the error to 1/32768.
  6956. *
  6957. * Handling this by adding 2/32768 here avoids needing to increase
  6958. * the global error limits to take this into account.)
  6959. */
  6960. gray = r * data.red_coefficient + g * data.green_coefficient +
  6961. b * data.blue_coefficient;
  6962. err = re * data.red_coefficient + ge * data.green_coefficient +
  6963. be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON;
  6964. }
  6965. else
  6966. {
  6967. /* The calculation happens in linear space, and this produces much
  6968. * wider errors in the encoded space. These are handled here by
  6969. * factoring the errors in to the calculation. There are two table
  6970. * lookups in the calculation and each introduces a quantization
  6971. * error defined by the table size.
  6972. */
  6973. png_modifier *pm = display->pm;
  6974. double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
  6975. double out_qe = (that->sample_depth > 8 ? .5/65535 :
  6976. (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) :
  6977. .5/255));
  6978. double rhi, ghi, bhi, grayhi;
  6979. double g1 = 1/data.gamma;
  6980. rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
  6981. r -= re + in_qe; if (r < 0) r = 0;
  6982. ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
  6983. g -= ge + in_qe; if (g < 0) g = 0;
  6984. bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
  6985. b -= be + in_qe; if (b < 0) b = 0;
  6986. r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
  6987. g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
  6988. b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
  6989. /* Work out the lower and upper bounds for the gray value in the
  6990. * encoded space, then work out an average and error. Remove the
  6991. * previously added input quantization error at this point.
  6992. */
  6993. gray = r * data.red_coefficient + g * data.green_coefficient +
  6994. b * data.blue_coefficient - 2./32768 - out_qe;
  6995. if (gray <= 0)
  6996. gray = 0;
  6997. else
  6998. {
  6999. gray *= (1 - 6 * DBL_EPSILON);
  7000. gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
  7001. }
  7002. grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
  7003. bhi * data.blue_coefficient + 2./32768 + out_qe;
  7004. grayhi *= (1 + 6 * DBL_EPSILON);
  7005. if (grayhi >= 1)
  7006. grayhi = 1;
  7007. else
  7008. grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
  7009. err = (grayhi - gray) / 2;
  7010. gray = (grayhi + gray) / 2;
  7011. if (err <= in_qe)
  7012. err = gray * DBL_EPSILON;
  7013. else
  7014. err -= in_qe;
  7015. #if !RELEASE_BUILD
  7016. /* Validate that the error is within limits (this has caused
  7017. * problems before, it's much easier to detect them here.)
  7018. */
  7019. if (err > pm->limit)
  7020. {
  7021. size_t pos = 0;
  7022. char buffer[128];
  7023. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  7024. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  7025. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  7026. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  7027. png_warning(pp, buffer);
  7028. pm->limit = err;
  7029. }
  7030. #endif /* !RELEASE_BUILD */
  7031. }
  7032. }
  7033. # endif /* !DIGITIZE */
  7034. that->bluef = that->greenf = that->redf = gray;
  7035. that->bluee = that->greene = that->rede = err;
  7036. /* The sBIT is the minimum of the three colour channel sBITs. */
  7037. if (that->red_sBIT > that->green_sBIT)
  7038. that->red_sBIT = that->green_sBIT;
  7039. if (that->red_sBIT > that->blue_sBIT)
  7040. that->red_sBIT = that->blue_sBIT;
  7041. that->blue_sBIT = that->green_sBIT = that->red_sBIT;
  7042. /* And remove the colour bit in the type: */
  7043. if (that->colour_type == PNG_COLOR_TYPE_RGB)
  7044. that->colour_type = PNG_COLOR_TYPE_GRAY;
  7045. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  7046. that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  7047. }
  7048. this->next->mod(this->next, that, pp, display);
  7049. }
  7050. static int
  7051. image_transform_png_set_rgb_to_gray_add(image_transform *this,
  7052. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7053. {
  7054. UNUSED(bit_depth)
  7055. this->next = *that;
  7056. *that = this;
  7057. return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
  7058. }
  7059. #undef data
  7060. IT(rgb_to_gray);
  7061. #undef PT
  7062. #define PT ITSTRUCT(rgb_to_gray)
  7063. #undef image_transform_ini
  7064. #define image_transform_ini image_transform_default_ini
  7065. #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
  7066. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  7067. /* png_set_background(png_structp, png_const_color_16p background_color,
  7068. * int background_gamma_code, int need_expand, double background_gamma)
  7069. * png_set_background_fixed(png_structp, png_const_color_16p background_color,
  7070. * int background_gamma_code, int need_expand,
  7071. * png_fixed_point background_gamma)
  7072. *
  7073. * This ignores the gamma (at present.)
  7074. */
  7075. #define data ITDATA(background)
  7076. static image_pixel data;
  7077. static void
  7078. image_transform_png_set_background_set(const image_transform *this,
  7079. transform_display *that, png_structp pp, png_infop pi)
  7080. {
  7081. png_byte colour_type, bit_depth;
  7082. png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
  7083. int expand;
  7084. png_color_16 back;
  7085. /* We need a background colour, because we don't know exactly what transforms
  7086. * have been set we have to supply the colour in the original file format and
  7087. * so we need to know what that is! The background colour is stored in the
  7088. * transform_display.
  7089. */
  7090. R8(random_bytes);
  7091. /* Read the random value, for colour type 3 the background colour is actually
  7092. * expressed as a 24bit rgb, not an index.
  7093. */
  7094. colour_type = that->this.colour_type;
  7095. if (colour_type == 3)
  7096. {
  7097. colour_type = PNG_COLOR_TYPE_RGB;
  7098. bit_depth = 8;
  7099. expand = 0; /* passing in an RGB not a pixel index */
  7100. }
  7101. else
  7102. {
  7103. if (that->this.has_tRNS)
  7104. that->this.is_transparent = 1;
  7105. bit_depth = that->this.bit_depth;
  7106. expand = 1;
  7107. }
  7108. image_pixel_init(&data, random_bytes, colour_type,
  7109. bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
  7110. /* Extract the background colour from this image_pixel, but make sure the
  7111. * unused fields of 'back' are garbage.
  7112. */
  7113. R8(back);
  7114. if (colour_type & PNG_COLOR_MASK_COLOR)
  7115. {
  7116. back.red = (png_uint_16)data.red;
  7117. back.green = (png_uint_16)data.green;
  7118. back.blue = (png_uint_16)data.blue;
  7119. }
  7120. else
  7121. back.gray = (png_uint_16)data.red;
  7122. #ifdef PNG_FLOATING_POINT_SUPPORTED
  7123. png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  7124. #else
  7125. png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  7126. #endif
  7127. this->next->set(this->next, that, pp, pi);
  7128. }
  7129. static void
  7130. image_transform_png_set_background_mod(const image_transform *this,
  7131. image_pixel *that, png_const_structp pp,
  7132. const transform_display *display)
  7133. {
  7134. /* Check for tRNS first: */
  7135. if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
  7136. image_pixel_add_alpha(that, &display->this, 1/*for background*/);
  7137. /* This is only necessary if the alpha value is less than 1. */
  7138. if (that->alphaf < 1)
  7139. {
  7140. /* Now we do the background calculation without any gamma correction. */
  7141. if (that->alphaf <= 0)
  7142. {
  7143. that->redf = data.redf;
  7144. that->greenf = data.greenf;
  7145. that->bluef = data.bluef;
  7146. that->rede = data.rede;
  7147. that->greene = data.greene;
  7148. that->bluee = data.bluee;
  7149. that->red_sBIT= data.red_sBIT;
  7150. that->green_sBIT= data.green_sBIT;
  7151. that->blue_sBIT= data.blue_sBIT;
  7152. }
  7153. else /* 0 < alpha < 1 */
  7154. {
  7155. double alf = 1 - that->alphaf;
  7156. that->redf = that->redf * that->alphaf + data.redf * alf;
  7157. that->rede = that->rede * that->alphaf + data.rede * alf +
  7158. DBL_EPSILON;
  7159. that->greenf = that->greenf * that->alphaf + data.greenf * alf;
  7160. that->greene = that->greene * that->alphaf + data.greene * alf +
  7161. DBL_EPSILON;
  7162. that->bluef = that->bluef * that->alphaf + data.bluef * alf;
  7163. that->bluee = that->bluee * that->alphaf + data.bluee * alf +
  7164. DBL_EPSILON;
  7165. }
  7166. /* Remove the alpha type and set the alpha (not in that order.) */
  7167. that->alphaf = 1;
  7168. that->alphae = 0;
  7169. }
  7170. if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  7171. that->colour_type = PNG_COLOR_TYPE_RGB;
  7172. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  7173. that->colour_type = PNG_COLOR_TYPE_GRAY;
  7174. /* PNG_COLOR_TYPE_PALETTE is not changed */
  7175. this->next->mod(this->next, that, pp, display);
  7176. }
  7177. #define image_transform_png_set_background_add image_transform_default_add
  7178. #undef data
  7179. IT(background);
  7180. #undef PT
  7181. #define PT ITSTRUCT(background)
  7182. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  7183. /* png_set_quantize(png_structp, png_colorp palette, int num_palette,
  7184. * int maximum_colors, png_const_uint_16p histogram, int full_quantize)
  7185. *
  7186. * Very difficult to validate this!
  7187. */
  7188. /*NOTE: TBD NYI */
  7189. /* The data layout transforms are handled by swapping our own channel data,
  7190. * necessarily these need to happen at the end of the transform list because the
  7191. * semantic of the channels changes after these are executed. Some of these,
  7192. * like set_shift and set_packing, can't be done at present because they change
  7193. * the layout of the data at the sub-sample level so sample() won't get the
  7194. * right answer.
  7195. */
  7196. /* png_set_invert_alpha */
  7197. #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
  7198. /* Invert the alpha channel
  7199. *
  7200. * png_set_invert_alpha(png_structrp png_ptr)
  7201. */
  7202. static void
  7203. image_transform_png_set_invert_alpha_set(const image_transform *this,
  7204. transform_display *that, png_structp pp, png_infop pi)
  7205. {
  7206. png_set_invert_alpha(pp);
  7207. this->next->set(this->next, that, pp, pi);
  7208. }
  7209. static void
  7210. image_transform_png_set_invert_alpha_mod(const image_transform *this,
  7211. image_pixel *that, png_const_structp pp,
  7212. const transform_display *display)
  7213. {
  7214. if (that->colour_type & 4)
  7215. that->alpha_inverted = 1;
  7216. this->next->mod(this->next, that, pp, display);
  7217. }
  7218. static int
  7219. image_transform_png_set_invert_alpha_add(image_transform *this,
  7220. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7221. {
  7222. UNUSED(bit_depth)
  7223. this->next = *that;
  7224. *that = this;
  7225. /* Only has an effect on pixels with alpha: */
  7226. return (colour_type & 4) != 0;
  7227. }
  7228. IT(invert_alpha);
  7229. #undef PT
  7230. #define PT ITSTRUCT(invert_alpha)
  7231. #endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
  7232. /* png_set_bgr */
  7233. #ifdef PNG_READ_BGR_SUPPORTED
  7234. /* Swap R,G,B channels to order B,G,R.
  7235. *
  7236. * png_set_bgr(png_structrp png_ptr)
  7237. *
  7238. * This only has an effect on RGB and RGBA pixels.
  7239. */
  7240. static void
  7241. image_transform_png_set_bgr_set(const image_transform *this,
  7242. transform_display *that, png_structp pp, png_infop pi)
  7243. {
  7244. png_set_bgr(pp);
  7245. this->next->set(this->next, that, pp, pi);
  7246. }
  7247. static void
  7248. image_transform_png_set_bgr_mod(const image_transform *this,
  7249. image_pixel *that, png_const_structp pp,
  7250. const transform_display *display)
  7251. {
  7252. if (that->colour_type == PNG_COLOR_TYPE_RGB ||
  7253. that->colour_type == PNG_COLOR_TYPE_RGBA)
  7254. that->swap_rgb = 1;
  7255. this->next->mod(this->next, that, pp, display);
  7256. }
  7257. static int
  7258. image_transform_png_set_bgr_add(image_transform *this,
  7259. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7260. {
  7261. UNUSED(bit_depth)
  7262. this->next = *that;
  7263. *that = this;
  7264. return colour_type == PNG_COLOR_TYPE_RGB ||
  7265. colour_type == PNG_COLOR_TYPE_RGBA;
  7266. }
  7267. IT(bgr);
  7268. #undef PT
  7269. #define PT ITSTRUCT(bgr)
  7270. #endif /* PNG_READ_BGR_SUPPORTED */
  7271. /* png_set_swap_alpha */
  7272. #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
  7273. /* Put the alpha channel first.
  7274. *
  7275. * png_set_swap_alpha(png_structrp png_ptr)
  7276. *
  7277. * This only has an effect on GA and RGBA pixels.
  7278. */
  7279. static void
  7280. image_transform_png_set_swap_alpha_set(const image_transform *this,
  7281. transform_display *that, png_structp pp, png_infop pi)
  7282. {
  7283. png_set_swap_alpha(pp);
  7284. this->next->set(this->next, that, pp, pi);
  7285. }
  7286. static void
  7287. image_transform_png_set_swap_alpha_mod(const image_transform *this,
  7288. image_pixel *that, png_const_structp pp,
  7289. const transform_display *display)
  7290. {
  7291. if (that->colour_type == PNG_COLOR_TYPE_GA ||
  7292. that->colour_type == PNG_COLOR_TYPE_RGBA)
  7293. that->alpha_first = 1;
  7294. this->next->mod(this->next, that, pp, display);
  7295. }
  7296. static int
  7297. image_transform_png_set_swap_alpha_add(image_transform *this,
  7298. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7299. {
  7300. UNUSED(bit_depth)
  7301. this->next = *that;
  7302. *that = this;
  7303. return colour_type == PNG_COLOR_TYPE_GA ||
  7304. colour_type == PNG_COLOR_TYPE_RGBA;
  7305. }
  7306. IT(swap_alpha);
  7307. #undef PT
  7308. #define PT ITSTRUCT(swap_alpha)
  7309. #endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
  7310. /* png_set_swap */
  7311. #ifdef PNG_READ_SWAP_SUPPORTED
  7312. /* Byte swap 16-bit components.
  7313. *
  7314. * png_set_swap(png_structrp png_ptr)
  7315. */
  7316. static void
  7317. image_transform_png_set_swap_set(const image_transform *this,
  7318. transform_display *that, png_structp pp, png_infop pi)
  7319. {
  7320. png_set_swap(pp);
  7321. this->next->set(this->next, that, pp, pi);
  7322. }
  7323. static void
  7324. image_transform_png_set_swap_mod(const image_transform *this,
  7325. image_pixel *that, png_const_structp pp,
  7326. const transform_display *display)
  7327. {
  7328. if (that->bit_depth == 16)
  7329. that->swap16 = 1;
  7330. this->next->mod(this->next, that, pp, display);
  7331. }
  7332. static int
  7333. image_transform_png_set_swap_add(image_transform *this,
  7334. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7335. {
  7336. UNUSED(colour_type)
  7337. this->next = *that;
  7338. *that = this;
  7339. return bit_depth == 16;
  7340. }
  7341. IT(swap);
  7342. #undef PT
  7343. #define PT ITSTRUCT(swap)
  7344. #endif /* PNG_READ_SWAP_SUPPORTED */
  7345. #ifdef PNG_READ_FILLER_SUPPORTED
  7346. /* Add a filler byte to 8-bit Gray or 24-bit RGB images.
  7347. *
  7348. * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
  7349. *
  7350. * Flags:
  7351. *
  7352. * PNG_FILLER_BEFORE
  7353. * PNG_FILLER_AFTER
  7354. */
  7355. #define data ITDATA(filler)
  7356. static struct
  7357. {
  7358. png_uint_32 filler;
  7359. int flags;
  7360. } data;
  7361. static void
  7362. image_transform_png_set_filler_set(const image_transform *this,
  7363. transform_display *that, png_structp pp, png_infop pi)
  7364. {
  7365. /* Need a random choice for 'before' and 'after' as well as for the
  7366. * filler. The 'filler' value has all 32 bits set, but only bit_depth
  7367. * will be used. At this point we don't know bit_depth.
  7368. */
  7369. data.filler = random_u32();
  7370. data.flags = random_choice();
  7371. png_set_filler(pp, data.filler, data.flags);
  7372. /* The standard display handling stuff also needs to know that
  7373. * there is a filler, so set that here.
  7374. */
  7375. that->this.filler = 1;
  7376. this->next->set(this->next, that, pp, pi);
  7377. }
  7378. static void
  7379. image_transform_png_set_filler_mod(const image_transform *this,
  7380. image_pixel *that, png_const_structp pp,
  7381. const transform_display *display)
  7382. {
  7383. if (that->bit_depth >= 8 &&
  7384. (that->colour_type == PNG_COLOR_TYPE_RGB ||
  7385. that->colour_type == PNG_COLOR_TYPE_GRAY))
  7386. {
  7387. unsigned int max = (1U << that->bit_depth)-1;
  7388. that->alpha = data.filler & max;
  7389. that->alphaf = ((double)that->alpha) / max;
  7390. that->alphae = 0;
  7391. /* The filler has been stored in the alpha channel, we must record
  7392. * that this has been done for the checking later on, the color
  7393. * type is faked to have an alpha channel, but libpng won't report
  7394. * this; the app has to know the extra channel is there and this
  7395. * was recording in standard_display::filler above.
  7396. */
  7397. that->colour_type |= 4; /* alpha added */
  7398. that->alpha_first = data.flags == PNG_FILLER_BEFORE;
  7399. }
  7400. this->next->mod(this->next, that, pp, display);
  7401. }
  7402. static int
  7403. image_transform_png_set_filler_add(image_transform *this,
  7404. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7405. {
  7406. this->next = *that;
  7407. *that = this;
  7408. return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
  7409. colour_type == PNG_COLOR_TYPE_GRAY);
  7410. }
  7411. #undef data
  7412. IT(filler);
  7413. #undef PT
  7414. #define PT ITSTRUCT(filler)
  7415. /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
  7416. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  7417. #define data ITDATA(add_alpha)
  7418. static struct
  7419. {
  7420. png_uint_32 filler;
  7421. int flags;
  7422. } data;
  7423. static void
  7424. image_transform_png_set_add_alpha_set(const image_transform *this,
  7425. transform_display *that, png_structp pp, png_infop pi)
  7426. {
  7427. /* Need a random choice for 'before' and 'after' as well as for the
  7428. * filler. The 'filler' value has all 32 bits set, but only bit_depth
  7429. * will be used. At this point we don't know bit_depth.
  7430. */
  7431. data.filler = random_u32();
  7432. data.flags = random_choice();
  7433. png_set_add_alpha(pp, data.filler, data.flags);
  7434. this->next->set(this->next, that, pp, pi);
  7435. }
  7436. static void
  7437. image_transform_png_set_add_alpha_mod(const image_transform *this,
  7438. image_pixel *that, png_const_structp pp,
  7439. const transform_display *display)
  7440. {
  7441. if (that->bit_depth >= 8 &&
  7442. (that->colour_type == PNG_COLOR_TYPE_RGB ||
  7443. that->colour_type == PNG_COLOR_TYPE_GRAY))
  7444. {
  7445. unsigned int max = (1U << that->bit_depth)-1;
  7446. that->alpha = data.filler & max;
  7447. that->alphaf = ((double)that->alpha) / max;
  7448. that->alphae = 0;
  7449. that->colour_type |= 4; /* alpha added */
  7450. that->alpha_first = data.flags == PNG_FILLER_BEFORE;
  7451. }
  7452. this->next->mod(this->next, that, pp, display);
  7453. }
  7454. static int
  7455. image_transform_png_set_add_alpha_add(image_transform *this,
  7456. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7457. {
  7458. this->next = *that;
  7459. *that = this;
  7460. return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
  7461. colour_type == PNG_COLOR_TYPE_GRAY);
  7462. }
  7463. #undef data
  7464. IT(add_alpha);
  7465. #undef PT
  7466. #define PT ITSTRUCT(add_alpha)
  7467. #endif /* PNG_READ_FILLER_SUPPORTED */
  7468. /* png_set_packing */
  7469. #ifdef PNG_READ_PACK_SUPPORTED
  7470. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
  7471. *
  7472. * png_set_packing(png_structrp png_ptr)
  7473. *
  7474. * This should only affect grayscale and palette images with less than 8 bits
  7475. * per pixel.
  7476. */
  7477. static void
  7478. image_transform_png_set_packing_set(const image_transform *this,
  7479. transform_display *that, png_structp pp, png_infop pi)
  7480. {
  7481. png_set_packing(pp);
  7482. that->unpacked = 1;
  7483. this->next->set(this->next, that, pp, pi);
  7484. }
  7485. static void
  7486. image_transform_png_set_packing_mod(const image_transform *this,
  7487. image_pixel *that, png_const_structp pp,
  7488. const transform_display *display)
  7489. {
  7490. /* The general expand case depends on what the colour type is,
  7491. * low bit-depth pixel values are unpacked into bytes without
  7492. * scaling, so sample_depth is not changed.
  7493. */
  7494. if (that->bit_depth < 8) /* grayscale or palette */
  7495. that->bit_depth = 8;
  7496. this->next->mod(this->next, that, pp, display);
  7497. }
  7498. static int
  7499. image_transform_png_set_packing_add(image_transform *this,
  7500. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7501. {
  7502. UNUSED(colour_type)
  7503. this->next = *that;
  7504. *that = this;
  7505. /* Nothing should happen unless the bit depth is less than 8: */
  7506. return bit_depth < 8;
  7507. }
  7508. IT(packing);
  7509. #undef PT
  7510. #define PT ITSTRUCT(packing)
  7511. #endif /* PNG_READ_PACK_SUPPORTED */
  7512. /* png_set_packswap */
  7513. #ifdef PNG_READ_PACKSWAP_SUPPORTED
  7514. /* Swap pixels packed into bytes; reverses the order on screen so that
  7515. * the high order bits correspond to the rightmost pixels.
  7516. *
  7517. * png_set_packswap(png_structrp png_ptr)
  7518. */
  7519. static void
  7520. image_transform_png_set_packswap_set(const image_transform *this,
  7521. transform_display *that, png_structp pp, png_infop pi)
  7522. {
  7523. png_set_packswap(pp);
  7524. that->this.littleendian = 1;
  7525. this->next->set(this->next, that, pp, pi);
  7526. }
  7527. static void
  7528. image_transform_png_set_packswap_mod(const image_transform *this,
  7529. image_pixel *that, png_const_structp pp,
  7530. const transform_display *display)
  7531. {
  7532. if (that->bit_depth < 8)
  7533. that->littleendian = 1;
  7534. this->next->mod(this->next, that, pp, display);
  7535. }
  7536. static int
  7537. image_transform_png_set_packswap_add(image_transform *this,
  7538. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7539. {
  7540. UNUSED(colour_type)
  7541. this->next = *that;
  7542. *that = this;
  7543. return bit_depth < 8;
  7544. }
  7545. IT(packswap);
  7546. #undef PT
  7547. #define PT ITSTRUCT(packswap)
  7548. #endif /* PNG_READ_PACKSWAP_SUPPORTED */
  7549. /* png_set_invert_mono */
  7550. #ifdef PNG_READ_INVERT_MONO_SUPPORTED
  7551. /* Invert the gray channel
  7552. *
  7553. * png_set_invert_mono(png_structrp png_ptr)
  7554. */
  7555. static void
  7556. image_transform_png_set_invert_mono_set(const image_transform *this,
  7557. transform_display *that, png_structp pp, png_infop pi)
  7558. {
  7559. png_set_invert_mono(pp);
  7560. this->next->set(this->next, that, pp, pi);
  7561. }
  7562. static void
  7563. image_transform_png_set_invert_mono_mod(const image_transform *this,
  7564. image_pixel *that, png_const_structp pp,
  7565. const transform_display *display)
  7566. {
  7567. if (that->colour_type & 4)
  7568. that->mono_inverted = 1;
  7569. this->next->mod(this->next, that, pp, display);
  7570. }
  7571. static int
  7572. image_transform_png_set_invert_mono_add(image_transform *this,
  7573. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7574. {
  7575. UNUSED(bit_depth)
  7576. this->next = *that;
  7577. *that = this;
  7578. /* Only has an effect on pixels with no colour: */
  7579. return (colour_type & 2) == 0;
  7580. }
  7581. IT(invert_mono);
  7582. #undef PT
  7583. #define PT ITSTRUCT(invert_mono)
  7584. #endif /* PNG_READ_INVERT_MONO_SUPPORTED */
  7585. #ifdef PNG_READ_SHIFT_SUPPORTED
  7586. /* png_set_shift(png_structp, png_const_color_8p true_bits)
  7587. *
  7588. * The output pixels will be shifted by the given true_bits
  7589. * values.
  7590. */
  7591. #define data ITDATA(shift)
  7592. static png_color_8 data;
  7593. static void
  7594. image_transform_png_set_shift_set(const image_transform *this,
  7595. transform_display *that, png_structp pp, png_infop pi)
  7596. {
  7597. /* Get a random set of shifts. The shifts need to do something
  7598. * to test the transform, so they are limited to the bit depth
  7599. * of the input image. Notice that in the following the 'gray'
  7600. * field is randomized independently. This acts as a check that
  7601. * libpng does use the correct field.
  7602. */
  7603. unsigned int depth = that->this.bit_depth;
  7604. data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7605. data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7606. data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7607. data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7608. data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7609. png_set_shift(pp, &data);
  7610. this->next->set(this->next, that, pp, pi);
  7611. }
  7612. static void
  7613. image_transform_png_set_shift_mod(const image_transform *this,
  7614. image_pixel *that, png_const_structp pp,
  7615. const transform_display *display)
  7616. {
  7617. /* Copy the correct values into the sBIT fields, libpng does not do
  7618. * anything to palette data:
  7619. */
  7620. if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
  7621. {
  7622. that->sig_bits = 1;
  7623. /* The sBIT fields are reset to the values previously sent to
  7624. * png_set_shift according to the colour type.
  7625. * does.
  7626. */
  7627. if (that->colour_type & 2) /* RGB channels */
  7628. {
  7629. that->red_sBIT = data.red;
  7630. that->green_sBIT = data.green;
  7631. that->blue_sBIT = data.blue;
  7632. }
  7633. else /* One grey channel */
  7634. that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
  7635. that->alpha_sBIT = data.alpha;
  7636. }
  7637. this->next->mod(this->next, that, pp, display);
  7638. }
  7639. static int
  7640. image_transform_png_set_shift_add(image_transform *this,
  7641. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7642. {
  7643. UNUSED(bit_depth)
  7644. this->next = *that;
  7645. *that = this;
  7646. return colour_type != PNG_COLOR_TYPE_PALETTE;
  7647. }
  7648. IT(shift);
  7649. #undef PT
  7650. #define PT ITSTRUCT(shift)
  7651. #endif /* PNG_READ_SHIFT_SUPPORTED */
  7652. #ifdef THIS_IS_THE_PROFORMA
  7653. static void
  7654. image_transform_png_set_@_set(const image_transform *this,
  7655. transform_display *that, png_structp pp, png_infop pi)
  7656. {
  7657. png_set_@(pp);
  7658. this->next->set(this->next, that, pp, pi);
  7659. }
  7660. static void
  7661. image_transform_png_set_@_mod(const image_transform *this,
  7662. image_pixel *that, png_const_structp pp,
  7663. const transform_display *display)
  7664. {
  7665. this->next->mod(this->next, that, pp, display);
  7666. }
  7667. static int
  7668. image_transform_png_set_@_add(image_transform *this,
  7669. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7670. {
  7671. this->next = *that;
  7672. *that = this;
  7673. return 1;
  7674. }
  7675. IT(@);
  7676. #endif
  7677. /* This may just be 'end' if all the transforms are disabled! */
  7678. static image_transform *const image_transform_first = &PT;
  7679. static void
  7680. transform_enable(const char *name)
  7681. {
  7682. /* Everything starts out enabled, so if we see an 'enable' disabled
  7683. * everything else the first time round.
  7684. */
  7685. static int all_disabled = 0;
  7686. int found_it = 0;
  7687. image_transform *list = image_transform_first;
  7688. while (list != &image_transform_end)
  7689. {
  7690. if (strcmp(list->name, name) == 0)
  7691. {
  7692. list->enable = 1;
  7693. found_it = 1;
  7694. }
  7695. else if (!all_disabled)
  7696. list->enable = 0;
  7697. list = list->list;
  7698. }
  7699. all_disabled = 1;
  7700. if (!found_it)
  7701. {
  7702. fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
  7703. name);
  7704. exit(99);
  7705. }
  7706. }
  7707. static void
  7708. transform_disable(const char *name)
  7709. {
  7710. image_transform *list = image_transform_first;
  7711. while (list != &image_transform_end)
  7712. {
  7713. if (strcmp(list->name, name) == 0)
  7714. {
  7715. list->enable = 0;
  7716. return;
  7717. }
  7718. list = list->list;
  7719. }
  7720. fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
  7721. name);
  7722. exit(99);
  7723. }
  7724. static void
  7725. image_transform_reset_count(void)
  7726. {
  7727. image_transform *next = image_transform_first;
  7728. int count = 0;
  7729. while (next != &image_transform_end)
  7730. {
  7731. next->local_use = 0;
  7732. next->next = 0;
  7733. next = next->list;
  7734. ++count;
  7735. }
  7736. /* This can only happen if we every have more than 32 transforms (excluding
  7737. * the end) in the list.
  7738. */
  7739. if (count > 32) abort();
  7740. }
  7741. static int
  7742. image_transform_test_counter(png_uint_32 counter, unsigned int max)
  7743. {
  7744. /* Test the list to see if there is any point continuing, given a current
  7745. * counter and a 'max' value.
  7746. */
  7747. image_transform *next = image_transform_first;
  7748. while (next != &image_transform_end)
  7749. {
  7750. /* For max 0 or 1 continue until the counter overflows: */
  7751. counter >>= 1;
  7752. /* Continue if any entry hasn't reacked the max. */
  7753. if (max > 1 && next->local_use < max)
  7754. return 1;
  7755. next = next->list;
  7756. }
  7757. return max <= 1 && counter == 0;
  7758. }
  7759. static png_uint_32
  7760. image_transform_add(const image_transform **this, unsigned int max,
  7761. png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
  7762. png_byte colour_type, png_byte bit_depth)
  7763. {
  7764. for (;;) /* until we manage to add something */
  7765. {
  7766. png_uint_32 mask;
  7767. image_transform *list;
  7768. /* Find the next counter value, if the counter is zero this is the start
  7769. * of the list. This routine always returns the current counter (not the
  7770. * next) so it returns 0 at the end and expects 0 at the beginning.
  7771. */
  7772. if (counter == 0) /* first time */
  7773. {
  7774. image_transform_reset_count();
  7775. if (max <= 1)
  7776. counter = 1;
  7777. else
  7778. counter = random_32();
  7779. }
  7780. else /* advance the counter */
  7781. {
  7782. switch (max)
  7783. {
  7784. case 0: ++counter; break;
  7785. case 1: counter <<= 1; break;
  7786. default: counter = random_32(); break;
  7787. }
  7788. }
  7789. /* Now add all these items, if possible */
  7790. *this = &image_transform_end;
  7791. list = image_transform_first;
  7792. mask = 1;
  7793. /* Go through the whole list adding anything that the counter selects: */
  7794. while (list != &image_transform_end)
  7795. {
  7796. if ((counter & mask) != 0 && list->enable &&
  7797. (max == 0 || list->local_use < max))
  7798. {
  7799. /* Candidate to add: */
  7800. if (list->add(list, this, colour_type, bit_depth) || max == 0)
  7801. {
  7802. /* Added, so add to the name too. */
  7803. *pos = safecat(name, sizeof_name, *pos, " +");
  7804. *pos = safecat(name, sizeof_name, *pos, list->name);
  7805. }
  7806. else
  7807. {
  7808. /* Not useful and max>0, so remove it from *this: */
  7809. *this = list->next;
  7810. list->next = 0;
  7811. /* And, since we know it isn't useful, stop it being added again
  7812. * in this run:
  7813. */
  7814. list->local_use = max;
  7815. }
  7816. }
  7817. mask <<= 1;
  7818. list = list->list;
  7819. }
  7820. /* Now if anything was added we have something to do. */
  7821. if (*this != &image_transform_end)
  7822. return counter;
  7823. /* Nothing added, but was there anything in there to add? */
  7824. if (!image_transform_test_counter(counter, max))
  7825. return 0;
  7826. }
  7827. }
  7828. static void
  7829. perform_transform_test(png_modifier *pm)
  7830. {
  7831. png_byte colour_type = 0;
  7832. png_byte bit_depth = 0;
  7833. unsigned int palette_number = 0;
  7834. while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
  7835. pm->test_tRNS))
  7836. {
  7837. png_uint_32 counter = 0;
  7838. size_t base_pos;
  7839. char name[64];
  7840. base_pos = safecat(name, sizeof name, 0, "transform:");
  7841. for (;;)
  7842. {
  7843. size_t pos = base_pos;
  7844. const image_transform *list = 0;
  7845. /* 'max' is currently hardwired to '1'; this should be settable on the
  7846. * command line.
  7847. */
  7848. counter = image_transform_add(&list, 1/*max*/, counter,
  7849. name, sizeof name, &pos, colour_type, bit_depth);
  7850. if (counter == 0)
  7851. break;
  7852. /* The command line can change this to checking interlaced images. */
  7853. do
  7854. {
  7855. pm->repeat = 0;
  7856. transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
  7857. pm->interlace_type, 0, 0, 0), list, name);
  7858. if (fail(pm))
  7859. return;
  7860. }
  7861. while (pm->repeat);
  7862. }
  7863. }
  7864. }
  7865. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  7866. /********************************* GAMMA TESTS ********************************/
  7867. #ifdef PNG_READ_GAMMA_SUPPORTED
  7868. /* Reader callbacks and implementations, where they differ from the standard
  7869. * ones.
  7870. */
  7871. typedef struct gamma_display
  7872. {
  7873. standard_display this;
  7874. /* Parameters */
  7875. png_modifier* pm;
  7876. double file_gamma;
  7877. double screen_gamma;
  7878. double background_gamma;
  7879. png_byte sbit;
  7880. int threshold_test;
  7881. int use_input_precision;
  7882. int scale16;
  7883. int expand16;
  7884. int do_background;
  7885. png_color_16 background_color;
  7886. /* Local variables */
  7887. double maxerrout;
  7888. double maxerrpc;
  7889. double maxerrabs;
  7890. } gamma_display;
  7891. #define ALPHA_MODE_OFFSET 4
  7892. static void
  7893. gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
  7894. double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
  7895. int use_input_precision, int scale16, int expand16,
  7896. int do_background, const png_color_16 *pointer_to_the_background_color,
  7897. double background_gamma)
  7898. {
  7899. /* Standard fields */
  7900. standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
  7901. pm->use_update_info);
  7902. /* Parameter fields */
  7903. dp->pm = pm;
  7904. dp->file_gamma = file_gamma;
  7905. dp->screen_gamma = screen_gamma;
  7906. dp->background_gamma = background_gamma;
  7907. dp->sbit = sbit;
  7908. dp->threshold_test = threshold_test;
  7909. dp->use_input_precision = use_input_precision;
  7910. dp->scale16 = scale16;
  7911. dp->expand16 = expand16;
  7912. dp->do_background = do_background;
  7913. if (do_background && pointer_to_the_background_color != 0)
  7914. dp->background_color = *pointer_to_the_background_color;
  7915. else
  7916. memset(&dp->background_color, 0, sizeof dp->background_color);
  7917. /* Local variable fields */
  7918. dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
  7919. }
  7920. static void
  7921. gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
  7922. {
  7923. /* Reuse the standard stuff as appropriate. */
  7924. standard_info_part1(&dp->this, pp, pi);
  7925. /* If requested strip 16 to 8 bits - this is handled automagically below
  7926. * because the output bit depth is read from the library. Note that there
  7927. * are interactions with sBIT but, internally, libpng makes sbit at most
  7928. * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
  7929. */
  7930. if (dp->scale16)
  7931. # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
  7932. png_set_scale_16(pp);
  7933. # else
  7934. /* The following works both in 1.5.4 and earlier versions: */
  7935. # ifdef PNG_READ_16_TO_8_SUPPORTED
  7936. png_set_strip_16(pp);
  7937. # else
  7938. png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
  7939. # endif
  7940. # endif
  7941. if (dp->expand16)
  7942. # ifdef PNG_READ_EXPAND_16_SUPPORTED
  7943. png_set_expand_16(pp);
  7944. # else
  7945. png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
  7946. # endif
  7947. if (dp->do_background >= ALPHA_MODE_OFFSET)
  7948. {
  7949. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7950. {
  7951. /* This tests the alpha mode handling, if supported. */
  7952. int mode = dp->do_background - ALPHA_MODE_OFFSET;
  7953. /* The gamma value is the output gamma, and is in the standard,
  7954. * non-inverted, representation. It provides a default for the PNG file
  7955. * gamma, but since the file has a gAMA chunk this does not matter.
  7956. */
  7957. const double sg = dp->screen_gamma;
  7958. # ifndef PNG_FLOATING_POINT_SUPPORTED
  7959. png_fixed_point g = fix(sg);
  7960. # endif
  7961. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7962. png_set_alpha_mode(pp, mode, sg);
  7963. # else
  7964. png_set_alpha_mode_fixed(pp, mode, g);
  7965. # endif
  7966. /* However, for the standard Porter-Duff algorithm the output defaults
  7967. * to be linear, so if the test requires non-linear output it must be
  7968. * corrected here.
  7969. */
  7970. if (mode == PNG_ALPHA_STANDARD && sg != 1)
  7971. {
  7972. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7973. png_set_gamma(pp, sg, dp->file_gamma);
  7974. # else
  7975. png_fixed_point f = fix(dp->file_gamma);
  7976. png_set_gamma_fixed(pp, g, f);
  7977. # endif
  7978. }
  7979. }
  7980. # else
  7981. png_error(pp, "alpha mode handling not supported");
  7982. # endif
  7983. }
  7984. else
  7985. {
  7986. /* Set up gamma processing. */
  7987. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7988. png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
  7989. # else
  7990. {
  7991. png_fixed_point s = fix(dp->screen_gamma);
  7992. png_fixed_point f = fix(dp->file_gamma);
  7993. png_set_gamma_fixed(pp, s, f);
  7994. }
  7995. # endif
  7996. if (dp->do_background)
  7997. {
  7998. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  7999. /* NOTE: this assumes the caller provided the correct background gamma!
  8000. */
  8001. const double bg = dp->background_gamma;
  8002. # ifndef PNG_FLOATING_POINT_SUPPORTED
  8003. png_fixed_point g = fix(bg);
  8004. # endif
  8005. # ifdef PNG_FLOATING_POINT_SUPPORTED
  8006. png_set_background(pp, &dp->background_color, dp->do_background,
  8007. 0/*need_expand*/, bg);
  8008. # else
  8009. png_set_background_fixed(pp, &dp->background_color,
  8010. dp->do_background, 0/*need_expand*/, g);
  8011. # endif
  8012. # else
  8013. png_error(pp, "png_set_background not supported");
  8014. # endif
  8015. }
  8016. }
  8017. {
  8018. int i = dp->this.use_update_info;
  8019. /* Always do one call, even if use_update_info is 0. */
  8020. do
  8021. png_read_update_info(pp, pi);
  8022. while (--i > 0);
  8023. }
  8024. /* Now we may get a different cbRow: */
  8025. standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
  8026. }
  8027. static void PNGCBAPI
  8028. gamma_info(png_structp pp, png_infop pi)
  8029. {
  8030. gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
  8031. pi);
  8032. }
  8033. /* Validate a single component value - the routine gets the input and output
  8034. * sample values as unscaled PNG component values along with a cache of all the
  8035. * information required to validate the values.
  8036. */
  8037. typedef struct validate_info
  8038. {
  8039. png_const_structp pp;
  8040. gamma_display *dp;
  8041. png_byte sbit;
  8042. int use_input_precision;
  8043. int do_background;
  8044. int scale16;
  8045. unsigned int sbit_max;
  8046. unsigned int isbit_shift;
  8047. unsigned int outmax;
  8048. double gamma_correction; /* Overall correction required. */
  8049. double file_inverse; /* Inverse of file gamma. */
  8050. double screen_gamma;
  8051. double screen_inverse; /* Inverse of screen gamma. */
  8052. double background_red; /* Linear background value, red or gray. */
  8053. double background_green;
  8054. double background_blue;
  8055. double maxabs;
  8056. double maxpc;
  8057. double maxcalc;
  8058. double maxout;
  8059. double maxout_total; /* Total including quantization error */
  8060. double outlog;
  8061. int outquant;
  8062. }
  8063. validate_info;
  8064. static void
  8065. init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
  8066. int in_depth, int out_depth)
  8067. {
  8068. unsigned int outmax = (1U<<out_depth)-1;
  8069. vi->pp = pp;
  8070. vi->dp = dp;
  8071. if (dp->sbit > 0 && dp->sbit < in_depth)
  8072. {
  8073. vi->sbit = dp->sbit;
  8074. vi->isbit_shift = in_depth - dp->sbit;
  8075. }
  8076. else
  8077. {
  8078. vi->sbit = (png_byte)in_depth;
  8079. vi->isbit_shift = 0;
  8080. }
  8081. vi->sbit_max = (1U << vi->sbit)-1;
  8082. /* This mimics the libpng threshold test, '0' is used to prevent gamma
  8083. * correction in the validation test.
  8084. */
  8085. vi->screen_gamma = dp->screen_gamma;
  8086. if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
  8087. vi->screen_gamma = vi->screen_inverse = 0;
  8088. else
  8089. vi->screen_inverse = 1/vi->screen_gamma;
  8090. vi->use_input_precision = dp->use_input_precision;
  8091. vi->outmax = outmax;
  8092. vi->maxabs = abserr(dp->pm, in_depth, out_depth);
  8093. vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
  8094. vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
  8095. vi->maxout = outerr(dp->pm, in_depth, out_depth);
  8096. vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
  8097. vi->maxout_total = vi->maxout + vi->outquant * .5;
  8098. vi->outlog = outlog(dp->pm, in_depth, out_depth);
  8099. if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
  8100. (dp->this.colour_type == 3 && dp->this.is_transparent) ||
  8101. ((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
  8102. dp->this.has_tRNS))
  8103. {
  8104. vi->do_background = dp->do_background;
  8105. if (vi->do_background != 0)
  8106. {
  8107. const double bg_inverse = 1/dp->background_gamma;
  8108. double r, g, b;
  8109. /* Caller must at least put the gray value into the red channel */
  8110. r = dp->background_color.red; r /= outmax;
  8111. g = dp->background_color.green; g /= outmax;
  8112. b = dp->background_color.blue; b /= outmax;
  8113. # if 0
  8114. /* libpng doesn't do this optimization, if we do pngvalid will fail.
  8115. */
  8116. if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
  8117. # endif
  8118. {
  8119. r = pow(r, bg_inverse);
  8120. g = pow(g, bg_inverse);
  8121. b = pow(b, bg_inverse);
  8122. }
  8123. vi->background_red = r;
  8124. vi->background_green = g;
  8125. vi->background_blue = b;
  8126. }
  8127. }
  8128. else /* Do not expect any background processing */
  8129. vi->do_background = 0;
  8130. if (vi->do_background == 0)
  8131. vi->background_red = vi->background_green = vi->background_blue = 0;
  8132. vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
  8133. if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
  8134. vi->gamma_correction = 0;
  8135. vi->file_inverse = 1/dp->file_gamma;
  8136. if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
  8137. vi->file_inverse = 0;
  8138. vi->scale16 = dp->scale16;
  8139. }
  8140. /* This function handles composition of a single non-alpha component. The
  8141. * argument is the input sample value, in the range 0..1, and the alpha value.
  8142. * The result is the composed, linear, input sample. If alpha is less than zero
  8143. * this is the alpha component and the function should not be called!
  8144. */
  8145. static double
  8146. gamma_component_compose(int do_background, double input_sample, double alpha,
  8147. double background, int *compose)
  8148. {
  8149. switch (do_background)
  8150. {
  8151. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  8152. case PNG_BACKGROUND_GAMMA_SCREEN:
  8153. case PNG_BACKGROUND_GAMMA_FILE:
  8154. case PNG_BACKGROUND_GAMMA_UNIQUE:
  8155. /* Standard PNG background processing. */
  8156. if (alpha < 1)
  8157. {
  8158. if (alpha > 0)
  8159. {
  8160. input_sample = input_sample * alpha + background * (1-alpha);
  8161. if (compose != NULL)
  8162. *compose = 1;
  8163. }
  8164. else
  8165. input_sample = background;
  8166. }
  8167. break;
  8168. #endif
  8169. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8170. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  8171. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  8172. /* The components are premultiplied in either case and the output is
  8173. * gamma encoded (to get standard Porter-Duff we expect the output
  8174. * gamma to be set to 1.0!)
  8175. */
  8176. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  8177. /* The optimization is that the partial-alpha entries are linear
  8178. * while the opaque pixels are gamma encoded, but this only affects the
  8179. * output encoding.
  8180. */
  8181. if (alpha < 1)
  8182. {
  8183. if (alpha > 0)
  8184. {
  8185. input_sample *= alpha;
  8186. if (compose != NULL)
  8187. *compose = 1;
  8188. }
  8189. else
  8190. input_sample = 0;
  8191. }
  8192. break;
  8193. #endif
  8194. default:
  8195. /* Standard cases where no compositing is done (so the component
  8196. * value is already correct.)
  8197. */
  8198. UNUSED(alpha)
  8199. UNUSED(background)
  8200. UNUSED(compose)
  8201. break;
  8202. }
  8203. return input_sample;
  8204. }
  8205. /* This API returns the encoded *input* component, in the range 0..1 */
  8206. static double
  8207. gamma_component_validate(const char *name, const validate_info *vi,
  8208. unsigned int id, unsigned int od,
  8209. const double alpha /* <0 for the alpha channel itself */,
  8210. const double background /* component background value */)
  8211. {
  8212. unsigned int isbit = id >> vi->isbit_shift;
  8213. unsigned int sbit_max = vi->sbit_max;
  8214. unsigned int outmax = vi->outmax;
  8215. int do_background = vi->do_background;
  8216. double i;
  8217. /* First check on the 'perfect' result obtained from the digitized input
  8218. * value, id, and compare this against the actual digitized result, 'od'.
  8219. * 'i' is the input result in the range 0..1:
  8220. */
  8221. i = isbit; i /= sbit_max;
  8222. /* Check for the fast route: if we don't do any background composition or if
  8223. * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
  8224. * just use the gamma_correction field to correct to the final output gamma.
  8225. */
  8226. if (alpha == 1 /* opaque pixel component */ || !do_background
  8227. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8228. || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
  8229. #endif
  8230. || (alpha < 0 /* alpha channel */
  8231. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8232. && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
  8233. #endif
  8234. ))
  8235. {
  8236. /* Then get the gamma corrected version of 'i' and compare to 'od', any
  8237. * error less than .5 is insignificant - just quantization of the output
  8238. * value to the nearest digital value (nevertheless the error is still
  8239. * recorded - it's interesting ;-)
  8240. */
  8241. double encoded_sample = i;
  8242. double encoded_error;
  8243. /* alpha less than 0 indicates the alpha channel, which is always linear
  8244. */
  8245. if (alpha >= 0 && vi->gamma_correction > 0)
  8246. encoded_sample = pow(encoded_sample, vi->gamma_correction);
  8247. encoded_sample *= outmax;
  8248. encoded_error = fabs(od-encoded_sample);
  8249. if (encoded_error > vi->dp->maxerrout)
  8250. vi->dp->maxerrout = encoded_error;
  8251. if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
  8252. return i;
  8253. }
  8254. /* The slow route - attempt to do linear calculations. */
  8255. /* There may be an error, or background processing is required, so calculate
  8256. * the actual sample values - unencoded light intensity values. Note that in
  8257. * practice these are not completely unencoded because they include a
  8258. * 'viewing correction' to decrease or (normally) increase the perceptual
  8259. * contrast of the image. There's nothing we can do about this - we don't
  8260. * know what it is - so assume the unencoded value is perceptually linear.
  8261. */
  8262. {
  8263. double input_sample = i; /* In range 0..1 */
  8264. double output, error, encoded_sample, encoded_error;
  8265. double es_lo, es_hi;
  8266. int compose = 0; /* Set to one if composition done */
  8267. int output_is_encoded; /* Set if encoded to screen gamma */
  8268. int log_max_error = 1; /* Check maximum error values */
  8269. png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */
  8270. /* Convert to linear light (with the above caveat.) The alpha channel is
  8271. * already linear.
  8272. */
  8273. if (alpha >= 0)
  8274. {
  8275. int tcompose;
  8276. if (vi->file_inverse > 0)
  8277. input_sample = pow(input_sample, vi->file_inverse);
  8278. /* Handle the compose processing: */
  8279. tcompose = 0;
  8280. input_sample = gamma_component_compose(do_background, input_sample,
  8281. alpha, background, &tcompose);
  8282. if (tcompose)
  8283. compose = 1;
  8284. }
  8285. /* And similarly for the output value, but we need to check the background
  8286. * handling to linearize it correctly.
  8287. */
  8288. output = od;
  8289. output /= outmax;
  8290. output_is_encoded = vi->screen_gamma > 0;
  8291. if (alpha < 0) /* The alpha channel */
  8292. {
  8293. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8294. if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
  8295. #endif
  8296. {
  8297. /* In all other cases the output alpha channel is linear already,
  8298. * don't log errors here, they are much larger in linear data.
  8299. */
  8300. output_is_encoded = 0;
  8301. log_max_error = 0;
  8302. }
  8303. }
  8304. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8305. else /* A component */
  8306. {
  8307. if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
  8308. alpha < 1) /* the optimized case - linear output */
  8309. {
  8310. if (alpha > 0) log_max_error = 0;
  8311. output_is_encoded = 0;
  8312. }
  8313. }
  8314. #endif
  8315. if (output_is_encoded)
  8316. output = pow(output, vi->screen_gamma);
  8317. /* Calculate (or recalculate) the encoded_sample value and repeat the
  8318. * check above (unnecessary if we took the fast route, but harmless.)
  8319. */
  8320. encoded_sample = input_sample;
  8321. if (output_is_encoded)
  8322. encoded_sample = pow(encoded_sample, vi->screen_inverse);
  8323. encoded_sample *= outmax;
  8324. encoded_error = fabs(od-encoded_sample);
  8325. /* Don't log errors in the alpha channel, or the 'optimized' case,
  8326. * neither are significant to the overall perception.
  8327. */
  8328. if (log_max_error && encoded_error > vi->dp->maxerrout)
  8329. vi->dp->maxerrout = encoded_error;
  8330. if (encoded_error < vi->maxout_total)
  8331. {
  8332. if (encoded_error < vi->outlog)
  8333. return i;
  8334. /* Test passed but error is bigger than the log limit, record why the
  8335. * test passed:
  8336. */
  8337. pass = "less than maxout:\n";
  8338. }
  8339. /* i: the original input value in the range 0..1
  8340. *
  8341. * pngvalid calculations:
  8342. * input_sample: linear result; i linearized and composed, range 0..1
  8343. * encoded_sample: encoded result; input_sample scaled to output bit depth
  8344. *
  8345. * libpng calculations:
  8346. * output: linear result; od scaled to 0..1 and linearized
  8347. * od: encoded result from libpng
  8348. */
  8349. /* Now we have the numbers for real errors, both absolute values as as a
  8350. * percentage of the correct value (output):
  8351. */
  8352. error = fabs(input_sample-output);
  8353. if (log_max_error && error > vi->dp->maxerrabs)
  8354. vi->dp->maxerrabs = error;
  8355. /* The following is an attempt to ignore the tendency of quantization to
  8356. * dominate the percentage errors for lower result values:
  8357. */
  8358. if (log_max_error && input_sample > .5)
  8359. {
  8360. double percentage_error = error/input_sample;
  8361. if (percentage_error > vi->dp->maxerrpc)
  8362. vi->dp->maxerrpc = percentage_error;
  8363. }
  8364. /* Now calculate the digitization limits for 'encoded_sample' using the
  8365. * 'max' values. Note that maxout is in the encoded space but maxpc and
  8366. * maxabs are in linear light space.
  8367. *
  8368. * First find the maximum error in linear light space, range 0..1:
  8369. */
  8370. {
  8371. double tmp = input_sample * vi->maxpc;
  8372. if (tmp < vi->maxabs) tmp = vi->maxabs;
  8373. /* If 'compose' is true the composition was done in linear space using
  8374. * integer arithmetic. This introduces an extra error of +/- 0.5 (at
  8375. * least) in the integer space used. 'maxcalc' records this, taking
  8376. * into account the possibility that even for 16 bit output 8 bit space
  8377. * may have been used.
  8378. */
  8379. if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
  8380. /* The 'maxout' value refers to the encoded result, to compare with
  8381. * this encode input_sample adjusted by the maximum error (tmp) above.
  8382. */
  8383. es_lo = encoded_sample - vi->maxout;
  8384. if (es_lo > 0 && input_sample-tmp > 0)
  8385. {
  8386. double low_value = input_sample-tmp;
  8387. if (output_is_encoded)
  8388. low_value = pow(low_value, vi->screen_inverse);
  8389. low_value *= outmax;
  8390. if (low_value < es_lo) es_lo = low_value;
  8391. /* Quantize this appropriately: */
  8392. es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
  8393. }
  8394. else
  8395. es_lo = 0;
  8396. es_hi = encoded_sample + vi->maxout;
  8397. if (es_hi < outmax && input_sample+tmp < 1)
  8398. {
  8399. double high_value = input_sample+tmp;
  8400. if (output_is_encoded)
  8401. high_value = pow(high_value, vi->screen_inverse);
  8402. high_value *= outmax;
  8403. if (high_value > es_hi) es_hi = high_value;
  8404. es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
  8405. }
  8406. else
  8407. es_hi = outmax;
  8408. }
  8409. /* The primary test is that the final encoded value returned by the
  8410. * library should be between the two limits (inclusive) that were
  8411. * calculated above.
  8412. */
  8413. if (od >= es_lo && od <= es_hi)
  8414. {
  8415. /* The value passes, but we may need to log the information anyway. */
  8416. if (encoded_error < vi->outlog)
  8417. return i;
  8418. if (pass == 0)
  8419. pass = "within digitization limits:\n";
  8420. }
  8421. {
  8422. /* There has been an error in processing, or we need to log this
  8423. * value.
  8424. */
  8425. double is_lo, is_hi;
  8426. /* pass is set at this point if either of the tests above would have
  8427. * passed. Don't do these additional tests here - just log the
  8428. * original [es_lo..es_hi] values.
  8429. */
  8430. if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
  8431. {
  8432. /* Ok, something is wrong - this actually happens in current libpng
  8433. * 16-to-8 processing. Assume that the input value (id, adjusted
  8434. * for sbit) can be anywhere between value-.5 and value+.5 - quite a
  8435. * large range if sbit is low.
  8436. *
  8437. * NOTE: at present because the libpng gamma table stuff has been
  8438. * changed to use a rounding algorithm to correct errors in 8-bit
  8439. * calculations the precise sbit calculation (a shift) has been
  8440. * lost. This can result in up to a +/-1 error in the presence of
  8441. * an sbit less than the bit depth.
  8442. */
  8443. # if PNG_LIBPNG_VER != 10700
  8444. # define SBIT_ERROR .5
  8445. # else
  8446. # define SBIT_ERROR 1.
  8447. # endif
  8448. double tmp = (isbit - SBIT_ERROR)/sbit_max;
  8449. if (tmp <= 0)
  8450. tmp = 0;
  8451. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  8452. tmp = pow(tmp, vi->file_inverse);
  8453. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  8454. NULL);
  8455. if (output_is_encoded && tmp > 0 && tmp < 1)
  8456. tmp = pow(tmp, vi->screen_inverse);
  8457. is_lo = ceil(outmax * tmp - vi->maxout_total);
  8458. if (is_lo < 0)
  8459. is_lo = 0;
  8460. tmp = (isbit + SBIT_ERROR)/sbit_max;
  8461. if (tmp >= 1)
  8462. tmp = 1;
  8463. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  8464. tmp = pow(tmp, vi->file_inverse);
  8465. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  8466. NULL);
  8467. if (output_is_encoded && tmp > 0 && tmp < 1)
  8468. tmp = pow(tmp, vi->screen_inverse);
  8469. is_hi = floor(outmax * tmp + vi->maxout_total);
  8470. if (is_hi > outmax)
  8471. is_hi = outmax;
  8472. if (!(od < is_lo || od > is_hi))
  8473. {
  8474. if (encoded_error < vi->outlog)
  8475. return i;
  8476. pass = "within input precision limits:\n";
  8477. }
  8478. /* One last chance. If this is an alpha channel and the 16to8
  8479. * option has been used and 'inaccurate' scaling is used then the
  8480. * bit reduction is obtained by simply using the top 8 bits of the
  8481. * value.
  8482. *
  8483. * This is only done for older libpng versions when the 'inaccurate'
  8484. * (chop) method of scaling was used.
  8485. */
  8486. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  8487. # if PNG_LIBPNG_VER < 10504
  8488. /* This may be required for other components in the future,
  8489. * but at present the presence of gamma correction effectively
  8490. * prevents the errors in the component scaling (I don't quite
  8491. * understand why, but since it's better this way I care not
  8492. * to ask, JB 20110419.)
  8493. */
  8494. if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
  8495. vi->sbit + vi->isbit_shift == 16)
  8496. {
  8497. tmp = ((id >> 8) - .5)/255;
  8498. if (tmp > 0)
  8499. {
  8500. is_lo = ceil(outmax * tmp - vi->maxout_total);
  8501. if (is_lo < 0) is_lo = 0;
  8502. }
  8503. else
  8504. is_lo = 0;
  8505. tmp = ((id >> 8) + .5)/255;
  8506. if (tmp < 1)
  8507. {
  8508. is_hi = floor(outmax * tmp + vi->maxout_total);
  8509. if (is_hi > outmax) is_hi = outmax;
  8510. }
  8511. else
  8512. is_hi = outmax;
  8513. if (!(od < is_lo || od > is_hi))
  8514. {
  8515. if (encoded_error < vi->outlog)
  8516. return i;
  8517. pass = "within 8 bit limits:\n";
  8518. }
  8519. }
  8520. # endif
  8521. # endif
  8522. }
  8523. else /* !use_input_precision */
  8524. is_lo = es_lo, is_hi = es_hi;
  8525. /* Attempt to output a meaningful error/warning message: the message
  8526. * output depends on the background/composite operation being performed
  8527. * because this changes what parameters were actually used above.
  8528. */
  8529. {
  8530. size_t pos = 0;
  8531. /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
  8532. * places. Just use outmax to work out which.
  8533. */
  8534. int precision = (outmax >= 1000 ? 6 : 3);
  8535. int use_input=1, use_background=0, do_compose=0;
  8536. char msg[256];
  8537. if (pass != 0)
  8538. pos = safecat(msg, sizeof msg, pos, "\n\t");
  8539. /* Set up the various flags, the output_is_encoded flag above
  8540. * is also used below. do_compose is just a double check.
  8541. */
  8542. switch (do_background)
  8543. {
  8544. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  8545. case PNG_BACKGROUND_GAMMA_SCREEN:
  8546. case PNG_BACKGROUND_GAMMA_FILE:
  8547. case PNG_BACKGROUND_GAMMA_UNIQUE:
  8548. use_background = (alpha >= 0 && alpha < 1);
  8549. # endif
  8550. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8551. /* FALLTHROUGH */
  8552. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  8553. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  8554. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  8555. # endif /* ALPHA_MODE_SUPPORTED */
  8556. # if (defined PNG_READ_BACKGROUND_SUPPORTED) ||\
  8557. (defined PNG_READ_ALPHA_MODE_SUPPORTED)
  8558. do_compose = (alpha > 0 && alpha < 1);
  8559. use_input = (alpha != 0);
  8560. break;
  8561. # endif
  8562. default:
  8563. break;
  8564. }
  8565. /* Check the 'compose' flag */
  8566. if (compose != do_compose)
  8567. png_error(vi->pp, "internal error (compose)");
  8568. /* 'name' is the component name */
  8569. pos = safecat(msg, sizeof msg, pos, name);
  8570. pos = safecat(msg, sizeof msg, pos, "(");
  8571. pos = safecatn(msg, sizeof msg, pos, id);
  8572. if (use_input || pass != 0/*logging*/)
  8573. {
  8574. if (isbit != id)
  8575. {
  8576. /* sBIT has reduced the precision of the input: */
  8577. pos = safecat(msg, sizeof msg, pos, ", sbit(");
  8578. pos = safecatn(msg, sizeof msg, pos, vi->sbit);
  8579. pos = safecat(msg, sizeof msg, pos, "): ");
  8580. pos = safecatn(msg, sizeof msg, pos, isbit);
  8581. }
  8582. pos = safecat(msg, sizeof msg, pos, "/");
  8583. /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
  8584. pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
  8585. }
  8586. pos = safecat(msg, sizeof msg, pos, ")");
  8587. /* A component may have been multiplied (in linear space) by the
  8588. * alpha value, 'compose' says whether this is relevant.
  8589. */
  8590. if (compose || pass != 0)
  8591. {
  8592. /* If any form of composition is being done report our
  8593. * calculated linear value here (the code above doesn't record
  8594. * the input value before composition is performed, so what
  8595. * gets reported is the value after composition.)
  8596. */
  8597. if (use_input || pass != 0)
  8598. {
  8599. if (vi->file_inverse > 0)
  8600. {
  8601. pos = safecat(msg, sizeof msg, pos, "^");
  8602. pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
  8603. }
  8604. else
  8605. pos = safecat(msg, sizeof msg, pos, "[linear]");
  8606. pos = safecat(msg, sizeof msg, pos, "*(alpha)");
  8607. pos = safecatd(msg, sizeof msg, pos, alpha, precision);
  8608. }
  8609. /* Now record the *linear* background value if it was used
  8610. * (this function is not passed the original, non-linear,
  8611. * value but it is contained in the test name.)
  8612. */
  8613. if (use_background)
  8614. {
  8615. pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
  8616. pos = safecat(msg, sizeof msg, pos, "(background)");
  8617. pos = safecatd(msg, sizeof msg, pos, background, precision);
  8618. pos = safecat(msg, sizeof msg, pos, "*");
  8619. pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
  8620. }
  8621. }
  8622. /* Report the calculated value (input_sample) and the linearized
  8623. * libpng value (output) unless this is just a component gamma
  8624. * correction.
  8625. */
  8626. if (compose || alpha < 0 || pass != 0)
  8627. {
  8628. pos = safecat(msg, sizeof msg, pos,
  8629. pass != 0 ? " =\n\t" : " = ");
  8630. pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
  8631. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  8632. pos = safecatd(msg, sizeof msg, pos, output, precision);
  8633. pos = safecat(msg, sizeof msg, pos, ")");
  8634. /* Finally report the output gamma encoding, if any. */
  8635. if (output_is_encoded)
  8636. {
  8637. pos = safecat(msg, sizeof msg, pos, " ^");
  8638. pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
  8639. pos = safecat(msg, sizeof msg, pos, "(to screen) =");
  8640. }
  8641. else
  8642. pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
  8643. }
  8644. if ((!compose && alpha >= 0) || pass != 0)
  8645. {
  8646. if (pass != 0) /* logging */
  8647. pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
  8648. /* This is the non-composition case, the internal linear
  8649. * values are irrelevant (though the log below will reveal
  8650. * them.) Output a much shorter warning/error message and report
  8651. * the overall gamma correction.
  8652. */
  8653. if (vi->gamma_correction > 0)
  8654. {
  8655. pos = safecat(msg, sizeof msg, pos, " ^");
  8656. pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
  8657. pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
  8658. }
  8659. else
  8660. pos = safecat(msg, sizeof msg, pos,
  8661. " [no gamma correction] =");
  8662. if (pass != 0)
  8663. pos = safecat(msg, sizeof msg, pos, "]");
  8664. }
  8665. /* This is our calculated encoded_sample which should (but does
  8666. * not) match od:
  8667. */
  8668. pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
  8669. pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
  8670. pos = safecat(msg, sizeof msg, pos, " < ");
  8671. pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
  8672. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  8673. pos = safecatn(msg, sizeof msg, pos, od);
  8674. pos = safecat(msg, sizeof msg, pos, ")");
  8675. pos = safecat(msg, sizeof msg, pos, "/");
  8676. pos = safecatn(msg, sizeof msg, pos, outmax);
  8677. pos = safecat(msg, sizeof msg, pos, " < ");
  8678. pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
  8679. if (pass == 0) /* The error condition */
  8680. {
  8681. # ifdef PNG_WARNINGS_SUPPORTED
  8682. png_warning(vi->pp, msg);
  8683. # else
  8684. store_warning(vi->pp, msg);
  8685. # endif
  8686. }
  8687. else /* logging this value */
  8688. store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
  8689. }
  8690. }
  8691. }
  8692. return i;
  8693. }
  8694. static void
  8695. gamma_image_validate(gamma_display *dp, png_const_structp pp,
  8696. png_infop pi)
  8697. {
  8698. /* Get some constants derived from the input and output file formats: */
  8699. const png_store* const ps = dp->this.ps;
  8700. png_byte in_ct = dp->this.colour_type;
  8701. png_byte in_bd = dp->this.bit_depth;
  8702. png_uint_32 w = dp->this.w;
  8703. png_uint_32 h = dp->this.h;
  8704. const size_t cbRow = dp->this.cbRow;
  8705. png_byte out_ct = png_get_color_type(pp, pi);
  8706. png_byte out_bd = png_get_bit_depth(pp, pi);
  8707. /* There are three sources of error, firstly the quantization in the
  8708. * file encoding, determined by sbit and/or the file depth, secondly
  8709. * the output (screen) gamma and thirdly the output file encoding.
  8710. *
  8711. * Since this API receives the screen and file gamma in double
  8712. * precision it is possible to calculate an exact answer given an input
  8713. * pixel value. Therefore we assume that the *input* value is exact -
  8714. * sample/maxsample - calculate the corresponding gamma corrected
  8715. * output to the limits of double precision arithmetic and compare with
  8716. * what libpng returns.
  8717. *
  8718. * Since the library must quantize the output to 8 or 16 bits there is
  8719. * a fundamental limit on the accuracy of the output of +/-.5 - this
  8720. * quantization limit is included in addition to the other limits
  8721. * specified by the parameters to the API. (Effectively, add .5
  8722. * everywhere.)
  8723. *
  8724. * The behavior of the 'sbit' parameter is defined by section 12.5
  8725. * (sample depth scaling) of the PNG spec. That section forces the
  8726. * decoder to assume that the PNG values have been scaled if sBIT is
  8727. * present:
  8728. *
  8729. * png-sample = floor( input-sample * (max-out/max-in) + .5);
  8730. *
  8731. * This means that only a subset of the possible PNG values should
  8732. * appear in the input. However, the spec allows the encoder to use a
  8733. * variety of approximations to the above and doesn't require any
  8734. * restriction of the values produced.
  8735. *
  8736. * Nevertheless the spec requires that the upper 'sBIT' bits of the
  8737. * value stored in a PNG file be the original sample bits.
  8738. * Consequently the code below simply scales the top sbit bits by
  8739. * (1<<sbit)-1 to obtain an original sample value.
  8740. *
  8741. * Because there is limited precision in the input it is arguable that
  8742. * an acceptable result is any valid result from input-.5 to input+.5.
  8743. * The basic tests below do not do this, however if 'use_input_precision'
  8744. * is set a subsequent test is performed above.
  8745. */
  8746. unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
  8747. int processing;
  8748. png_uint_32 y;
  8749. const store_palette_entry *in_palette = dp->this.palette;
  8750. int in_is_transparent = dp->this.is_transparent;
  8751. int process_tRNS;
  8752. int out_npalette = -1;
  8753. int out_is_transparent = 0; /* Just refers to the palette case */
  8754. store_palette out_palette;
  8755. validate_info vi;
  8756. /* Check for row overwrite errors */
  8757. store_image_check(dp->this.ps, pp, 0);
  8758. /* Supply the input and output sample depths here - 8 for an indexed image,
  8759. * otherwise the bit depth.
  8760. */
  8761. init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
  8762. processing = (vi.gamma_correction > 0 && !dp->threshold_test)
  8763. || in_bd != out_bd || in_ct != out_ct || vi.do_background;
  8764. process_tRNS = dp->this.has_tRNS && vi.do_background;
  8765. /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
  8766. * the palette there is no way of finding out, because libpng fails to
  8767. * update the palette on png_read_update_info. Indeed, libpng doesn't
  8768. * even do the required work until much later, when it doesn't have any
  8769. * info pointer. Oops. For the moment 'processing' is turned off if
  8770. * out_ct is palette.
  8771. */
  8772. if (in_ct == 3 && out_ct == 3)
  8773. processing = 0;
  8774. if (processing && out_ct == 3)
  8775. out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
  8776. for (y=0; y<h; ++y)
  8777. {
  8778. png_const_bytep pRow = store_image_row(ps, pp, 0, y);
  8779. png_byte std[STANDARD_ROWMAX];
  8780. transform_row(pp, std, in_ct, in_bd, y);
  8781. if (processing)
  8782. {
  8783. unsigned int x;
  8784. for (x=0; x<w; ++x)
  8785. {
  8786. double alpha = 1; /* serves as a flag value */
  8787. /* Record the palette index for index images. */
  8788. unsigned int in_index =
  8789. in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256;
  8790. unsigned int out_index =
  8791. out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256;
  8792. /* Handle input alpha - png_set_background will cause the output
  8793. * alpha to disappear so there is nothing to check.
  8794. */
  8795. if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 ||
  8796. (in_ct == 3 && in_is_transparent))
  8797. {
  8798. unsigned int input_alpha = in_ct == 3 ?
  8799. dp->this.palette[in_index].alpha :
  8800. sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0);
  8801. unsigned int output_alpha = 65536 /* as a flag value */;
  8802. if (out_ct == 3)
  8803. {
  8804. if (out_is_transparent)
  8805. output_alpha = out_palette[out_index].alpha;
  8806. }
  8807. else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
  8808. output_alpha = sample(pRow, out_ct, out_bd, x,
  8809. samples_per_pixel, 0, 0);
  8810. if (output_alpha != 65536)
  8811. alpha = gamma_component_validate("alpha", &vi, input_alpha,
  8812. output_alpha, -1/*alpha*/, 0/*background*/);
  8813. else /* no alpha in output */
  8814. {
  8815. /* This is a copy of the calculation of 'i' above in order to
  8816. * have the alpha value to use in the background calculation.
  8817. */
  8818. alpha = input_alpha >> vi.isbit_shift;
  8819. alpha /= vi.sbit_max;
  8820. }
  8821. }
  8822. else if (process_tRNS)
  8823. {
  8824. /* alpha needs to be set appropriately for this pixel, it is
  8825. * currently 1 and needs to be 0 for an input pixel which matches
  8826. * the values in tRNS.
  8827. */
  8828. switch (in_ct)
  8829. {
  8830. case 0: /* gray */
  8831. if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
  8832. dp->this.transparent.red)
  8833. alpha = 0;
  8834. break;
  8835. case 2: /* RGB */
  8836. if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
  8837. dp->this.transparent.red &&
  8838. sample(std, in_ct, in_bd, x, 1, 0, 0) ==
  8839. dp->this.transparent.green &&
  8840. sample(std, in_ct, in_bd, x, 2, 0, 0) ==
  8841. dp->this.transparent.blue)
  8842. alpha = 0;
  8843. break;
  8844. default:
  8845. break;
  8846. }
  8847. }
  8848. /* Handle grayscale or RGB components. */
  8849. if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
  8850. (void)gamma_component_validate("gray", &vi,
  8851. sample(std, in_ct, in_bd, x, 0, 0, 0),
  8852. sample(pRow, out_ct, out_bd, x, 0, 0, 0),
  8853. alpha/*component*/, vi.background_red);
  8854. else /* RGB or palette */
  8855. {
  8856. (void)gamma_component_validate("red", &vi,
  8857. in_ct == 3 ? in_palette[in_index].red :
  8858. sample(std, in_ct, in_bd, x, 0, 0, 0),
  8859. out_ct == 3 ? out_palette[out_index].red :
  8860. sample(pRow, out_ct, out_bd, x, 0, 0, 0),
  8861. alpha/*component*/, vi.background_red);
  8862. (void)gamma_component_validate("green", &vi,
  8863. in_ct == 3 ? in_palette[in_index].green :
  8864. sample(std, in_ct, in_bd, x, 1, 0, 0),
  8865. out_ct == 3 ? out_palette[out_index].green :
  8866. sample(pRow, out_ct, out_bd, x, 1, 0, 0),
  8867. alpha/*component*/, vi.background_green);
  8868. (void)gamma_component_validate("blue", &vi,
  8869. in_ct == 3 ? in_palette[in_index].blue :
  8870. sample(std, in_ct, in_bd, x, 2, 0, 0),
  8871. out_ct == 3 ? out_palette[out_index].blue :
  8872. sample(pRow, out_ct, out_bd, x, 2, 0, 0),
  8873. alpha/*component*/, vi.background_blue);
  8874. }
  8875. }
  8876. }
  8877. else if (memcmp(std, pRow, cbRow) != 0)
  8878. {
  8879. char msg[64];
  8880. /* No transform is expected on the threshold tests. */
  8881. sprintf(msg, "gamma: below threshold row %lu changed",
  8882. (unsigned long)y);
  8883. png_error(pp, msg);
  8884. }
  8885. } /* row (y) loop */
  8886. dp->this.ps->validated = 1;
  8887. }
  8888. static void PNGCBAPI
  8889. gamma_end(png_structp ppIn, png_infop pi)
  8890. {
  8891. png_const_structp pp = ppIn;
  8892. gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
  8893. if (!dp->this.speed)
  8894. gamma_image_validate(dp, pp, pi);
  8895. else
  8896. dp->this.ps->validated = 1;
  8897. }
  8898. /* A single test run checking a gamma transformation.
  8899. *
  8900. * maxabs: maximum absolute error as a fraction
  8901. * maxout: maximum output error in the output units
  8902. * maxpc: maximum percentage error (as a percentage)
  8903. */
  8904. static void
  8905. gamma_test(png_modifier *pmIn, png_byte colour_typeIn,
  8906. png_byte bit_depthIn, int palette_numberIn,
  8907. int interlace_typeIn,
  8908. const double file_gammaIn, const double screen_gammaIn,
  8909. png_byte sbitIn, int threshold_testIn,
  8910. const char *name,
  8911. int use_input_precisionIn, int scale16In,
  8912. int expand16In, int do_backgroundIn,
  8913. const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
  8914. {
  8915. gamma_display d;
  8916. context(&pmIn->this, fault);
  8917. gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
  8918. palette_numberIn, interlace_typeIn, 0, 0, 0),
  8919. file_gammaIn, screen_gammaIn, sbitIn,
  8920. threshold_testIn, use_input_precisionIn, scale16In,
  8921. expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
  8922. Try
  8923. {
  8924. png_structp pp;
  8925. png_infop pi;
  8926. gama_modification gama_mod;
  8927. srgb_modification srgb_mod;
  8928. sbit_modification sbit_mod;
  8929. /* For the moment don't use the png_modifier support here. */
  8930. d.pm->encoding_counter = 0;
  8931. modifier_set_encoding(d.pm); /* Just resets everything */
  8932. d.pm->current_gamma = d.file_gamma;
  8933. /* Make an appropriate modifier to set the PNG file gamma to the
  8934. * given gamma value and the sBIT chunk to the given precision.
  8935. */
  8936. d.pm->modifications = NULL;
  8937. gama_modification_init(&gama_mod, d.pm, d.file_gamma);
  8938. srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
  8939. if (d.sbit > 0)
  8940. sbit_modification_init(&sbit_mod, d.pm, d.sbit);
  8941. modification_reset(d.pm->modifications);
  8942. /* Get a png_struct for reading the image. */
  8943. pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
  8944. standard_palette_init(&d.this);
  8945. /* Introduce the correct read function. */
  8946. if (d.pm->this.progressive)
  8947. {
  8948. /* Share the row function with the standard implementation. */
  8949. png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
  8950. gamma_end);
  8951. /* Now feed data into the reader until we reach the end: */
  8952. modifier_progressive_read(d.pm, pp, pi);
  8953. }
  8954. else
  8955. {
  8956. /* modifier_read expects a png_modifier* */
  8957. png_set_read_fn(pp, d.pm, modifier_read);
  8958. /* Check the header values: */
  8959. png_read_info(pp, pi);
  8960. /* Process the 'info' requirements. Only one image is generated */
  8961. gamma_info_imp(&d, pp, pi);
  8962. sequential_row(&d.this, pp, pi, -1, 0);
  8963. if (!d.this.speed)
  8964. gamma_image_validate(&d, pp, pi);
  8965. else
  8966. d.this.ps->validated = 1;
  8967. }
  8968. modifier_reset(d.pm);
  8969. if (d.pm->log && !d.threshold_test && !d.this.speed)
  8970. fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
  8971. d.this.bit_depth, colour_types[d.this.colour_type], name,
  8972. d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
  8973. /* Log the summary values too. */
  8974. if (d.this.colour_type == 0 || d.this.colour_type == 4)
  8975. {
  8976. switch (d.this.bit_depth)
  8977. {
  8978. case 1:
  8979. break;
  8980. case 2:
  8981. if (d.maxerrout > d.pm->error_gray_2)
  8982. d.pm->error_gray_2 = d.maxerrout;
  8983. break;
  8984. case 4:
  8985. if (d.maxerrout > d.pm->error_gray_4)
  8986. d.pm->error_gray_4 = d.maxerrout;
  8987. break;
  8988. case 8:
  8989. if (d.maxerrout > d.pm->error_gray_8)
  8990. d.pm->error_gray_8 = d.maxerrout;
  8991. break;
  8992. case 16:
  8993. if (d.maxerrout > d.pm->error_gray_16)
  8994. d.pm->error_gray_16 = d.maxerrout;
  8995. break;
  8996. default:
  8997. png_error(pp, "bad bit depth (internal: 1)");
  8998. }
  8999. }
  9000. else if (d.this.colour_type == 2 || d.this.colour_type == 6)
  9001. {
  9002. switch (d.this.bit_depth)
  9003. {
  9004. case 8:
  9005. if (d.maxerrout > d.pm->error_color_8)
  9006. d.pm->error_color_8 = d.maxerrout;
  9007. break;
  9008. case 16:
  9009. if (d.maxerrout > d.pm->error_color_16)
  9010. d.pm->error_color_16 = d.maxerrout;
  9011. break;
  9012. default:
  9013. png_error(pp, "bad bit depth (internal: 2)");
  9014. }
  9015. }
  9016. else if (d.this.colour_type == 3)
  9017. {
  9018. if (d.maxerrout > d.pm->error_indexed)
  9019. d.pm->error_indexed = d.maxerrout;
  9020. }
  9021. }
  9022. Catch(fault)
  9023. modifier_reset(voidcast(png_modifier*,(void*)fault));
  9024. }
  9025. static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
  9026. png_byte bit_depth, int interlace_type, double file_gamma,
  9027. double screen_gamma)
  9028. {
  9029. size_t pos = 0;
  9030. char name[64];
  9031. pos = safecat(name, sizeof name, pos, "threshold ");
  9032. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  9033. pos = safecat(name, sizeof name, pos, "/");
  9034. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  9035. (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
  9036. file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
  9037. 0 /*no input precision*/,
  9038. 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
  9039. 0 /*no background gamma*/);
  9040. }
  9041. static void
  9042. perform_gamma_threshold_tests(png_modifier *pm)
  9043. {
  9044. png_byte colour_type = 0;
  9045. png_byte bit_depth = 0;
  9046. unsigned int palette_number = 0;
  9047. /* Don't test more than one instance of each palette - it's pointless, in
  9048. * fact this test is somewhat excessive since libpng doesn't make this
  9049. * decision based on colour type or bit depth!
  9050. *
  9051. * CHANGED: now test two palettes and, as a side effect, images with and
  9052. * without tRNS.
  9053. */
  9054. while (next_format(&colour_type, &bit_depth, &palette_number,
  9055. pm->test_lbg_gamma_threshold, pm->test_tRNS))
  9056. if (palette_number < 2)
  9057. {
  9058. double test_gamma = 1.0;
  9059. while (test_gamma >= .4)
  9060. {
  9061. /* There's little point testing the interlacing vs non-interlacing,
  9062. * but this can be set from the command line.
  9063. */
  9064. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  9065. test_gamma, 1/test_gamma);
  9066. test_gamma *= .95;
  9067. }
  9068. /* And a special test for sRGB */
  9069. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  9070. .45455, 2.2);
  9071. if (fail(pm))
  9072. return;
  9073. }
  9074. }
  9075. static void gamma_transform_test(png_modifier *pm,
  9076. png_byte colour_type, png_byte bit_depth,
  9077. int palette_number,
  9078. int interlace_type, const double file_gamma,
  9079. const double screen_gamma, png_byte sbit,
  9080. int use_input_precision, int scale16)
  9081. {
  9082. size_t pos = 0;
  9083. char name[64];
  9084. if (sbit != bit_depth && sbit != 0)
  9085. {
  9086. pos = safecat(name, sizeof name, pos, "sbit(");
  9087. pos = safecatn(name, sizeof name, pos, sbit);
  9088. pos = safecat(name, sizeof name, pos, ") ");
  9089. }
  9090. else
  9091. pos = safecat(name, sizeof name, pos, "gamma ");
  9092. if (scale16)
  9093. pos = safecat(name, sizeof name, pos, "16to8 ");
  9094. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  9095. pos = safecat(name, sizeof name, pos, "->");
  9096. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  9097. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  9098. file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
  9099. scale16, pm->test_gamma_expand16, 0 , 0, 0);
  9100. }
  9101. static void perform_gamma_transform_tests(png_modifier *pm)
  9102. {
  9103. png_byte colour_type = 0;
  9104. png_byte bit_depth = 0;
  9105. unsigned int palette_number = 0;
  9106. while (next_format(&colour_type, &bit_depth, &palette_number,
  9107. pm->test_lbg_gamma_transform, pm->test_tRNS))
  9108. {
  9109. unsigned int i, j;
  9110. for (i=0; i<pm->ngamma_tests; ++i)
  9111. {
  9112. for (j=0; j<pm->ngamma_tests; ++j)
  9113. {
  9114. if (i != j)
  9115. {
  9116. gamma_transform_test(pm, colour_type, bit_depth, palette_number,
  9117. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  9118. 0/*sBIT*/, pm->use_input_precision, 0/*do not scale16*/);
  9119. if (fail(pm))
  9120. return;
  9121. }
  9122. }
  9123. }
  9124. }
  9125. }
  9126. static void perform_gamma_sbit_tests(png_modifier *pm)
  9127. {
  9128. png_byte sbit;
  9129. /* The only interesting cases are colour and grayscale, alpha is ignored here
  9130. * for overall speed. Only bit depths where sbit is less than the bit depth
  9131. * are tested.
  9132. */
  9133. for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
  9134. {
  9135. png_byte colour_type = 0, bit_depth = 0;
  9136. unsigned int npalette = 0;
  9137. while (next_format(&colour_type, &bit_depth, &npalette,
  9138. pm->test_lbg_gamma_sbit, pm->test_tRNS))
  9139. if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
  9140. ((colour_type == 3 && sbit < 8) ||
  9141. (colour_type != 3 && sbit < bit_depth)))
  9142. {
  9143. unsigned int i;
  9144. for (i=0; i<pm->ngamma_tests; ++i)
  9145. {
  9146. unsigned int j;
  9147. for (j=0; j<pm->ngamma_tests; ++j)
  9148. {
  9149. if (i != j)
  9150. {
  9151. gamma_transform_test(pm, colour_type, bit_depth, npalette,
  9152. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  9153. sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
  9154. if (fail(pm))
  9155. return;
  9156. }
  9157. }
  9158. }
  9159. }
  9160. }
  9161. }
  9162. /* Note that this requires a 16 bit source image but produces 8 bit output, so
  9163. * we only need the 16bit write support, but the 16 bit images are only
  9164. * generated if DO_16BIT is defined.
  9165. */
  9166. #ifdef DO_16BIT
  9167. static void perform_gamma_scale16_tests(png_modifier *pm)
  9168. {
  9169. # ifndef PNG_MAX_GAMMA_8
  9170. # define PNG_MAX_GAMMA_8 11
  9171. # endif
  9172. # if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER != 10700
  9173. # define SBIT_16_TO_8 PNG_MAX_GAMMA_8
  9174. # else
  9175. # define SBIT_16_TO_8 16
  9176. # endif
  9177. /* Include the alpha cases here. Note that sbit matches the internal value
  9178. * used by the library - otherwise we will get spurious errors from the
  9179. * internal sbit style approximation.
  9180. *
  9181. * The threshold test is here because otherwise the 16 to 8 conversion will
  9182. * proceed *without* gamma correction, and the tests above will fail (but not
  9183. * by much) - this could be fixed, it only appears with the -g option.
  9184. */
  9185. unsigned int i, j;
  9186. for (i=0; i<pm->ngamma_tests; ++i)
  9187. {
  9188. for (j=0; j<pm->ngamma_tests; ++j)
  9189. {
  9190. if (i != j &&
  9191. fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
  9192. {
  9193. gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
  9194. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9195. pm->use_input_precision_16to8, 1 /*scale16*/);
  9196. if (fail(pm))
  9197. return;
  9198. gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
  9199. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9200. pm->use_input_precision_16to8, 1 /*scale16*/);
  9201. if (fail(pm))
  9202. return;
  9203. gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
  9204. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9205. pm->use_input_precision_16to8, 1 /*scale16*/);
  9206. if (fail(pm))
  9207. return;
  9208. gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
  9209. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9210. pm->use_input_precision_16to8, 1 /*scale16*/);
  9211. if (fail(pm))
  9212. return;
  9213. }
  9214. }
  9215. }
  9216. }
  9217. #endif /* 16 to 8 bit conversion */
  9218. #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
  9219. defined(PNG_READ_ALPHA_MODE_SUPPORTED)
  9220. static void gamma_composition_test(png_modifier *pm,
  9221. png_byte colour_type, png_byte bit_depth,
  9222. int palette_number,
  9223. int interlace_type, const double file_gamma,
  9224. const double screen_gamma,
  9225. int use_input_precision, int do_background,
  9226. int expand_16)
  9227. {
  9228. size_t pos = 0;
  9229. png_const_charp base;
  9230. double bg;
  9231. char name[128];
  9232. png_color_16 background;
  9233. /* Make up a name and get an appropriate background gamma value. */
  9234. switch (do_background)
  9235. {
  9236. default:
  9237. base = "";
  9238. bg = 4; /* should not be used */
  9239. break;
  9240. case PNG_BACKGROUND_GAMMA_SCREEN:
  9241. base = " bckg(Screen):";
  9242. bg = 1/screen_gamma;
  9243. break;
  9244. case PNG_BACKGROUND_GAMMA_FILE:
  9245. base = " bckg(File):";
  9246. bg = file_gamma;
  9247. break;
  9248. case PNG_BACKGROUND_GAMMA_UNIQUE:
  9249. base = " bckg(Unique):";
  9250. /* This tests the handling of a unique value, the math is such that the
  9251. * value tends to be <1, but is neither screen nor file (even if they
  9252. * match!)
  9253. */
  9254. bg = (file_gamma + screen_gamma) / 3;
  9255. break;
  9256. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  9257. case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
  9258. base = " alpha(PNG)";
  9259. bg = 4; /* should not be used */
  9260. break;
  9261. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  9262. base = " alpha(Porter-Duff)";
  9263. bg = 4; /* should not be used */
  9264. break;
  9265. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  9266. base = " alpha(Optimized)";
  9267. bg = 4; /* should not be used */
  9268. break;
  9269. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  9270. base = " alpha(Broken)";
  9271. bg = 4; /* should not be used */
  9272. break;
  9273. #endif
  9274. }
  9275. /* Use random background values - the background is always presented in the
  9276. * output space (8 or 16 bit components).
  9277. */
  9278. if (expand_16 || bit_depth == 16)
  9279. {
  9280. png_uint_32 r = random_32();
  9281. background.red = (png_uint_16)r;
  9282. background.green = (png_uint_16)(r >> 16);
  9283. r = random_32();
  9284. background.blue = (png_uint_16)r;
  9285. background.gray = (png_uint_16)(r >> 16);
  9286. /* In earlier libpng versions, those where DIGITIZE is set, any background
  9287. * gamma correction in the expand16 case was done using 8-bit gamma
  9288. * correction tables, resulting in larger errors. To cope with those
  9289. * cases use a 16-bit background value which will handle this gamma
  9290. * correction.
  9291. */
  9292. # if DIGITIZE
  9293. if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
  9294. do_background == PNG_BACKGROUND_GAMMA_FILE) &&
  9295. fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
  9296. {
  9297. /* The background values will be looked up in an 8-bit table to do
  9298. * the gamma correction, so only select values which are an exact
  9299. * match for the 8-bit table entries:
  9300. */
  9301. background.red = (png_uint_16)((background.red >> 8) * 257);
  9302. background.green = (png_uint_16)((background.green >> 8) * 257);
  9303. background.blue = (png_uint_16)((background.blue >> 8) * 257);
  9304. background.gray = (png_uint_16)((background.gray >> 8) * 257);
  9305. }
  9306. # endif
  9307. }
  9308. else /* 8 bit colors */
  9309. {
  9310. png_uint_32 r = random_32();
  9311. background.red = (png_byte)r;
  9312. background.green = (png_byte)(r >> 8);
  9313. background.blue = (png_byte)(r >> 16);
  9314. background.gray = (png_byte)(r >> 24);
  9315. }
  9316. background.index = 193; /* rgb(193,193,193) to detect errors */
  9317. if (!(colour_type & PNG_COLOR_MASK_COLOR))
  9318. {
  9319. /* Because, currently, png_set_background is always called with
  9320. * 'need_expand' false in this case and because the gamma test itself
  9321. * doesn't cause an expand to 8-bit for lower bit depths the colour must
  9322. * be reduced to the correct range.
  9323. */
  9324. if (bit_depth < 8)
  9325. background.gray &= (png_uint_16)((1U << bit_depth)-1);
  9326. /* Grayscale input, we do not convert to RGB (TBD), so we must set the
  9327. * background to gray - else libpng seems to fail.
  9328. */
  9329. background.red = background.green = background.blue = background.gray;
  9330. }
  9331. pos = safecat(name, sizeof name, pos, "gamma ");
  9332. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  9333. pos = safecat(name, sizeof name, pos, "->");
  9334. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  9335. pos = safecat(name, sizeof name, pos, base);
  9336. if (do_background < ALPHA_MODE_OFFSET)
  9337. {
  9338. /* Include the background color and gamma in the name: */
  9339. pos = safecat(name, sizeof name, pos, "(");
  9340. /* This assumes no expand gray->rgb - the current code won't handle that!
  9341. */
  9342. if (colour_type & PNG_COLOR_MASK_COLOR)
  9343. {
  9344. pos = safecatn(name, sizeof name, pos, background.red);
  9345. pos = safecat(name, sizeof name, pos, ",");
  9346. pos = safecatn(name, sizeof name, pos, background.green);
  9347. pos = safecat(name, sizeof name, pos, ",");
  9348. pos = safecatn(name, sizeof name, pos, background.blue);
  9349. }
  9350. else
  9351. pos = safecatn(name, sizeof name, pos, background.gray);
  9352. pos = safecat(name, sizeof name, pos, ")^");
  9353. pos = safecatd(name, sizeof name, pos, bg, 3);
  9354. }
  9355. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  9356. file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
  9357. 0/*strip 16*/, expand_16, do_background, &background, bg);
  9358. }
  9359. static void
  9360. perform_gamma_composition_tests(png_modifier *pm, int do_background,
  9361. int expand_16)
  9362. {
  9363. png_byte colour_type = 0;
  9364. png_byte bit_depth = 0;
  9365. unsigned int palette_number = 0;
  9366. /* Skip the non-alpha cases - there is no setting of a transparency colour at
  9367. * present.
  9368. *
  9369. * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
  9370. * however the palette case fails miserably so is commented out below.
  9371. */
  9372. while (next_format(&colour_type, &bit_depth, &palette_number,
  9373. pm->test_lbg_gamma_composition, pm->test_tRNS))
  9374. if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
  9375. #if 0 /* TODO: FIXME */
  9376. /*TODO: FIXME: this should work */
  9377. || colour_type == 3
  9378. #endif
  9379. || (colour_type != 3 && palette_number != 0))
  9380. {
  9381. unsigned int i, j;
  9382. /* Don't skip the i==j case here - it's relevant. */
  9383. for (i=0; i<pm->ngamma_tests; ++i)
  9384. {
  9385. for (j=0; j<pm->ngamma_tests; ++j)
  9386. {
  9387. gamma_composition_test(pm, colour_type, bit_depth, palette_number,
  9388. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  9389. pm->use_input_precision, do_background, expand_16);
  9390. if (fail(pm))
  9391. return;
  9392. }
  9393. }
  9394. }
  9395. }
  9396. #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
  9397. static void
  9398. init_gamma_errors(png_modifier *pm)
  9399. {
  9400. /* Use -1 to catch tests that were not actually run */
  9401. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
  9402. pm->error_color_8 = -1.;
  9403. pm->error_indexed = -1.;
  9404. pm->error_gray_16 = pm->error_color_16 = -1.;
  9405. }
  9406. static void
  9407. print_one(const char *leader, double err)
  9408. {
  9409. if (err != -1.)
  9410. printf(" %s %.5f\n", leader, err);
  9411. }
  9412. static void
  9413. summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
  9414. int indexed)
  9415. {
  9416. fflush(stderr);
  9417. if (who)
  9418. printf("\nGamma correction with %s:\n", who);
  9419. else
  9420. printf("\nBasic gamma correction:\n");
  9421. if (low_bit_depth)
  9422. {
  9423. print_one(" 2 bit gray: ", pm->error_gray_2);
  9424. print_one(" 4 bit gray: ", pm->error_gray_4);
  9425. print_one(" 8 bit gray: ", pm->error_gray_8);
  9426. print_one(" 8 bit color:", pm->error_color_8);
  9427. if (indexed)
  9428. print_one(" indexed: ", pm->error_indexed);
  9429. }
  9430. print_one("16 bit gray: ", pm->error_gray_16);
  9431. print_one("16 bit color:", pm->error_color_16);
  9432. fflush(stdout);
  9433. }
  9434. static void
  9435. perform_gamma_test(png_modifier *pm, int summary)
  9436. {
  9437. /*TODO: remove this*/
  9438. /* Save certain values for the temporary overrides below. */
  9439. unsigned int calculations_use_input_precision =
  9440. pm->calculations_use_input_precision;
  9441. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  9442. double maxout8 = pm->maxout8;
  9443. # endif
  9444. /* First some arbitrary no-transform tests: */
  9445. if (!pm->this.speed && pm->test_gamma_threshold)
  9446. {
  9447. perform_gamma_threshold_tests(pm);
  9448. if (fail(pm))
  9449. return;
  9450. }
  9451. /* Now some real transforms. */
  9452. if (pm->test_gamma_transform)
  9453. {
  9454. if (summary)
  9455. {
  9456. fflush(stderr);
  9457. printf("Gamma correction error summary\n\n");
  9458. printf("The printed value is the maximum error in the pixel values\n");
  9459. printf("calculated by the libpng gamma correction code. The error\n");
  9460. printf("is calculated as the difference between the output pixel\n");
  9461. printf("value (always an integer) and the ideal value from the\n");
  9462. printf("libpng specification (typically not an integer).\n\n");
  9463. printf("Expect this value to be less than .5 for 8 bit formats,\n");
  9464. printf("less than 1 for formats with fewer than 8 bits and a small\n");
  9465. printf("number (typically less than 5) for the 16 bit formats.\n");
  9466. printf("For performance reasons the value for 16 bit formats\n");
  9467. printf("increases when the image file includes an sBIT chunk.\n");
  9468. fflush(stdout);
  9469. }
  9470. init_gamma_errors(pm);
  9471. /*TODO: remove this. Necessary because the current libpng
  9472. * implementation works in 8 bits:
  9473. */
  9474. if (pm->test_gamma_expand16)
  9475. pm->calculations_use_input_precision = 1;
  9476. perform_gamma_transform_tests(pm);
  9477. if (!calculations_use_input_precision)
  9478. pm->calculations_use_input_precision = 0;
  9479. if (summary)
  9480. summarize_gamma_errors(pm, NULL/*who*/, 1/*low bit depth*/, 1/*indexed*/);
  9481. if (fail(pm))
  9482. return;
  9483. }
  9484. /* The sbit tests produce much larger errors: */
  9485. if (pm->test_gamma_sbit)
  9486. {
  9487. init_gamma_errors(pm);
  9488. perform_gamma_sbit_tests(pm);
  9489. if (summary)
  9490. summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
  9491. if (fail(pm))
  9492. return;
  9493. }
  9494. #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
  9495. if (pm->test_gamma_scale16)
  9496. {
  9497. /* The 16 to 8 bit strip operations: */
  9498. init_gamma_errors(pm);
  9499. perform_gamma_scale16_tests(pm);
  9500. if (summary)
  9501. {
  9502. fflush(stderr);
  9503. printf("\nGamma correction with 16 to 8 bit reduction:\n");
  9504. printf(" 16 bit gray: %.5f\n", pm->error_gray_16);
  9505. printf(" 16 bit color: %.5f\n", pm->error_color_16);
  9506. fflush(stdout);
  9507. }
  9508. if (fail(pm))
  9509. return;
  9510. }
  9511. #endif
  9512. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  9513. if (pm->test_gamma_background)
  9514. {
  9515. init_gamma_errors(pm);
  9516. /*TODO: remove this. Necessary because the current libpng
  9517. * implementation works in 8 bits:
  9518. */
  9519. if (pm->test_gamma_expand16)
  9520. {
  9521. pm->calculations_use_input_precision = 1;
  9522. pm->maxout8 = .499; /* because the 16 bit background is smashed */
  9523. }
  9524. perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
  9525. pm->test_gamma_expand16);
  9526. if (!calculations_use_input_precision)
  9527. pm->calculations_use_input_precision = 0;
  9528. pm->maxout8 = maxout8;
  9529. if (summary)
  9530. summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
  9531. if (fail(pm))
  9532. return;
  9533. }
  9534. #endif
  9535. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  9536. if (pm->test_gamma_alpha_mode)
  9537. {
  9538. int do_background;
  9539. init_gamma_errors(pm);
  9540. /*TODO: remove this. Necessary because the current libpng
  9541. * implementation works in 8 bits:
  9542. */
  9543. if (pm->test_gamma_expand16)
  9544. pm->calculations_use_input_precision = 1;
  9545. for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
  9546. do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
  9547. ++do_background)
  9548. perform_gamma_composition_tests(pm, do_background,
  9549. pm->test_gamma_expand16);
  9550. if (!calculations_use_input_precision)
  9551. pm->calculations_use_input_precision = 0;
  9552. if (summary)
  9553. summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
  9554. if (fail(pm))
  9555. return;
  9556. }
  9557. #endif
  9558. }
  9559. #endif /* PNG_READ_GAMMA_SUPPORTED */
  9560. #endif /* PNG_READ_SUPPORTED */
  9561. /* INTERLACE MACRO VALIDATION */
  9562. /* This is copied verbatim from the specification, it is simply the pass
  9563. * number in which each pixel in each 8x8 tile appears. The array must
  9564. * be indexed adam7[y][x] and notice that the pass numbers are based at
  9565. * 1, not 0 - the base libpng uses.
  9566. */
  9567. static const
  9568. png_byte adam7[8][8] =
  9569. {
  9570. { 1,6,4,6,2,6,4,6 },
  9571. { 7,7,7,7,7,7,7,7 },
  9572. { 5,6,5,6,5,6,5,6 },
  9573. { 7,7,7,7,7,7,7,7 },
  9574. { 3,6,4,6,3,6,4,6 },
  9575. { 7,7,7,7,7,7,7,7 },
  9576. { 5,6,5,6,5,6,5,6 },
  9577. { 7,7,7,7,7,7,7,7 }
  9578. };
  9579. /* This routine validates all the interlace support macros in png.h for
  9580. * a variety of valid PNG widths and heights. It uses a number of similarly
  9581. * named internal routines that feed off the above array.
  9582. */
  9583. static png_uint_32
  9584. png_pass_start_row(int pass)
  9585. {
  9586. int x, y;
  9587. ++pass;
  9588. for (y=0; y<8; ++y)
  9589. for (x=0; x<8; ++x)
  9590. if (adam7[y][x] == pass)
  9591. return y;
  9592. return 0xf;
  9593. }
  9594. static png_uint_32
  9595. png_pass_start_col(int pass)
  9596. {
  9597. int x, y;
  9598. ++pass;
  9599. for (x=0; x<8; ++x)
  9600. for (y=0; y<8; ++y)
  9601. if (adam7[y][x] == pass)
  9602. return x;
  9603. return 0xf;
  9604. }
  9605. static int
  9606. png_pass_row_shift(int pass)
  9607. {
  9608. int x, y, base=(-1), inc=8;
  9609. ++pass;
  9610. for (y=0; y<8; ++y)
  9611. {
  9612. for (x=0; x<8; ++x)
  9613. {
  9614. if (adam7[y][x] == pass)
  9615. {
  9616. if (base == (-1))
  9617. base = y;
  9618. else if (base == y)
  9619. {}
  9620. else if (inc == y-base)
  9621. base=y;
  9622. else if (inc == 8)
  9623. inc = y-base, base=y;
  9624. else if (inc != y-base)
  9625. return 0xff; /* error - more than one 'inc' value! */
  9626. }
  9627. }
  9628. }
  9629. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  9630. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  9631. switch (inc)
  9632. {
  9633. case 2: return 1;
  9634. case 4: return 2;
  9635. case 8: return 3;
  9636. default: break;
  9637. }
  9638. /* error - unrecognized 'inc' */
  9639. return (inc << 8) + 0xfd;
  9640. }
  9641. static int
  9642. png_pass_col_shift(int pass)
  9643. {
  9644. int x, y, base=(-1), inc=8;
  9645. ++pass;
  9646. for (x=0; x<8; ++x)
  9647. {
  9648. for (y=0; y<8; ++y)
  9649. {
  9650. if (adam7[y][x] == pass)
  9651. {
  9652. if (base == (-1))
  9653. base = x;
  9654. else if (base == x)
  9655. {}
  9656. else if (inc == x-base)
  9657. base=x;
  9658. else if (inc == 8)
  9659. inc = x-base, base=x;
  9660. else if (inc != x-base)
  9661. return 0xff; /* error - more than one 'inc' value! */
  9662. }
  9663. }
  9664. }
  9665. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  9666. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  9667. switch (inc)
  9668. {
  9669. case 1: return 0; /* pass 7 has all the columns */
  9670. case 2: return 1;
  9671. case 4: return 2;
  9672. case 8: return 3;
  9673. default: break;
  9674. }
  9675. /* error - unrecognized 'inc' */
  9676. return (inc << 8) + 0xfd;
  9677. }
  9678. static png_uint_32
  9679. png_row_from_pass_row(png_uint_32 yIn, int pass)
  9680. {
  9681. /* By examination of the array: */
  9682. switch (pass)
  9683. {
  9684. case 0: return yIn * 8;
  9685. case 1: return yIn * 8;
  9686. case 2: return yIn * 8 + 4;
  9687. case 3: return yIn * 4;
  9688. case 4: return yIn * 4 + 2;
  9689. case 5: return yIn * 2;
  9690. case 6: return yIn * 2 + 1;
  9691. default: break;
  9692. }
  9693. return 0xff; /* bad pass number */
  9694. }
  9695. static png_uint_32
  9696. png_col_from_pass_col(png_uint_32 xIn, int pass)
  9697. {
  9698. /* By examination of the array: */
  9699. switch (pass)
  9700. {
  9701. case 0: return xIn * 8;
  9702. case 1: return xIn * 8 + 4;
  9703. case 2: return xIn * 4;
  9704. case 3: return xIn * 4 + 2;
  9705. case 4: return xIn * 2;
  9706. case 5: return xIn * 2 + 1;
  9707. case 6: return xIn;
  9708. default: break;
  9709. }
  9710. return 0xff; /* bad pass number */
  9711. }
  9712. static int
  9713. png_row_in_interlace_pass(png_uint_32 y, int pass)
  9714. {
  9715. /* Is row 'y' in pass 'pass'? */
  9716. int x;
  9717. y &= 7;
  9718. ++pass;
  9719. for (x=0; x<8; ++x)
  9720. if (adam7[y][x] == pass)
  9721. return 1;
  9722. return 0;
  9723. }
  9724. static int
  9725. png_col_in_interlace_pass(png_uint_32 x, int pass)
  9726. {
  9727. /* Is column 'x' in pass 'pass'? */
  9728. int y;
  9729. x &= 7;
  9730. ++pass;
  9731. for (y=0; y<8; ++y)
  9732. if (adam7[y][x] == pass)
  9733. return 1;
  9734. return 0;
  9735. }
  9736. static png_uint_32
  9737. png_pass_rows(png_uint_32 height, int pass)
  9738. {
  9739. png_uint_32 tiles = height>>3;
  9740. png_uint_32 rows = 0;
  9741. unsigned int x, y;
  9742. height &= 7;
  9743. ++pass;
  9744. for (y=0; y<8; ++y)
  9745. {
  9746. for (x=0; x<8; ++x)
  9747. {
  9748. if (adam7[y][x] == pass)
  9749. {
  9750. rows += tiles;
  9751. if (y < height) ++rows;
  9752. break; /* i.e. break the 'x', column, loop. */
  9753. }
  9754. }
  9755. }
  9756. return rows;
  9757. }
  9758. static png_uint_32
  9759. png_pass_cols(png_uint_32 width, int pass)
  9760. {
  9761. png_uint_32 tiles = width>>3;
  9762. png_uint_32 cols = 0;
  9763. unsigned int x, y;
  9764. width &= 7;
  9765. ++pass;
  9766. for (x=0; x<8; ++x)
  9767. {
  9768. for (y=0; y<8; ++y)
  9769. {
  9770. if (adam7[y][x] == pass)
  9771. {
  9772. cols += tiles;
  9773. if (x < width) ++cols;
  9774. break; /* i.e. break the 'y', row, loop. */
  9775. }
  9776. }
  9777. }
  9778. return cols;
  9779. }
  9780. static void
  9781. perform_interlace_macro_validation(void)
  9782. {
  9783. /* The macros to validate, first those that depend only on pass:
  9784. *
  9785. * PNG_PASS_START_ROW(pass)
  9786. * PNG_PASS_START_COL(pass)
  9787. * PNG_PASS_ROW_SHIFT(pass)
  9788. * PNG_PASS_COL_SHIFT(pass)
  9789. */
  9790. int pass;
  9791. for (pass=0; pass<7; ++pass)
  9792. {
  9793. png_uint_32 m, f, v;
  9794. m = PNG_PASS_START_ROW(pass);
  9795. f = png_pass_start_row(pass);
  9796. if (m != f)
  9797. {
  9798. fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
  9799. exit(99);
  9800. }
  9801. m = PNG_PASS_START_COL(pass);
  9802. f = png_pass_start_col(pass);
  9803. if (m != f)
  9804. {
  9805. fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
  9806. exit(99);
  9807. }
  9808. m = PNG_PASS_ROW_SHIFT(pass);
  9809. f = png_pass_row_shift(pass);
  9810. if (m != f)
  9811. {
  9812. fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
  9813. exit(99);
  9814. }
  9815. m = PNG_PASS_COL_SHIFT(pass);
  9816. f = png_pass_col_shift(pass);
  9817. if (m != f)
  9818. {
  9819. fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
  9820. exit(99);
  9821. }
  9822. /* Macros that depend on the image or sub-image height too:
  9823. *
  9824. * PNG_PASS_ROWS(height, pass)
  9825. * PNG_PASS_COLS(width, pass)
  9826. * PNG_ROW_FROM_PASS_ROW(yIn, pass)
  9827. * PNG_COL_FROM_PASS_COL(xIn, pass)
  9828. * PNG_ROW_IN_INTERLACE_PASS(y, pass)
  9829. * PNG_COL_IN_INTERLACE_PASS(x, pass)
  9830. */
  9831. for (v=0;;)
  9832. {
  9833. /* The first two tests overflow if the pass row or column is outside
  9834. * the possible range for a 32-bit result. In fact the values should
  9835. * never be outside the range for a 31-bit result, but checking for 32
  9836. * bits here ensures that if an app uses a bogus pass row or column
  9837. * (just so long as it fits in a 32 bit integer) it won't get a
  9838. * possibly dangerous overflow.
  9839. */
  9840. /* First the base 0 stuff: */
  9841. if (v < png_pass_rows(0xFFFFFFFFU, pass))
  9842. {
  9843. m = PNG_ROW_FROM_PASS_ROW(v, pass);
  9844. f = png_row_from_pass_row(v, pass);
  9845. if (m != f)
  9846. {
  9847. fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
  9848. v, pass, m, f);
  9849. exit(99);
  9850. }
  9851. }
  9852. if (v < png_pass_cols(0xFFFFFFFFU, pass))
  9853. {
  9854. m = PNG_COL_FROM_PASS_COL(v, pass);
  9855. f = png_col_from_pass_col(v, pass);
  9856. if (m != f)
  9857. {
  9858. fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
  9859. v, pass, m, f);
  9860. exit(99);
  9861. }
  9862. }
  9863. m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
  9864. f = png_row_in_interlace_pass(v, pass);
  9865. if (m != f)
  9866. {
  9867. fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  9868. v, pass, m, f);
  9869. exit(99);
  9870. }
  9871. m = PNG_COL_IN_INTERLACE_PASS(v, pass);
  9872. f = png_col_in_interlace_pass(v, pass);
  9873. if (m != f)
  9874. {
  9875. fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  9876. v, pass, m, f);
  9877. exit(99);
  9878. }
  9879. /* Then the base 1 stuff: */
  9880. ++v;
  9881. m = PNG_PASS_ROWS(v, pass);
  9882. f = png_pass_rows(v, pass);
  9883. if (m != f)
  9884. {
  9885. fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
  9886. v, pass, m, f);
  9887. exit(99);
  9888. }
  9889. m = PNG_PASS_COLS(v, pass);
  9890. f = png_pass_cols(v, pass);
  9891. if (m != f)
  9892. {
  9893. fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
  9894. v, pass, m, f);
  9895. exit(99);
  9896. }
  9897. /* Move to the next v - the stepping algorithm starts skipping
  9898. * values above 1024.
  9899. */
  9900. if (v > 1024)
  9901. {
  9902. if (v == PNG_UINT_31_MAX)
  9903. break;
  9904. v = (v << 1) ^ v;
  9905. if (v >= PNG_UINT_31_MAX)
  9906. v = PNG_UINT_31_MAX-1;
  9907. }
  9908. }
  9909. }
  9910. }
  9911. /* Test color encodings. These values are back-calculated from the published
  9912. * chromaticities. The values are accurate to about 14 decimal places; 15 are
  9913. * given. These values are much more accurate than the ones given in the spec,
  9914. * which typically don't exceed 4 decimal places. This allows testing of the
  9915. * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid
  9916. * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
  9917. * more.)
  9918. *
  9919. * The png_modifier code assumes that encodings[0] is sRGB and treats it
  9920. * specially: do not change the first entry in this list!
  9921. */
  9922. static const color_encoding test_encodings[] =
  9923. {
  9924. /* sRGB: must be first in this list! */
  9925. /*gamma:*/ { 1/2.2,
  9926. /*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
  9927. /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
  9928. /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
  9929. /* Kodak ProPhoto (wide gamut) */
  9930. /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
  9931. /*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
  9932. /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
  9933. /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
  9934. /* Adobe RGB (1998) */
  9935. /*gamma:*/ { 1/(2+51./256),
  9936. /*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
  9937. /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
  9938. /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
  9939. /* Adobe Wide Gamut RGB */
  9940. /*gamma:*/ { 1/(2+51./256),
  9941. /*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
  9942. /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
  9943. /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
  9944. /* Fake encoding which selects just the green channel */
  9945. /*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */
  9946. /*red: */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 },
  9947. /*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 },
  9948. /*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} },
  9949. };
  9950. /* signal handler
  9951. *
  9952. * This attempts to trap signals and escape without crashing. It needs a
  9953. * context pointer so that it can throw an exception (call longjmp) to recover
  9954. * from the condition; this is handled by making the png_modifier used by 'main'
  9955. * into a global variable.
  9956. */
  9957. static png_modifier pm;
  9958. static void signal_handler(int signum)
  9959. {
  9960. size_t pos = 0;
  9961. char msg[64];
  9962. pos = safecat(msg, sizeof msg, pos, "caught signal: ");
  9963. switch (signum)
  9964. {
  9965. case SIGABRT:
  9966. pos = safecat(msg, sizeof msg, pos, "abort");
  9967. break;
  9968. case SIGFPE:
  9969. pos = safecat(msg, sizeof msg, pos, "floating point exception");
  9970. break;
  9971. case SIGILL:
  9972. pos = safecat(msg, sizeof msg, pos, "illegal instruction");
  9973. break;
  9974. case SIGINT:
  9975. pos = safecat(msg, sizeof msg, pos, "interrupt");
  9976. break;
  9977. case SIGSEGV:
  9978. pos = safecat(msg, sizeof msg, pos, "invalid memory access");
  9979. break;
  9980. case SIGTERM:
  9981. pos = safecat(msg, sizeof msg, pos, "termination request");
  9982. break;
  9983. default:
  9984. pos = safecat(msg, sizeof msg, pos, "unknown ");
  9985. pos = safecatn(msg, sizeof msg, pos, signum);
  9986. break;
  9987. }
  9988. store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
  9989. /* And finally throw an exception so we can keep going, unless this is
  9990. * SIGTERM in which case stop now.
  9991. */
  9992. if (signum != SIGTERM)
  9993. {
  9994. struct exception_context *the_exception_context =
  9995. &pm.this.exception_context;
  9996. Throw &pm.this;
  9997. }
  9998. else
  9999. exit(1);
  10000. }
  10001. /* main program */
  10002. int main(int argc, char **argv)
  10003. {
  10004. int summary = 1; /* Print the error summary at the end */
  10005. int memstats = 0; /* Print memory statistics at the end */
  10006. /* Create the given output file on success: */
  10007. const char *touch = NULL;
  10008. /* This is an array of standard gamma values (believe it or not I've seen
  10009. * every one of these mentioned somewhere.)
  10010. *
  10011. * In the following list the most useful values are first!
  10012. */
  10013. static double
  10014. gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
  10015. /* This records the command and arguments: */
  10016. size_t cp = 0;
  10017. char command[1024];
  10018. anon_context(&pm.this);
  10019. gnu_volatile(summary)
  10020. gnu_volatile(memstats)
  10021. gnu_volatile(touch)
  10022. /* Add appropriate signal handlers, just the ANSI specified ones: */
  10023. signal(SIGABRT, signal_handler);
  10024. signal(SIGFPE, signal_handler);
  10025. signal(SIGILL, signal_handler);
  10026. signal(SIGINT, signal_handler);
  10027. signal(SIGSEGV, signal_handler);
  10028. signal(SIGTERM, signal_handler);
  10029. #ifdef HAVE_FEENABLEEXCEPT
  10030. /* Only required to enable FP exceptions on platforms where they start off
  10031. * disabled; this is not necessary but if it is not done pngvalid will likely
  10032. * end up ignoring FP conditions that other platforms fault.
  10033. */
  10034. feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
  10035. #endif
  10036. modifier_init(&pm);
  10037. /* Preallocate the image buffer, because we know how big it needs to be,
  10038. * note that, for testing purposes, it is deliberately mis-aligned by tag
  10039. * bytes either side. All rows have an additional five bytes of padding for
  10040. * overwrite checking.
  10041. */
  10042. store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
  10043. /* Don't give argv[0], it's normally some horrible libtool string: */
  10044. cp = safecat(command, sizeof command, cp, "pngvalid");
  10045. /* Default to error on warning: */
  10046. pm.this.treat_warnings_as_errors = 1;
  10047. /* Default assume_16_bit_calculations appropriately; this tells the checking
  10048. * code that 16-bit arithmetic is used for 8-bit samples when it would make a
  10049. * difference.
  10050. */
  10051. pm.assume_16_bit_calculations = PNG_LIBPNG_VER == 10700;
  10052. /* Currently 16 bit expansion happens at the end of the pipeline, so the
  10053. * calculations are done in the input bit depth not the output.
  10054. *
  10055. * TODO: fix this
  10056. */
  10057. pm.calculations_use_input_precision = 1U;
  10058. /* Store the test gammas */
  10059. pm.gammas = gammas;
  10060. pm.ngammas = ARRAY_SIZE(gammas);
  10061. pm.ngamma_tests = 0; /* default to off */
  10062. /* Low bit depth gray images don't do well in the gamma tests, until
  10063. * this is fixed turn them off for some gamma cases:
  10064. */
  10065. # ifdef PNG_WRITE_tRNS_SUPPORTED
  10066. pm.test_tRNS = 1;
  10067. # endif
  10068. pm.test_lbg = PNG_LIBPNG_VER >= 10600;
  10069. pm.test_lbg_gamma_threshold = 1;
  10070. pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
  10071. pm.test_lbg_gamma_sbit = 1;
  10072. pm.test_lbg_gamma_composition = PNG_LIBPNG_VER == 10700;
  10073. /* And the test encodings */
  10074. pm.encodings = test_encodings;
  10075. pm.nencodings = ARRAY_SIZE(test_encodings);
  10076. # if PNG_LIBPNG_VER != 10700
  10077. pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
  10078. # else
  10079. pm.sbitlow = 1U;
  10080. # endif
  10081. /* The following allows results to pass if they correspond to anything in the
  10082. * transformed range [input-.5,input+.5]; this is is required because of the
  10083. * way libpng treats the 16_TO_8 flag when building the gamma tables in
  10084. * releases up to 1.6.0.
  10085. *
  10086. * TODO: review this
  10087. */
  10088. pm.use_input_precision_16to8 = 1U;
  10089. pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
  10090. /* Some default values (set the behavior for 'make check' here).
  10091. * These values simply control the maximum error permitted in the gamma
  10092. * transformations. The practical limits for human perception are described
  10093. * below (the setting for maxpc16), however for 8 bit encodings it isn't
  10094. * possible to meet the accepted capabilities of human vision - i.e. 8 bit
  10095. * images can never be good enough, regardless of encoding.
  10096. */
  10097. pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
  10098. pm.maxabs8 = .00005; /* 1/20000 */
  10099. pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
  10100. pm.maxpc8 = .499; /* I.e., .499% fractional error */
  10101. pm.maxout16 = .499; /* Error in *encoded* value */
  10102. pm.maxabs16 = .00005;/* 1/20000 */
  10103. pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
  10104. # if PNG_LIBPNG_VER != 10700
  10105. pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
  10106. # else
  10107. pm.maxcalcG = 1./((1<<16)-1);
  10108. # endif
  10109. /* NOTE: this is a reasonable perceptual limit. We assume that humans can
  10110. * perceive light level differences of 1% over a 100:1 range, so we need to
  10111. * maintain 1 in 10000 accuracy (in linear light space), which is what the
  10112. * following guarantees. It also allows significantly higher errors at
  10113. * higher 16 bit values, which is important for performance. The actual
  10114. * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
  10115. * this is only allowed for values >38149 by the following:
  10116. */
  10117. pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
  10118. /* Now parse the command line options. */
  10119. while (--argc >= 1)
  10120. {
  10121. int catmore = 0; /* Set if the argument has an argument. */
  10122. /* Record each argument for posterity: */
  10123. cp = safecat(command, sizeof command, cp, " ");
  10124. cp = safecat(command, sizeof command, cp, *++argv);
  10125. if (strcmp(*argv, "-v") == 0)
  10126. pm.this.verbose = 1;
  10127. else if (strcmp(*argv, "-l") == 0)
  10128. pm.log = 1;
  10129. else if (strcmp(*argv, "-q") == 0)
  10130. summary = pm.this.verbose = pm.log = 0;
  10131. else if (strcmp(*argv, "-w") == 0 ||
  10132. strcmp(*argv, "--strict") == 0)
  10133. pm.this.treat_warnings_as_errors = 1; /* NOTE: this is the default! */
  10134. else if (strcmp(*argv, "--nostrict") == 0)
  10135. pm.this.treat_warnings_as_errors = 0;
  10136. else if (strcmp(*argv, "--speed") == 0)
  10137. pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
  10138. summary = 0;
  10139. else if (strcmp(*argv, "--memory") == 0)
  10140. memstats = 1;
  10141. else if (strcmp(*argv, "--size") == 0)
  10142. pm.test_size = 1;
  10143. else if (strcmp(*argv, "--nosize") == 0)
  10144. pm.test_size = 0;
  10145. else if (strcmp(*argv, "--standard") == 0)
  10146. pm.test_standard = 1;
  10147. else if (strcmp(*argv, "--nostandard") == 0)
  10148. pm.test_standard = 0;
  10149. else if (strcmp(*argv, "--transform") == 0)
  10150. pm.test_transform = 1;
  10151. else if (strcmp(*argv, "--notransform") == 0)
  10152. pm.test_transform = 0;
  10153. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  10154. else if (strncmp(*argv, "--transform-disable=",
  10155. sizeof "--transform-disable") == 0)
  10156. {
  10157. pm.test_transform = 1;
  10158. transform_disable(*argv + sizeof "--transform-disable");
  10159. }
  10160. else if (strncmp(*argv, "--transform-enable=",
  10161. sizeof "--transform-enable") == 0)
  10162. {
  10163. pm.test_transform = 1;
  10164. transform_enable(*argv + sizeof "--transform-enable");
  10165. }
  10166. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  10167. else if (strcmp(*argv, "--gamma") == 0)
  10168. {
  10169. /* Just do two gamma tests here (2.2 and linear) for speed: */
  10170. pm.ngamma_tests = 2U;
  10171. pm.test_gamma_threshold = 1;
  10172. pm.test_gamma_transform = 1;
  10173. pm.test_gamma_sbit = 1;
  10174. pm.test_gamma_scale16 = 1;
  10175. pm.test_gamma_background = 1; /* composition */
  10176. pm.test_gamma_alpha_mode = 1;
  10177. }
  10178. else if (strcmp(*argv, "--nogamma") == 0)
  10179. pm.ngamma_tests = 0;
  10180. else if (strcmp(*argv, "--gamma-threshold") == 0)
  10181. pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
  10182. else if (strcmp(*argv, "--nogamma-threshold") == 0)
  10183. pm.test_gamma_threshold = 0;
  10184. else if (strcmp(*argv, "--gamma-transform") == 0)
  10185. pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
  10186. else if (strcmp(*argv, "--nogamma-transform") == 0)
  10187. pm.test_gamma_transform = 0;
  10188. else if (strcmp(*argv, "--gamma-sbit") == 0)
  10189. pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
  10190. else if (strcmp(*argv, "--nogamma-sbit") == 0)
  10191. pm.test_gamma_sbit = 0;
  10192. else if (strcmp(*argv, "--gamma-16-to-8") == 0)
  10193. pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
  10194. else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
  10195. pm.test_gamma_scale16 = 0;
  10196. else if (strcmp(*argv, "--gamma-background") == 0)
  10197. pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
  10198. else if (strcmp(*argv, "--nogamma-background") == 0)
  10199. pm.test_gamma_background = 0;
  10200. else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
  10201. pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
  10202. else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
  10203. pm.test_gamma_alpha_mode = 0;
  10204. else if (strcmp(*argv, "--expand16") == 0)
  10205. {
  10206. # ifdef PNG_READ_EXPAND_16_SUPPORTED
  10207. pm.test_gamma_expand16 = 1;
  10208. # else
  10209. fprintf(stderr, "pngvalid: --expand16: no read support\n");
  10210. return SKIP;
  10211. # endif
  10212. }
  10213. else if (strcmp(*argv, "--noexpand16") == 0)
  10214. pm.test_gamma_expand16 = 0;
  10215. else if (strcmp(*argv, "--low-depth-gray") == 0)
  10216. pm.test_lbg = pm.test_lbg_gamma_threshold =
  10217. pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
  10218. pm.test_lbg_gamma_composition = 1;
  10219. else if (strcmp(*argv, "--nolow-depth-gray") == 0)
  10220. pm.test_lbg = pm.test_lbg_gamma_threshold =
  10221. pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
  10222. pm.test_lbg_gamma_composition = 0;
  10223. else if (strcmp(*argv, "--tRNS") == 0)
  10224. {
  10225. # ifdef PNG_WRITE_tRNS_SUPPORTED
  10226. pm.test_tRNS = 1;
  10227. # else
  10228. fprintf(stderr, "pngvalid: --tRNS: no write support\n");
  10229. return SKIP;
  10230. # endif
  10231. }
  10232. else if (strcmp(*argv, "--notRNS") == 0)
  10233. pm.test_tRNS = 0;
  10234. else if (strcmp(*argv, "--more-gammas") == 0)
  10235. pm.ngamma_tests = 3U;
  10236. else if (strcmp(*argv, "--all-gammas") == 0)
  10237. pm.ngamma_tests = pm.ngammas;
  10238. else if (strcmp(*argv, "--progressive-read") == 0)
  10239. pm.this.progressive = 1;
  10240. else if (strcmp(*argv, "--use-update-info") == 0)
  10241. ++pm.use_update_info; /* Can call multiple times */
  10242. else if (strcmp(*argv, "--interlace") == 0)
  10243. {
  10244. # if CAN_WRITE_INTERLACE
  10245. pm.interlace_type = PNG_INTERLACE_ADAM7;
  10246. # else /* !CAN_WRITE_INTERLACE */
  10247. fprintf(stderr, "pngvalid: no write interlace support\n");
  10248. return SKIP;
  10249. # endif /* !CAN_WRITE_INTERLACE */
  10250. }
  10251. else if (strcmp(*argv, "--use-input-precision") == 0)
  10252. pm.use_input_precision = 1U;
  10253. else if (strcmp(*argv, "--use-calculation-precision") == 0)
  10254. pm.use_input_precision = 0;
  10255. else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
  10256. pm.calculations_use_input_precision = 1U;
  10257. else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
  10258. pm.assume_16_bit_calculations = 1U;
  10259. else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
  10260. pm.calculations_use_input_precision =
  10261. pm.assume_16_bit_calculations = 0;
  10262. else if (strcmp(*argv, "--exhaustive") == 0)
  10263. pm.test_exhaustive = 1;
  10264. else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
  10265. --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
  10266. else if (argc > 1 && strcmp(*argv, "--touch") == 0)
  10267. --argc, touch = *++argv, catmore = 1;
  10268. else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
  10269. {
  10270. --argc;
  10271. if (strcmp(5+*argv, "abs8") == 0)
  10272. pm.maxabs8 = atof(*++argv);
  10273. else if (strcmp(5+*argv, "abs16") == 0)
  10274. pm.maxabs16 = atof(*++argv);
  10275. else if (strcmp(5+*argv, "calc8") == 0)
  10276. pm.maxcalc8 = atof(*++argv);
  10277. else if (strcmp(5+*argv, "calc16") == 0)
  10278. pm.maxcalc16 = atof(*++argv);
  10279. else if (strcmp(5+*argv, "out8") == 0)
  10280. pm.maxout8 = atof(*++argv);
  10281. else if (strcmp(5+*argv, "out16") == 0)
  10282. pm.maxout16 = atof(*++argv);
  10283. else if (strcmp(5+*argv, "pc8") == 0)
  10284. pm.maxpc8 = atof(*++argv);
  10285. else if (strcmp(5+*argv, "pc16") == 0)
  10286. pm.maxpc16 = atof(*++argv);
  10287. else
  10288. {
  10289. fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
  10290. exit(99);
  10291. }
  10292. catmore = 1;
  10293. }
  10294. else if (strcmp(*argv, "--log8") == 0)
  10295. --argc, pm.log8 = atof(*++argv), catmore = 1;
  10296. else if (strcmp(*argv, "--log16") == 0)
  10297. --argc, pm.log16 = atof(*++argv), catmore = 1;
  10298. #ifdef PNG_SET_OPTION_SUPPORTED
  10299. else if (strncmp(*argv, "--option=", 9) == 0)
  10300. {
  10301. /* Syntax of the argument is <option>:{on|off} */
  10302. const char *arg = 9+*argv;
  10303. unsigned char option=0, setting=0;
  10304. #ifdef PNG_ARM_NEON
  10305. if (strncmp(arg, "arm-neon:", 9) == 0)
  10306. option = PNG_ARM_NEON, arg += 9;
  10307. else
  10308. #endif
  10309. #ifdef PNG_EXTENSIONS
  10310. if (strncmp(arg, "extensions:", 11) == 0)
  10311. option = PNG_EXTENSIONS, arg += 11;
  10312. else
  10313. #endif
  10314. #ifdef PNG_MAXIMUM_INFLATE_WINDOW
  10315. if (strncmp(arg, "max-inflate-window:", 19) == 0)
  10316. option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
  10317. else
  10318. #endif
  10319. {
  10320. fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
  10321. exit(99);
  10322. }
  10323. if (strcmp(arg, "off") == 0)
  10324. setting = PNG_OPTION_OFF;
  10325. else if (strcmp(arg, "on") == 0)
  10326. setting = PNG_OPTION_ON;
  10327. else
  10328. {
  10329. fprintf(stderr,
  10330. "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
  10331. *argv, arg);
  10332. exit(99);
  10333. }
  10334. pm.this.options[pm.this.noptions].option = option;
  10335. pm.this.options[pm.this.noptions++].setting = setting;
  10336. }
  10337. #endif /* PNG_SET_OPTION_SUPPORTED */
  10338. else
  10339. {
  10340. fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
  10341. exit(99);
  10342. }
  10343. if (catmore) /* consumed an extra *argv */
  10344. {
  10345. cp = safecat(command, sizeof command, cp, " ");
  10346. cp = safecat(command, sizeof command, cp, *argv);
  10347. }
  10348. }
  10349. /* If pngvalid is run with no arguments default to a reasonable set of the
  10350. * tests.
  10351. */
  10352. if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
  10353. pm.ngamma_tests == 0)
  10354. {
  10355. /* Make this do all the tests done in the test shell scripts with the same
  10356. * parameters, where possible. The limitation is that all the progressive
  10357. * read and interlace stuff has to be done in separate runs, so only the
  10358. * basic 'standard' and 'size' tests are done.
  10359. */
  10360. pm.test_standard = 1;
  10361. pm.test_size = 1;
  10362. pm.test_transform = 1;
  10363. pm.ngamma_tests = 2U;
  10364. }
  10365. if (pm.ngamma_tests > 0 &&
  10366. pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
  10367. pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
  10368. pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
  10369. {
  10370. pm.test_gamma_threshold = 1;
  10371. pm.test_gamma_transform = 1;
  10372. pm.test_gamma_sbit = 1;
  10373. pm.test_gamma_scale16 = 1;
  10374. pm.test_gamma_background = 1;
  10375. pm.test_gamma_alpha_mode = 1;
  10376. }
  10377. else if (pm.ngamma_tests == 0)
  10378. {
  10379. /* Nothing to test so turn everything off: */
  10380. pm.test_gamma_threshold = 0;
  10381. pm.test_gamma_transform = 0;
  10382. pm.test_gamma_sbit = 0;
  10383. pm.test_gamma_scale16 = 0;
  10384. pm.test_gamma_background = 0;
  10385. pm.test_gamma_alpha_mode = 0;
  10386. }
  10387. Try
  10388. {
  10389. /* Make useful base images */
  10390. make_transform_images(&pm);
  10391. /* Perform the standard and gamma tests. */
  10392. if (pm.test_standard)
  10393. {
  10394. perform_interlace_macro_validation();
  10395. perform_formatting_test(&pm.this);
  10396. # ifdef PNG_READ_SUPPORTED
  10397. perform_standard_test(&pm);
  10398. # endif
  10399. perform_error_test(&pm);
  10400. }
  10401. /* Various oddly sized images: */
  10402. if (pm.test_size)
  10403. {
  10404. make_size_images(&pm.this);
  10405. # ifdef PNG_READ_SUPPORTED
  10406. perform_size_test(&pm);
  10407. # endif
  10408. }
  10409. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  10410. /* Combinatorial transforms: */
  10411. if (pm.test_transform)
  10412. perform_transform_test(&pm);
  10413. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  10414. #ifdef PNG_READ_GAMMA_SUPPORTED
  10415. if (pm.ngamma_tests > 0)
  10416. perform_gamma_test(&pm, summary);
  10417. #endif
  10418. }
  10419. Catch_anonymous
  10420. {
  10421. fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
  10422. if (!pm.this.verbose)
  10423. {
  10424. if (pm.this.error[0] != 0)
  10425. fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
  10426. fprintf(stderr, "pngvalid: run with -v to see what happened\n");
  10427. }
  10428. exit(1);
  10429. }
  10430. if (summary)
  10431. {
  10432. printf("%s: %s (%s point arithmetic)\n",
  10433. (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  10434. pm.this.nwarnings)) ? "FAIL" : "PASS",
  10435. command,
  10436. #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
  10437. "floating"
  10438. #else
  10439. "fixed"
  10440. #endif
  10441. );
  10442. }
  10443. if (memstats)
  10444. {
  10445. printf("Allocated memory statistics (in bytes):\n"
  10446. "\tread %lu maximum single, %lu peak, %lu total\n"
  10447. "\twrite %lu maximum single, %lu peak, %lu total\n",
  10448. (unsigned long)pm.this.read_memory_pool.max_max,
  10449. (unsigned long)pm.this.read_memory_pool.max_limit,
  10450. (unsigned long)pm.this.read_memory_pool.max_total,
  10451. (unsigned long)pm.this.write_memory_pool.max_max,
  10452. (unsigned long)pm.this.write_memory_pool.max_limit,
  10453. (unsigned long)pm.this.write_memory_pool.max_total);
  10454. }
  10455. /* Do this here to provoke memory corruption errors in memory not directly
  10456. * allocated by libpng - not a complete test, but better than nothing.
  10457. */
  10458. store_delete(&pm.this);
  10459. /* Error exit if there are any errors, and maybe if there are any
  10460. * warnings.
  10461. */
  10462. if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  10463. pm.this.nwarnings))
  10464. {
  10465. if (!pm.this.verbose)
  10466. fprintf(stderr, "pngvalid: %s\n", pm.this.error);
  10467. fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
  10468. pm.this.nwarnings);
  10469. exit(1);
  10470. }
  10471. /* Success case. */
  10472. if (touch != NULL)
  10473. {
  10474. FILE *fsuccess = fopen(touch, "wt");
  10475. if (fsuccess != NULL)
  10476. {
  10477. int error = 0;
  10478. fprintf(fsuccess, "PNG validation succeeded\n");
  10479. fflush(fsuccess);
  10480. error = ferror(fsuccess);
  10481. if (fclose(fsuccess) || error)
  10482. {
  10483. fprintf(stderr, "%s: write failed\n", touch);
  10484. exit(1);
  10485. }
  10486. }
  10487. else
  10488. {
  10489. fprintf(stderr, "%s: open failed\n", touch);
  10490. exit(1);
  10491. }
  10492. }
  10493. /* This is required because some very minimal configurations do not use it:
  10494. */
  10495. UNUSED(fail)
  10496. return 0;
  10497. }
  10498. #else /* write or low level APIs not supported */
  10499. int main(void)
  10500. {
  10501. fprintf(stderr,
  10502. "pngvalid: no low level write support in libpng, all tests skipped\n");
  10503. /* So the test is skipped: */
  10504. return SKIP;
  10505. }
  10506. #endif