pngvalid.c 362 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747
  1. /* pngvalid.c - validate libpng by constructing then reading png files.
  2. *
  3. * Last changed in libpng 1.5.25 [December 3, 2015]
  4. * Copyright (c) 2014-2015 Glenn Randers-Pehrson
  5. * Written by John Cunningham Bowler
  6. *
  7. * This code is released under the libpng license.
  8. * For conditions of distribution and use, see the disclaimer
  9. * and license in png.h
  10. *
  11. * NOTES:
  12. * This is a C program that is intended to be linked against libpng. It
  13. * generates bitmaps internally, stores them as PNG files (using the
  14. * sequential write code) then reads them back (using the sequential
  15. * read code) and validates that the result has the correct data.
  16. *
  17. * The program can be modified and extended to test the correctness of
  18. * transformations performed by libpng.
  19. */
  20. #define _POSIX_SOURCE 1
  21. #define _ISOC99_SOURCE 1 /* For floating point */
  22. #define _GNU_SOURCE 1 /* For the floating point exception extension */
  23. #include <signal.h>
  24. #include <stdio.h>
  25. #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
  26. # include <config.h>
  27. #endif
  28. #ifdef HAVE_FEENABLEEXCEPT /* from config.h, if included */
  29. # include <fenv.h>
  30. #endif
  31. #ifndef FE_DIVBYZERO
  32. # define FE_DIVBYZERO 0
  33. #endif
  34. #ifndef FE_INVALID
  35. # define FE_INVALID 0
  36. #endif
  37. #ifndef FE_OVERFLOW
  38. # define FE_OVERFLOW 0
  39. #endif
  40. /* Define the following to use this test against your installed libpng, rather
  41. * than the one being built here:
  42. */
  43. #ifdef PNG_FREESTANDING_TESTS
  44. # include <png.h>
  45. #else
  46. # include "../../png.h"
  47. #endif
  48. #ifdef PNG_ZLIB_HEADER
  49. # include PNG_ZLIB_HEADER
  50. #else
  51. # include <zlib.h> /* For crc32 */
  52. #endif
  53. /* 1.6.1 added support for the configure test harness, which uses 77 to indicate
  54. * a skipped test, in earlier versions we need to succeed on a skipped test, so:
  55. */
  56. #if PNG_LIBPNG_VER < 10601
  57. # define SKIP 0
  58. #else
  59. # define SKIP 77
  60. #endif
  61. /* pngvalid requires write support and one of the fixed or floating point APIs.
  62. */
  63. #if defined(PNG_WRITE_SUPPORTED) &&\
  64. (defined(PNG_FIXED_POINT_SUPPORTED) || defined(PNG_FLOATING_POINT_SUPPORTED))
  65. #if PNG_LIBPNG_VER < 10500
  66. /* This deliberately lacks the const. */
  67. typedef png_byte *png_const_bytep;
  68. /* This is copied from 1.5.1 png.h: */
  69. #define PNG_INTERLACE_ADAM7_PASSES 7
  70. #define PNG_PASS_START_ROW(pass) (((1U&~(pass))<<(3-((pass)>>1)))&7)
  71. #define PNG_PASS_START_COL(pass) (((1U& (pass))<<(3-(((pass)+1)>>1)))&7)
  72. #define PNG_PASS_ROW_SHIFT(pass) ((pass)>2?(8-(pass))>>1:3)
  73. #define PNG_PASS_COL_SHIFT(pass) ((pass)>1?(7-(pass))>>1:3)
  74. #define PNG_PASS_ROWS(height, pass) (((height)+(((1<<PNG_PASS_ROW_SHIFT(pass))\
  75. -1)-PNG_PASS_START_ROW(pass)))>>PNG_PASS_ROW_SHIFT(pass))
  76. #define PNG_PASS_COLS(width, pass) (((width)+(((1<<PNG_PASS_COL_SHIFT(pass))\
  77. -1)-PNG_PASS_START_COL(pass)))>>PNG_PASS_COL_SHIFT(pass))
  78. #define PNG_ROW_FROM_PASS_ROW(yIn, pass) \
  79. (((yIn)<<PNG_PASS_ROW_SHIFT(pass))+PNG_PASS_START_ROW(pass))
  80. #define PNG_COL_FROM_PASS_COL(xIn, pass) \
  81. (((xIn)<<PNG_PASS_COL_SHIFT(pass))+PNG_PASS_START_COL(pass))
  82. #define PNG_PASS_MASK(pass,off) ( \
  83. ((0x110145AFU>>(((7-(off))-(pass))<<2)) & 0xFU) | \
  84. ((0x01145AF0U>>(((7-(off))-(pass))<<2)) & 0xF0U))
  85. #define PNG_ROW_IN_INTERLACE_PASS(y, pass) \
  86. ((PNG_PASS_MASK(pass,0) >> ((y)&7)) & 1)
  87. #define PNG_COL_IN_INTERLACE_PASS(x, pass) \
  88. ((PNG_PASS_MASK(pass,1) >> ((x)&7)) & 1)
  89. /* These are needed too for the default build: */
  90. #define PNG_WRITE_16BIT_SUPPORTED
  91. #define PNG_READ_16BIT_SUPPORTED
  92. /* This comes from pnglibconf.h afer 1.5: */
  93. #define PNG_FP_1 100000
  94. #define PNG_GAMMA_THRESHOLD_FIXED\
  95. ((png_fixed_point)(PNG_GAMMA_THRESHOLD * PNG_FP_1))
  96. #endif
  97. #if PNG_LIBPNG_VER < 10600
  98. /* 1.6.0 constifies many APIs, the following exists to allow pngvalid to be
  99. * compiled against earlier versions.
  100. */
  101. # define png_const_structp png_structp
  102. #endif
  103. #include <float.h> /* For floating point constants */
  104. #include <stdlib.h> /* For malloc */
  105. #include <string.h> /* For memcpy, memset */
  106. #include <math.h> /* For floor */
  107. /* Unused formal parameter errors are removed using the following macro which is
  108. * expected to have no bad effects on performance.
  109. */
  110. #ifndef UNUSED
  111. # if defined(__GNUC__) || defined(_MSC_VER)
  112. # define UNUSED(param) (void)param;
  113. # else
  114. # define UNUSED(param)
  115. # endif
  116. #endif
  117. /***************************** EXCEPTION HANDLING *****************************/
  118. #ifdef PNG_FREESTANDING_TESTS
  119. # include <cexcept.h>
  120. #else
  121. # include "../visupng/cexcept.h"
  122. #endif
  123. #ifdef __cplusplus
  124. # define this not_the_cpp_this
  125. # define new not_the_cpp_new
  126. # define voidcast(type, value) static_cast<type>(value)
  127. #else
  128. # define voidcast(type, value) (value)
  129. #endif /* __cplusplus */
  130. struct png_store;
  131. define_exception_type(struct png_store*);
  132. /* The following are macros to reduce typing everywhere where the well known
  133. * name 'the_exception_context' must be defined.
  134. */
  135. #define anon_context(ps) struct exception_context *the_exception_context = \
  136. &(ps)->exception_context
  137. #define context(ps,fault) anon_context(ps); png_store *fault
  138. /* This macro returns the number of elements in an array as an (unsigned int),
  139. * it is necessary to avoid the inability of certain versions of GCC to use
  140. * the value of a compile-time constant when performing range checks. It must
  141. * be passed an array name.
  142. */
  143. #define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
  144. /* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires
  145. * some broken GCC versions to be fixed up to avoid invalid whining about auto
  146. * variables that are *not* changed within the scope of a setjmp being changed.
  147. *
  148. * Feel free to extend the list of broken versions.
  149. */
  150. #define is_gnu(major,minor)\
  151. (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor)
  152. #define is_gnu_patch(major,minor,patch)\
  153. is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0
  154. /* For the moment just do it always; all versions of GCC seem to be broken: */
  155. #ifdef __GNUC__
  156. const void * volatile make_volatile_for_gnu;
  157. # define gnu_volatile(x) make_volatile_for_gnu = &x;
  158. #else /* !GNUC broken versions */
  159. # define gnu_volatile(x)
  160. #endif /* !GNUC broken versions */
  161. /******************************* UTILITIES ************************************/
  162. /* Error handling is particularly problematic in production code - error
  163. * handlers often themselves have bugs which lead to programs that detect
  164. * minor errors crashing. The following functions deal with one very
  165. * common class of errors in error handlers - attempting to format error or
  166. * warning messages into buffers that are too small.
  167. */
  168. static size_t safecat(char *buffer, size_t bufsize, size_t pos,
  169. const char *cat)
  170. {
  171. while (pos < bufsize && cat != NULL && *cat != 0)
  172. buffer[pos++] = *cat++;
  173. if (pos >= bufsize)
  174. pos = bufsize-1;
  175. buffer[pos] = 0;
  176. return pos;
  177. }
  178. static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
  179. {
  180. char number[64];
  181. sprintf(number, "%d", n);
  182. return safecat(buffer, bufsize, pos, number);
  183. }
  184. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  185. static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
  186. int precision)
  187. {
  188. char number[64];
  189. sprintf(number, "%.*f", precision, d);
  190. return safecat(buffer, bufsize, pos, number);
  191. }
  192. #endif
  193. static const char invalid[] = "invalid";
  194. static const char sep[] = ": ";
  195. static const char *colour_types[8] =
  196. {
  197. "grayscale", invalid, "truecolour", "indexed-colour",
  198. "grayscale with alpha", invalid, "truecolour with alpha", invalid
  199. };
  200. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  201. /* Convert a double precision value to fixed point. */
  202. static png_fixed_point
  203. fix(double d)
  204. {
  205. d = floor(d * PNG_FP_1 + .5);
  206. return (png_fixed_point)d;
  207. }
  208. #endif /* PNG_READ_SUPPORTED */
  209. /* Generate random bytes. This uses a boring repeatable algorithm and it
  210. * is implemented here so that it gives the same set of numbers on every
  211. * architecture. It's a linear congruential generator (Knuth or Sedgewick
  212. * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
  213. * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
  214. * Generation.)
  215. */
  216. static void
  217. make_random_bytes(png_uint_32* seed, void* pv, size_t size)
  218. {
  219. png_uint_32 u0 = seed[0], u1 = seed[1];
  220. png_bytep bytes = voidcast(png_bytep, pv);
  221. /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
  222. * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
  223. */
  224. size_t i;
  225. for (i=0; i<size; ++i)
  226. {
  227. /* First generate 8 new bits then shift them in at the end. */
  228. png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
  229. u1 <<= 8;
  230. u1 |= u0 >> 24;
  231. u0 <<= 8;
  232. u0 |= u;
  233. *bytes++ = (png_byte)u;
  234. }
  235. seed[0] = u0;
  236. seed[1] = u1;
  237. }
  238. static void
  239. make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
  240. {
  241. make_random_bytes(seed, bytes, 4);
  242. }
  243. #if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED
  244. static void
  245. randomize(void *pv, size_t size)
  246. {
  247. static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
  248. make_random_bytes(random_seed, pv, size);
  249. }
  250. #define RANDOMIZE(this) randomize(&(this), sizeof (this))
  251. #endif /* READ || WRITE_tRNS */
  252. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  253. static unsigned int
  254. random_mod(unsigned int max)
  255. {
  256. unsigned int x;
  257. RANDOMIZE(x);
  258. return x % max; /* 0 .. max-1 */
  259. }
  260. #if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\
  261. (defined PNG_READ_FILLER_SUPPORTED)
  262. static int
  263. random_choice(void)
  264. {
  265. unsigned char x;
  266. RANDOMIZE(x);
  267. return x & 1;
  268. }
  269. #endif
  270. #endif /* PNG_READ_SUPPORTED */
  271. /* A numeric ID based on PNG file characteristics. The 'do_interlace' field
  272. * simply records whether pngvalid did the interlace itself or whether it
  273. * was done by libpng. Width and height must be less than 256. 'palette' is an
  274. * index of the palette to use for formats with a palette otherwise a boolean
  275. * indicating if a tRNS chunk was generated.
  276. */
  277. #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
  278. ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
  279. (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
  280. #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
  281. #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
  282. #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
  283. #define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3))
  284. #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
  285. #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
  286. #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
  287. /* Utility to construct a standard name for a standard image. */
  288. static size_t
  289. standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
  290. int bit_depth, unsigned int npalette, int interlace_type,
  291. png_uint_32 w, png_uint_32 h, int do_interlace)
  292. {
  293. pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
  294. if (colour_type == 3) /* must have a palette */
  295. {
  296. pos = safecat(buffer, bufsize, pos, "[");
  297. pos = safecatn(buffer, bufsize, pos, npalette);
  298. pos = safecat(buffer, bufsize, pos, "]");
  299. }
  300. else if (npalette != 0)
  301. pos = safecat(buffer, bufsize, pos, "+tRNS");
  302. pos = safecat(buffer, bufsize, pos, " ");
  303. pos = safecatn(buffer, bufsize, pos, bit_depth);
  304. pos = safecat(buffer, bufsize, pos, " bit");
  305. if (interlace_type != PNG_INTERLACE_NONE)
  306. {
  307. pos = safecat(buffer, bufsize, pos, " interlaced");
  308. if (do_interlace)
  309. pos = safecat(buffer, bufsize, pos, "(pngvalid)");
  310. else
  311. pos = safecat(buffer, bufsize, pos, "(libpng)");
  312. }
  313. if (w > 0 || h > 0)
  314. {
  315. pos = safecat(buffer, bufsize, pos, " ");
  316. pos = safecatn(buffer, bufsize, pos, w);
  317. pos = safecat(buffer, bufsize, pos, "x");
  318. pos = safecatn(buffer, bufsize, pos, h);
  319. }
  320. return pos;
  321. }
  322. static size_t
  323. standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
  324. {
  325. return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
  326. DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
  327. WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
  328. }
  329. /* Convenience API and defines to list valid formats. Note that 16 bit read and
  330. * write support is required to do 16 bit read tests (we must be able to make a
  331. * 16 bit image to test!)
  332. */
  333. #ifdef PNG_WRITE_16BIT_SUPPORTED
  334. # define WRITE_BDHI 4
  335. # ifdef PNG_READ_16BIT_SUPPORTED
  336. # define READ_BDHI 4
  337. # define DO_16BIT
  338. # endif
  339. #else
  340. # define WRITE_BDHI 3
  341. #endif
  342. #ifndef DO_16BIT
  343. # define READ_BDHI 3
  344. #endif
  345. /* The following defines the number of different palettes to generate for
  346. * each log bit depth of a colour type 3 standard image.
  347. */
  348. #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
  349. static int
  350. next_format(png_bytep colour_type, png_bytep bit_depth,
  351. unsigned int* palette_number, int low_depth_gray, int tRNS)
  352. {
  353. if (*bit_depth == 0)
  354. {
  355. *colour_type = 0;
  356. if (low_depth_gray)
  357. *bit_depth = 1;
  358. else
  359. *bit_depth = 8;
  360. *palette_number = 0;
  361. return 1;
  362. }
  363. if (*colour_type < 4/*no alpha channel*/)
  364. {
  365. /* Add multiple palettes for colour type 3, one image with tRNS
  366. * and one without for other non-alpha formats:
  367. */
  368. unsigned int pn = ++*palette_number;
  369. png_byte ct = *colour_type;
  370. if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
  371. (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
  372. return 1;
  373. /* No: next bit depth */
  374. *palette_number = 0;
  375. }
  376. *bit_depth = (png_byte)(*bit_depth << 1);
  377. /* Palette images are restricted to 8 bit depth */
  378. if (*bit_depth <= 8
  379. #ifdef DO_16BIT
  380. || (*colour_type != 3 && *bit_depth <= 16)
  381. #endif
  382. )
  383. return 1;
  384. /* Move to the next color type, or return 0 at the end. */
  385. switch (*colour_type)
  386. {
  387. case 0:
  388. *colour_type = 2;
  389. *bit_depth = 8;
  390. return 1;
  391. case 2:
  392. *colour_type = 3;
  393. *bit_depth = 1;
  394. return 1;
  395. case 3:
  396. *colour_type = 4;
  397. *bit_depth = 8;
  398. return 1;
  399. case 4:
  400. *colour_type = 6;
  401. *bit_depth = 8;
  402. return 1;
  403. default:
  404. return 0;
  405. }
  406. }
  407. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  408. static unsigned int
  409. sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
  410. png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
  411. {
  412. png_uint_32 bit_index, result;
  413. /* Find a sample index for the desired sample: */
  414. x *= bit_depth;
  415. bit_index = x;
  416. if ((colour_type & 1) == 0) /* !palette */
  417. {
  418. if (colour_type & 2)
  419. bit_index *= 3;
  420. if (colour_type & 4)
  421. bit_index += x; /* Alpha channel */
  422. /* Multiple channels; select one: */
  423. if (colour_type & (2+4))
  424. bit_index += sample_index * bit_depth;
  425. }
  426. /* Return the sample from the row as an integer. */
  427. row += bit_index >> 3;
  428. result = *row;
  429. if (bit_depth == 8)
  430. return result;
  431. else if (bit_depth > 8)
  432. {
  433. if (swap16)
  434. return (*++row << 8) + result;
  435. else
  436. return (result << 8) + *++row;
  437. }
  438. /* Less than 8 bits per sample. By default PNG has the big end of
  439. * the egg on the left of the screen, but if littleendian is set
  440. * then the big end is on the right.
  441. */
  442. bit_index &= 7;
  443. if (!littleendian)
  444. bit_index = 8-bit_index-bit_depth;
  445. return (result >> bit_index) & ((1U<<bit_depth)-1);
  446. }
  447. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  448. /* Copy a single pixel, of a given size, from one buffer to another -
  449. * while this is basically bit addressed there is an implicit assumption
  450. * that pixels 8 or more bits in size are byte aligned and that pixels
  451. * do not otherwise cross byte boundaries. (This is, so far as I know,
  452. * universally true in bitmap computer graphics. [JCB 20101212])
  453. *
  454. * NOTE: The to and from buffers may be the same.
  455. */
  456. static void
  457. pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
  458. png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
  459. int littleendian)
  460. {
  461. /* Assume we can multiply by 'size' without overflow because we are
  462. * just working in a single buffer.
  463. */
  464. toIndex *= pixelSize;
  465. fromIndex *= pixelSize;
  466. if (pixelSize < 8) /* Sub-byte */
  467. {
  468. /* Mask to select the location of the copied pixel: */
  469. unsigned int destMask = ((1U<<pixelSize)-1) <<
  470. (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
  471. /* The following read the entire pixels and clears the extra: */
  472. unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
  473. unsigned int sourceByte = fromBuffer[fromIndex >> 3];
  474. /* Don't rely on << or >> supporting '0' here, just in case: */
  475. fromIndex &= 7;
  476. if (littleendian)
  477. {
  478. if (fromIndex > 0) sourceByte >>= fromIndex;
  479. if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
  480. }
  481. else
  482. {
  483. if (fromIndex > 0) sourceByte <<= fromIndex;
  484. if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
  485. }
  486. toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
  487. }
  488. else /* One or more bytes */
  489. memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
  490. }
  491. #ifdef PNG_READ_SUPPORTED
  492. /* Copy a complete row of pixels, taking into account potential partial
  493. * bytes at the end.
  494. */
  495. static void
  496. row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
  497. int littleendian)
  498. {
  499. memcpy(toBuffer, fromBuffer, bitWidth >> 3);
  500. if ((bitWidth & 7) != 0)
  501. {
  502. unsigned int mask;
  503. toBuffer += bitWidth >> 3;
  504. fromBuffer += bitWidth >> 3;
  505. if (littleendian)
  506. mask = 0xff << (bitWidth & 7);
  507. else
  508. mask = 0xff >> (bitWidth & 7);
  509. *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
  510. }
  511. }
  512. /* Compare pixels - they are assumed to start at the first byte in the
  513. * given buffers.
  514. */
  515. static int
  516. pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
  517. {
  518. #if PNG_LIBPNG_VER < 10506
  519. if (memcmp(pa, pb, bit_width>>3) == 0)
  520. {
  521. png_uint_32 p;
  522. if ((bit_width & 7) == 0) return 0;
  523. /* Ok, any differences? */
  524. p = pa[bit_width >> 3];
  525. p ^= pb[bit_width >> 3];
  526. if (p == 0) return 0;
  527. /* There are, but they may not be significant, remove the bits
  528. * after the end (the low order bits in PNG.)
  529. */
  530. bit_width &= 7;
  531. p >>= 8-bit_width;
  532. if (p == 0) return 0;
  533. }
  534. #else
  535. /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
  536. * bits too:
  537. */
  538. if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
  539. return 0;
  540. #endif
  541. /* Return the index of the changed byte. */
  542. {
  543. png_uint_32 where = 0;
  544. while (pa[where] == pb[where]) ++where;
  545. return 1+where;
  546. }
  547. }
  548. #endif /* PNG_READ_SUPPORTED */
  549. /*************************** BASIC PNG FILE WRITING ***************************/
  550. /* A png_store takes data from the sequential writer or provides data
  551. * to the sequential reader. It can also store the result of a PNG
  552. * write for later retrieval.
  553. */
  554. #define STORE_BUFFER_SIZE 500 /* arbitrary */
  555. typedef struct png_store_buffer
  556. {
  557. struct png_store_buffer* prev; /* NOTE: stored in reverse order */
  558. png_byte buffer[STORE_BUFFER_SIZE];
  559. } png_store_buffer;
  560. #define FILE_NAME_SIZE 64
  561. typedef struct store_palette_entry /* record of a single palette entry */
  562. {
  563. png_byte red;
  564. png_byte green;
  565. png_byte blue;
  566. png_byte alpha;
  567. } store_palette_entry, store_palette[256];
  568. typedef struct png_store_file
  569. {
  570. struct png_store_file* next; /* as many as you like... */
  571. char name[FILE_NAME_SIZE];
  572. png_uint_32 id; /* must be correct (see FILEID) */
  573. png_size_t datacount; /* In this (the last) buffer */
  574. png_store_buffer data; /* Last buffer in file */
  575. int npalette; /* Number of entries in palette */
  576. store_palette_entry* palette; /* May be NULL */
  577. } png_store_file;
  578. /* The following is a pool of memory allocated by a single libpng read or write
  579. * operation.
  580. */
  581. typedef struct store_pool
  582. {
  583. struct png_store *store; /* Back pointer */
  584. struct store_memory *list; /* List of allocated memory */
  585. png_byte mark[4]; /* Before and after data */
  586. /* Statistics for this run. */
  587. png_alloc_size_t max; /* Maximum single allocation */
  588. png_alloc_size_t current; /* Current allocation */
  589. png_alloc_size_t limit; /* Highest current allocation */
  590. png_alloc_size_t total; /* Total allocation */
  591. /* Overall statistics (retained across successive runs). */
  592. png_alloc_size_t max_max;
  593. png_alloc_size_t max_limit;
  594. png_alloc_size_t max_total;
  595. } store_pool;
  596. typedef struct png_store
  597. {
  598. /* For cexcept.h exception handling - simply store one of these;
  599. * the context is a self pointer but it may point to a different
  600. * png_store (in fact it never does in this program.)
  601. */
  602. struct exception_context
  603. exception_context;
  604. unsigned int verbose :1;
  605. unsigned int treat_warnings_as_errors :1;
  606. unsigned int expect_error :1;
  607. unsigned int expect_warning :1;
  608. unsigned int saw_warning :1;
  609. unsigned int speed :1;
  610. unsigned int progressive :1; /* use progressive read */
  611. unsigned int validated :1; /* used as a temporary flag */
  612. int nerrors;
  613. int nwarnings;
  614. int noptions; /* number of options below: */
  615. struct {
  616. unsigned char option; /* option number, 0..30 */
  617. unsigned char setting; /* setting (unset,invalid,on,off) */
  618. } options[16];
  619. char test[128]; /* Name of test */
  620. char error[256];
  621. /* Read fields */
  622. png_structp pread; /* Used to read a saved file */
  623. png_infop piread;
  624. png_store_file* current; /* Set when reading */
  625. png_store_buffer* next; /* Set when reading */
  626. png_size_t readpos; /* Position in *next */
  627. png_byte* image; /* Buffer for reading interlaced images */
  628. png_size_t cb_image; /* Size of this buffer */
  629. png_size_t cb_row; /* Row size of the image(s) */
  630. png_uint_32 image_h; /* Number of rows in a single image */
  631. store_pool read_memory_pool;
  632. /* Write fields */
  633. png_store_file* saved;
  634. png_structp pwrite; /* Used when writing a new file */
  635. png_infop piwrite;
  636. png_size_t writepos; /* Position in .new */
  637. char wname[FILE_NAME_SIZE];
  638. png_store_buffer new; /* The end of the new PNG file being written. */
  639. store_pool write_memory_pool;
  640. store_palette_entry* palette;
  641. int npalette;
  642. } png_store;
  643. /* Initialization and cleanup */
  644. static void
  645. store_pool_mark(png_bytep mark)
  646. {
  647. static png_uint_32 store_seed[2] = { 0x12345678, 1};
  648. make_four_random_bytes(store_seed, mark);
  649. }
  650. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  651. /* Use this for random 32 bit values; this function makes sure the result is
  652. * non-zero.
  653. */
  654. static png_uint_32
  655. random_32(void)
  656. {
  657. for (;;)
  658. {
  659. png_byte mark[4];
  660. png_uint_32 result;
  661. store_pool_mark(mark);
  662. result = png_get_uint_32(mark);
  663. if (result != 0)
  664. return result;
  665. }
  666. }
  667. #endif /* PNG_READ_SUPPORTED */
  668. static void
  669. store_pool_init(png_store *ps, store_pool *pool)
  670. {
  671. memset(pool, 0, sizeof *pool);
  672. pool->store = ps;
  673. pool->list = NULL;
  674. pool->max = pool->current = pool->limit = pool->total = 0;
  675. pool->max_max = pool->max_limit = pool->max_total = 0;
  676. store_pool_mark(pool->mark);
  677. }
  678. static void
  679. store_init(png_store* ps)
  680. {
  681. memset(ps, 0, sizeof *ps);
  682. init_exception_context(&ps->exception_context);
  683. store_pool_init(ps, &ps->read_memory_pool);
  684. store_pool_init(ps, &ps->write_memory_pool);
  685. ps->verbose = 0;
  686. ps->treat_warnings_as_errors = 0;
  687. ps->expect_error = 0;
  688. ps->expect_warning = 0;
  689. ps->saw_warning = 0;
  690. ps->speed = 0;
  691. ps->progressive = 0;
  692. ps->validated = 0;
  693. ps->nerrors = ps->nwarnings = 0;
  694. ps->pread = NULL;
  695. ps->piread = NULL;
  696. ps->saved = ps->current = NULL;
  697. ps->next = NULL;
  698. ps->readpos = 0;
  699. ps->image = NULL;
  700. ps->cb_image = 0;
  701. ps->cb_row = 0;
  702. ps->image_h = 0;
  703. ps->pwrite = NULL;
  704. ps->piwrite = NULL;
  705. ps->writepos = 0;
  706. ps->new.prev = NULL;
  707. ps->palette = NULL;
  708. ps->npalette = 0;
  709. ps->noptions = 0;
  710. }
  711. static void
  712. store_freebuffer(png_store_buffer* psb)
  713. {
  714. if (psb->prev)
  715. {
  716. store_freebuffer(psb->prev);
  717. free(psb->prev);
  718. psb->prev = NULL;
  719. }
  720. }
  721. static void
  722. store_freenew(png_store *ps)
  723. {
  724. store_freebuffer(&ps->new);
  725. ps->writepos = 0;
  726. if (ps->palette != NULL)
  727. {
  728. free(ps->palette);
  729. ps->palette = NULL;
  730. ps->npalette = 0;
  731. }
  732. }
  733. static void
  734. store_storenew(png_store *ps)
  735. {
  736. png_store_buffer *pb;
  737. if (ps->writepos != STORE_BUFFER_SIZE)
  738. png_error(ps->pwrite, "invalid store call");
  739. pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
  740. if (pb == NULL)
  741. png_error(ps->pwrite, "store new: OOM");
  742. *pb = ps->new;
  743. ps->new.prev = pb;
  744. ps->writepos = 0;
  745. }
  746. static void
  747. store_freefile(png_store_file **ppf)
  748. {
  749. if (*ppf != NULL)
  750. {
  751. store_freefile(&(*ppf)->next);
  752. store_freebuffer(&(*ppf)->data);
  753. (*ppf)->datacount = 0;
  754. if ((*ppf)->palette != NULL)
  755. {
  756. free((*ppf)->palette);
  757. (*ppf)->palette = NULL;
  758. (*ppf)->npalette = 0;
  759. }
  760. free(*ppf);
  761. *ppf = NULL;
  762. }
  763. }
  764. /* Main interface to file storeage, after writing a new PNG file (see the API
  765. * below) call store_storefile to store the result with the given name and id.
  766. */
  767. static void
  768. store_storefile(png_store *ps, png_uint_32 id)
  769. {
  770. png_store_file *pf = voidcast(png_store_file*, malloc(sizeof *pf));
  771. if (pf == NULL)
  772. png_error(ps->pwrite, "storefile: OOM");
  773. safecat(pf->name, sizeof pf->name, 0, ps->wname);
  774. pf->id = id;
  775. pf->data = ps->new;
  776. pf->datacount = ps->writepos;
  777. ps->new.prev = NULL;
  778. ps->writepos = 0;
  779. pf->palette = ps->palette;
  780. pf->npalette = ps->npalette;
  781. ps->palette = 0;
  782. ps->npalette = 0;
  783. /* And save it. */
  784. pf->next = ps->saved;
  785. ps->saved = pf;
  786. }
  787. /* Generate an error message (in the given buffer) */
  788. static size_t
  789. store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
  790. size_t pos, const char *msg)
  791. {
  792. if (pp != NULL && pp == ps->pread)
  793. {
  794. /* Reading a file */
  795. pos = safecat(buffer, bufsize, pos, "read: ");
  796. if (ps->current != NULL)
  797. {
  798. pos = safecat(buffer, bufsize, pos, ps->current->name);
  799. pos = safecat(buffer, bufsize, pos, sep);
  800. }
  801. }
  802. else if (pp != NULL && pp == ps->pwrite)
  803. {
  804. /* Writing a file */
  805. pos = safecat(buffer, bufsize, pos, "write: ");
  806. pos = safecat(buffer, bufsize, pos, ps->wname);
  807. pos = safecat(buffer, bufsize, pos, sep);
  808. }
  809. else
  810. {
  811. /* Neither reading nor writing (or a memory error in struct delete) */
  812. pos = safecat(buffer, bufsize, pos, "pngvalid: ");
  813. }
  814. if (ps->test[0] != 0)
  815. {
  816. pos = safecat(buffer, bufsize, pos, ps->test);
  817. pos = safecat(buffer, bufsize, pos, sep);
  818. }
  819. pos = safecat(buffer, bufsize, pos, msg);
  820. return pos;
  821. }
  822. /* Verbose output to the error stream: */
  823. static void
  824. store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
  825. png_const_charp message)
  826. {
  827. char buffer[512];
  828. if (prefix)
  829. fputs(prefix, stderr);
  830. (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
  831. fputs(buffer, stderr);
  832. fputc('\n', stderr);
  833. }
  834. /* Log an error or warning - the relevant count is always incremented. */
  835. static void
  836. store_log(png_store* ps, png_const_structp pp, png_const_charp message,
  837. int is_error)
  838. {
  839. /* The warning is copied to the error buffer if there are no errors and it is
  840. * the first warning. The error is copied to the error buffer if it is the
  841. * first error (overwriting any prior warnings).
  842. */
  843. if (is_error ? (ps->nerrors)++ == 0 :
  844. (ps->nwarnings)++ == 0 && ps->nerrors == 0)
  845. store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
  846. if (ps->verbose)
  847. store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
  848. }
  849. #ifdef PNG_READ_SUPPORTED
  850. /* Internal error function, called with a png_store but no libpng stuff. */
  851. static void
  852. internal_error(png_store *ps, png_const_charp message)
  853. {
  854. store_log(ps, NULL, message, 1 /* error */);
  855. /* And finally throw an exception. */
  856. {
  857. struct exception_context *the_exception_context = &ps->exception_context;
  858. Throw ps;
  859. }
  860. }
  861. #endif /* PNG_READ_SUPPORTED */
  862. /* Functions to use as PNG callbacks. */
  863. static void PNGCBAPI
  864. store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
  865. {
  866. png_const_structp pp = ppIn;
  867. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  868. if (!ps->expect_error)
  869. store_log(ps, pp, message, 1 /* error */);
  870. /* And finally throw an exception. */
  871. {
  872. struct exception_context *the_exception_context = &ps->exception_context;
  873. Throw ps;
  874. }
  875. }
  876. static void PNGCBAPI
  877. store_warning(png_structp ppIn, png_const_charp message)
  878. {
  879. png_const_structp pp = ppIn;
  880. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  881. if (!ps->expect_warning)
  882. store_log(ps, pp, message, 0 /* warning */);
  883. else
  884. ps->saw_warning = 1;
  885. }
  886. /* These somewhat odd functions are used when reading an image to ensure that
  887. * the buffer is big enough, the png_structp is for errors.
  888. */
  889. /* Return a single row from the correct image. */
  890. static png_bytep
  891. store_image_row(const png_store* ps, png_const_structp pp, int nImage,
  892. png_uint_32 y)
  893. {
  894. png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
  895. if (ps->image == NULL)
  896. png_error(pp, "no allocated image");
  897. if (coffset + ps->cb_row + 3 > ps->cb_image)
  898. png_error(pp, "image too small");
  899. return ps->image + coffset;
  900. }
  901. static void
  902. store_image_free(png_store *ps, png_const_structp pp)
  903. {
  904. if (ps->image != NULL)
  905. {
  906. png_bytep image = ps->image;
  907. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  908. {
  909. if (pp != NULL)
  910. png_error(pp, "png_store image overwrite (1)");
  911. else
  912. store_log(ps, NULL, "png_store image overwrite (2)", 1);
  913. }
  914. ps->image = NULL;
  915. ps->cb_image = 0;
  916. --image;
  917. free(image);
  918. }
  919. }
  920. static void
  921. store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
  922. png_size_t cbRow, png_uint_32 cRows)
  923. {
  924. png_size_t cb = nImages * cRows * (cbRow + 5);
  925. if (ps->cb_image < cb)
  926. {
  927. png_bytep image;
  928. store_image_free(ps, pp);
  929. /* The buffer is deliberately mis-aligned. */
  930. image = voidcast(png_bytep, malloc(cb+2));
  931. if (image == NULL)
  932. {
  933. /* Called from the startup - ignore the error for the moment. */
  934. if (pp == NULL)
  935. return;
  936. png_error(pp, "OOM allocating image buffer");
  937. }
  938. /* These magic tags are used to detect overwrites above. */
  939. ++image;
  940. image[-1] = 0xed;
  941. image[cb] = 0xfe;
  942. ps->image = image;
  943. ps->cb_image = cb;
  944. }
  945. /* We have an adequate sized image; lay out the rows. There are 2 bytes at
  946. * the start and three at the end of each (this ensures that the row
  947. * alignment starts out odd - 2+1 and changes for larger images on each row.)
  948. */
  949. ps->cb_row = cbRow;
  950. ps->image_h = cRows;
  951. /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
  952. * This deliberately doesn't match the bits in the size test image which are
  953. * outside the image; these are set to 0xff (all 1). To make the row
  954. * comparison work in the 'size' test case the size rows are pre-initialized
  955. * to the same value prior to calling 'standard_row'.
  956. */
  957. memset(ps->image, 178, cb);
  958. /* Then put in the marks. */
  959. while (--nImages >= 0)
  960. {
  961. png_uint_32 y;
  962. for (y=0; y<cRows; ++y)
  963. {
  964. png_bytep row = store_image_row(ps, pp, nImages, y);
  965. /* The markers: */
  966. row[-2] = 190;
  967. row[-1] = 239;
  968. row[cbRow] = 222;
  969. row[cbRow+1] = 173;
  970. row[cbRow+2] = 17;
  971. }
  972. }
  973. }
  974. #ifdef PNG_READ_SUPPORTED
  975. static void
  976. store_image_check(const png_store* ps, png_const_structp pp, int iImage)
  977. {
  978. png_const_bytep image = ps->image;
  979. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  980. png_error(pp, "image overwrite");
  981. else
  982. {
  983. png_size_t cbRow = ps->cb_row;
  984. png_uint_32 rows = ps->image_h;
  985. image += iImage * (cbRow+5) * ps->image_h;
  986. image += 2; /* skip image first row markers */
  987. while (rows-- > 0)
  988. {
  989. if (image[-2] != 190 || image[-1] != 239)
  990. png_error(pp, "row start overwritten");
  991. if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
  992. image[cbRow+2] != 17)
  993. png_error(pp, "row end overwritten");
  994. image += cbRow+5;
  995. }
  996. }
  997. }
  998. #endif /* PNG_READ_SUPPORTED */
  999. static void PNGCBAPI
  1000. store_write(png_structp ppIn, png_bytep pb, png_size_t st)
  1001. {
  1002. png_const_structp pp = ppIn;
  1003. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  1004. if (ps->pwrite != pp)
  1005. png_error(pp, "store state damaged");
  1006. while (st > 0)
  1007. {
  1008. size_t cb;
  1009. if (ps->writepos >= STORE_BUFFER_SIZE)
  1010. store_storenew(ps);
  1011. cb = st;
  1012. if (cb > STORE_BUFFER_SIZE - ps->writepos)
  1013. cb = STORE_BUFFER_SIZE - ps->writepos;
  1014. memcpy(ps->new.buffer + ps->writepos, pb, cb);
  1015. pb += cb;
  1016. st -= cb;
  1017. ps->writepos += cb;
  1018. }
  1019. }
  1020. static void PNGCBAPI
  1021. store_flush(png_structp ppIn)
  1022. {
  1023. UNUSED(ppIn) /*DOES NOTHING*/
  1024. }
  1025. #ifdef PNG_READ_SUPPORTED
  1026. static size_t
  1027. store_read_buffer_size(png_store *ps)
  1028. {
  1029. /* Return the bytes available for read in the current buffer. */
  1030. if (ps->next != &ps->current->data)
  1031. return STORE_BUFFER_SIZE;
  1032. return ps->current->datacount;
  1033. }
  1034. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  1035. /* Return total bytes available for read. */
  1036. static size_t
  1037. store_read_buffer_avail(png_store *ps)
  1038. {
  1039. if (ps->current != NULL && ps->next != NULL)
  1040. {
  1041. png_store_buffer *next = &ps->current->data;
  1042. size_t cbAvail = ps->current->datacount;
  1043. while (next != ps->next && next != NULL)
  1044. {
  1045. next = next->prev;
  1046. cbAvail += STORE_BUFFER_SIZE;
  1047. }
  1048. if (next != ps->next)
  1049. png_error(ps->pread, "buffer read error");
  1050. if (cbAvail > ps->readpos)
  1051. return cbAvail - ps->readpos;
  1052. }
  1053. return 0;
  1054. }
  1055. #endif
  1056. static int
  1057. store_read_buffer_next(png_store *ps)
  1058. {
  1059. png_store_buffer *pbOld = ps->next;
  1060. png_store_buffer *pbNew = &ps->current->data;
  1061. if (pbOld != pbNew)
  1062. {
  1063. while (pbNew != NULL && pbNew->prev != pbOld)
  1064. pbNew = pbNew->prev;
  1065. if (pbNew != NULL)
  1066. {
  1067. ps->next = pbNew;
  1068. ps->readpos = 0;
  1069. return 1;
  1070. }
  1071. png_error(ps->pread, "buffer lost");
  1072. }
  1073. return 0; /* EOF or error */
  1074. }
  1075. /* Need separate implementation and callback to allow use of the same code
  1076. * during progressive read, where the io_ptr is set internally by libpng.
  1077. */
  1078. static void
  1079. store_read_imp(png_store *ps, png_bytep pb, png_size_t st)
  1080. {
  1081. if (ps->current == NULL || ps->next == NULL)
  1082. png_error(ps->pread, "store state damaged");
  1083. while (st > 0)
  1084. {
  1085. size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
  1086. if (cbAvail > 0)
  1087. {
  1088. if (cbAvail > st) cbAvail = st;
  1089. memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
  1090. st -= cbAvail;
  1091. pb += cbAvail;
  1092. ps->readpos += cbAvail;
  1093. }
  1094. else if (!store_read_buffer_next(ps))
  1095. png_error(ps->pread, "read beyond end of file");
  1096. }
  1097. }
  1098. static void PNGCBAPI
  1099. store_read(png_structp ppIn, png_bytep pb, png_size_t st)
  1100. {
  1101. png_const_structp pp = ppIn;
  1102. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  1103. if (ps == NULL || ps->pread != pp)
  1104. png_error(pp, "bad store read call");
  1105. store_read_imp(ps, pb, st);
  1106. }
  1107. static void
  1108. store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
  1109. {
  1110. /* Notice that a call to store_read will cause this function to fail because
  1111. * readpos will be set.
  1112. */
  1113. if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
  1114. png_error(pp, "store state damaged (progressive)");
  1115. do
  1116. {
  1117. if (ps->readpos != 0)
  1118. png_error(pp, "store_read called during progressive read");
  1119. png_process_data(pp, pi, ps->next->buffer, store_read_buffer_size(ps));
  1120. }
  1121. while (store_read_buffer_next(ps));
  1122. }
  1123. #endif /* PNG_READ_SUPPORTED */
  1124. /* The caller must fill this in: */
  1125. static store_palette_entry *
  1126. store_write_palette(png_store *ps, int npalette)
  1127. {
  1128. if (ps->pwrite == NULL)
  1129. store_log(ps, NULL, "attempt to write palette without write stream", 1);
  1130. if (ps->palette != NULL)
  1131. png_error(ps->pwrite, "multiple store_write_palette calls");
  1132. /* This function can only return NULL if called with '0'! */
  1133. if (npalette > 0)
  1134. {
  1135. ps->palette = voidcast(store_palette_entry*, malloc(npalette *
  1136. sizeof *ps->palette));
  1137. if (ps->palette == NULL)
  1138. png_error(ps->pwrite, "store new palette: OOM");
  1139. ps->npalette = npalette;
  1140. }
  1141. return ps->palette;
  1142. }
  1143. #ifdef PNG_READ_SUPPORTED
  1144. static store_palette_entry *
  1145. store_current_palette(png_store *ps, int *npalette)
  1146. {
  1147. /* This is an internal error (the call has been made outside a read
  1148. * operation.)
  1149. */
  1150. if (ps->current == NULL)
  1151. {
  1152. store_log(ps, ps->pread, "no current stream for palette", 1);
  1153. return NULL;
  1154. }
  1155. /* The result may be null if there is no palette. */
  1156. *npalette = ps->current->npalette;
  1157. return ps->current->palette;
  1158. }
  1159. #endif /* PNG_READ_SUPPORTED */
  1160. /***************************** MEMORY MANAGEMENT*** ***************************/
  1161. #ifdef PNG_USER_MEM_SUPPORTED
  1162. /* A store_memory is simply the header for an allocated block of memory. The
  1163. * pointer returned to libpng is just after the end of the header block, the
  1164. * allocated memory is followed by a second copy of the 'mark'.
  1165. */
  1166. typedef struct store_memory
  1167. {
  1168. store_pool *pool; /* Originating pool */
  1169. struct store_memory *next; /* Singly linked list */
  1170. png_alloc_size_t size; /* Size of memory allocated */
  1171. png_byte mark[4]; /* ID marker */
  1172. } store_memory;
  1173. /* Handle a fatal error in memory allocation. This calls png_error if the
  1174. * libpng struct is non-NULL, else it outputs a message and returns. This means
  1175. * that a memory problem while libpng is running will abort (png_error) the
  1176. * handling of particular file while one in cleanup (after the destroy of the
  1177. * struct has returned) will simply keep going and free (or attempt to free)
  1178. * all the memory.
  1179. */
  1180. static void
  1181. store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
  1182. {
  1183. if (pp != NULL)
  1184. png_error(pp, msg);
  1185. /* Else we have to do it ourselves. png_error eventually calls store_log,
  1186. * above. store_log accepts a NULL png_structp - it just changes what gets
  1187. * output by store_message.
  1188. */
  1189. store_log(ps, pp, msg, 1 /* error */);
  1190. }
  1191. static void
  1192. store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
  1193. {
  1194. /* Note that pp may be NULL (see store_pool_delete below), the caller has
  1195. * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
  1196. * pointer (for sure), but the contents may have been trashed.
  1197. */
  1198. if (memory->pool != pool)
  1199. store_pool_error(pool->store, pp, "memory corrupted (pool)");
  1200. else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
  1201. store_pool_error(pool->store, pp, "memory corrupted (start)");
  1202. /* It should be safe to read the size field now. */
  1203. else
  1204. {
  1205. png_alloc_size_t cb = memory->size;
  1206. if (cb > pool->max)
  1207. store_pool_error(pool->store, pp, "memory corrupted (size)");
  1208. else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
  1209. != 0)
  1210. store_pool_error(pool->store, pp, "memory corrupted (end)");
  1211. /* Finally give the library a chance to find problems too: */
  1212. else
  1213. {
  1214. pool->current -= cb;
  1215. free(memory);
  1216. }
  1217. }
  1218. }
  1219. static void
  1220. store_pool_delete(png_store *ps, store_pool *pool)
  1221. {
  1222. if (pool->list != NULL)
  1223. {
  1224. fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
  1225. pool == &ps->read_memory_pool ? "read" : "write",
  1226. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1227. ps->current->name : "unknown file") : ps->wname);
  1228. ++ps->nerrors;
  1229. do
  1230. {
  1231. store_memory *next = pool->list;
  1232. pool->list = next->next;
  1233. next->next = NULL;
  1234. fprintf(stderr, "\t%lu bytes @ %p\n",
  1235. (unsigned long)next->size, (const void*)(next+1));
  1236. /* The NULL means this will always return, even if the memory is
  1237. * corrupted.
  1238. */
  1239. store_memory_free(NULL, pool, next);
  1240. }
  1241. while (pool->list != NULL);
  1242. }
  1243. /* And reset the other fields too for the next time. */
  1244. if (pool->max > pool->max_max) pool->max_max = pool->max;
  1245. pool->max = 0;
  1246. if (pool->current != 0) /* unexpected internal error */
  1247. fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
  1248. ps->test, pool == &ps->read_memory_pool ? "read" : "write",
  1249. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1250. ps->current->name : "unknown file") : ps->wname);
  1251. pool->current = 0;
  1252. if (pool->limit > pool->max_limit)
  1253. pool->max_limit = pool->limit;
  1254. pool->limit = 0;
  1255. if (pool->total > pool->max_total)
  1256. pool->max_total = pool->total;
  1257. pool->total = 0;
  1258. /* Get a new mark too. */
  1259. store_pool_mark(pool->mark);
  1260. }
  1261. /* The memory callbacks: */
  1262. static png_voidp PNGCBAPI
  1263. store_malloc(png_structp ppIn, png_alloc_size_t cb)
  1264. {
  1265. png_const_structp pp = ppIn;
  1266. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1267. store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
  1268. (sizeof pool->mark)));
  1269. if (new != NULL)
  1270. {
  1271. if (cb > pool->max)
  1272. pool->max = cb;
  1273. pool->current += cb;
  1274. if (pool->current > pool->limit)
  1275. pool->limit = pool->current;
  1276. pool->total += cb;
  1277. new->size = cb;
  1278. memcpy(new->mark, pool->mark, sizeof new->mark);
  1279. memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
  1280. new->pool = pool;
  1281. new->next = pool->list;
  1282. pool->list = new;
  1283. ++new;
  1284. }
  1285. else
  1286. {
  1287. /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
  1288. * other than to retrieve the allocation pointer! libpng calls the
  1289. * store_malloc callback in two basic cases:
  1290. *
  1291. * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
  1292. * returned.
  1293. * 2) From png_struct or png_info structure creation; png_malloc is
  1294. * to return so cleanup can be performed.
  1295. *
  1296. * To handle this store_malloc can log a message, but can't do anything
  1297. * else.
  1298. */
  1299. store_log(pool->store, pp, "out of memory", 1 /* is_error */);
  1300. }
  1301. return new;
  1302. }
  1303. static void PNGCBAPI
  1304. store_free(png_structp ppIn, png_voidp memory)
  1305. {
  1306. png_const_structp pp = ppIn;
  1307. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1308. store_memory *this = voidcast(store_memory*, memory), **test;
  1309. /* Because libpng calls store_free with a dummy png_struct when deleting
  1310. * png_struct or png_info via png_destroy_struct_2 it is necessary to check
  1311. * the passed in png_structp to ensure it is valid, and not pass it to
  1312. * png_error if it is not.
  1313. */
  1314. if (pp != pool->store->pread && pp != pool->store->pwrite)
  1315. pp = NULL;
  1316. /* First check that this 'memory' really is valid memory - it must be in the
  1317. * pool list. If it is, use the shared memory_free function to free it.
  1318. */
  1319. --this;
  1320. for (test = &pool->list; *test != this; test = &(*test)->next)
  1321. {
  1322. if (*test == NULL)
  1323. {
  1324. store_pool_error(pool->store, pp, "bad pointer to free");
  1325. return;
  1326. }
  1327. }
  1328. /* Unlink this entry, *test == this. */
  1329. *test = this->next;
  1330. this->next = NULL;
  1331. store_memory_free(pp, pool, this);
  1332. }
  1333. #endif /* PNG_USER_MEM_SUPPORTED */
  1334. /* Setup functions. */
  1335. /* Cleanup when aborting a write or after storing the new file. */
  1336. static void
  1337. store_write_reset(png_store *ps)
  1338. {
  1339. if (ps->pwrite != NULL)
  1340. {
  1341. anon_context(ps);
  1342. Try
  1343. png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
  1344. Catch_anonymous
  1345. {
  1346. /* memory corruption: continue. */
  1347. }
  1348. ps->pwrite = NULL;
  1349. ps->piwrite = NULL;
  1350. }
  1351. /* And make sure that all the memory has been freed - this will output
  1352. * spurious errors in the case of memory corruption above, but this is safe.
  1353. */
  1354. # ifdef PNG_USER_MEM_SUPPORTED
  1355. store_pool_delete(ps, &ps->write_memory_pool);
  1356. # endif
  1357. store_freenew(ps);
  1358. }
  1359. /* The following is the main write function, it returns a png_struct and,
  1360. * optionally, a png_info suitable for writiing a new PNG file. Use
  1361. * store_storefile above to record this file after it has been written. The
  1362. * returned libpng structures as destroyed by store_write_reset above.
  1363. */
  1364. static png_structp
  1365. set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
  1366. {
  1367. anon_context(ps);
  1368. Try
  1369. {
  1370. if (ps->pwrite != NULL)
  1371. png_error(ps->pwrite, "write store already in use");
  1372. store_write_reset(ps);
  1373. safecat(ps->wname, sizeof ps->wname, 0, name);
  1374. /* Don't do the slow memory checks if doing a speed test, also if user
  1375. * memory is not supported we can't do it anyway.
  1376. */
  1377. # ifdef PNG_USER_MEM_SUPPORTED
  1378. if (!ps->speed)
  1379. ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
  1380. ps, store_error, store_warning, &ps->write_memory_pool,
  1381. store_malloc, store_free);
  1382. else
  1383. # endif
  1384. ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  1385. ps, store_error, store_warning);
  1386. png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
  1387. # ifdef PNG_SET_OPTION_SUPPORTED
  1388. {
  1389. int opt;
  1390. for (opt=0; opt<ps->noptions; ++opt)
  1391. if (png_set_option(ps->pwrite, ps->options[opt].option,
  1392. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1393. png_error(ps->pwrite, "png option invalid");
  1394. }
  1395. # endif
  1396. if (ppi != NULL)
  1397. *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
  1398. }
  1399. Catch_anonymous
  1400. return NULL;
  1401. return ps->pwrite;
  1402. }
  1403. /* Cleanup when finished reading (either due to error or in the success case).
  1404. * This routine exists even when there is no read support to make the code
  1405. * tidier (avoid a mass of ifdefs) and so easier to maintain.
  1406. */
  1407. static void
  1408. store_read_reset(png_store *ps)
  1409. {
  1410. # ifdef PNG_READ_SUPPORTED
  1411. if (ps->pread != NULL)
  1412. {
  1413. anon_context(ps);
  1414. Try
  1415. png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
  1416. Catch_anonymous
  1417. {
  1418. /* error already output: continue */
  1419. }
  1420. ps->pread = NULL;
  1421. ps->piread = NULL;
  1422. }
  1423. # endif
  1424. # ifdef PNG_USER_MEM_SUPPORTED
  1425. /* Always do this to be safe. */
  1426. store_pool_delete(ps, &ps->read_memory_pool);
  1427. # endif
  1428. ps->current = NULL;
  1429. ps->next = NULL;
  1430. ps->readpos = 0;
  1431. ps->validated = 0;
  1432. }
  1433. #ifdef PNG_READ_SUPPORTED
  1434. static void
  1435. store_read_set(png_store *ps, png_uint_32 id)
  1436. {
  1437. png_store_file *pf = ps->saved;
  1438. while (pf != NULL)
  1439. {
  1440. if (pf->id == id)
  1441. {
  1442. ps->current = pf;
  1443. ps->next = NULL;
  1444. store_read_buffer_next(ps);
  1445. return;
  1446. }
  1447. pf = pf->next;
  1448. }
  1449. {
  1450. size_t pos;
  1451. char msg[FILE_NAME_SIZE+64];
  1452. pos = standard_name_from_id(msg, sizeof msg, 0, id);
  1453. pos = safecat(msg, sizeof msg, pos, ": file not found");
  1454. png_error(ps->pread, msg);
  1455. }
  1456. }
  1457. /* The main interface for reading a saved file - pass the id number of the file
  1458. * to retrieve. Ids must be unique or the earlier file will be hidden. The API
  1459. * returns a png_struct and, optionally, a png_info. Both of these will be
  1460. * destroyed by store_read_reset above.
  1461. */
  1462. static png_structp
  1463. set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
  1464. const char *name)
  1465. {
  1466. /* Set the name for png_error */
  1467. safecat(ps->test, sizeof ps->test, 0, name);
  1468. if (ps->pread != NULL)
  1469. png_error(ps->pread, "read store already in use");
  1470. store_read_reset(ps);
  1471. /* Both the create APIs can return NULL if used in their default mode
  1472. * (because there is no other way of handling an error because the jmp_buf
  1473. * by default is stored in png_struct and that has not been allocated!)
  1474. * However, given that store_error works correctly in these circumstances
  1475. * we don't ever expect NULL in this program.
  1476. */
  1477. # ifdef PNG_USER_MEM_SUPPORTED
  1478. if (!ps->speed)
  1479. ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
  1480. store_error, store_warning, &ps->read_memory_pool, store_malloc,
  1481. store_free);
  1482. else
  1483. # endif
  1484. ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
  1485. store_warning);
  1486. if (ps->pread == NULL)
  1487. {
  1488. struct exception_context *the_exception_context = &ps->exception_context;
  1489. store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
  1490. 1 /*error*/);
  1491. Throw ps;
  1492. }
  1493. # ifdef PNG_SET_OPTION_SUPPORTED
  1494. {
  1495. int opt;
  1496. for (opt=0; opt<ps->noptions; ++opt)
  1497. if (png_set_option(ps->pread, ps->options[opt].option,
  1498. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1499. png_error(ps->pread, "png option invalid");
  1500. }
  1501. # endif
  1502. store_read_set(ps, id);
  1503. if (ppi != NULL)
  1504. *ppi = ps->piread = png_create_info_struct(ps->pread);
  1505. return ps->pread;
  1506. }
  1507. #endif /* PNG_READ_SUPPORTED */
  1508. /* The overall cleanup of a store simply calls the above then removes all the
  1509. * saved files. This does not delete the store itself.
  1510. */
  1511. static void
  1512. store_delete(png_store *ps)
  1513. {
  1514. store_write_reset(ps);
  1515. store_read_reset(ps);
  1516. store_freefile(&ps->saved);
  1517. store_image_free(ps, NULL);
  1518. }
  1519. /*********************** PNG FILE MODIFICATION ON READ ************************/
  1520. /* Files may be modified on read. The following structure contains a complete
  1521. * png_store together with extra members to handle modification and a special
  1522. * read callback for libpng. To use this the 'modifications' field must be set
  1523. * to a list of png_modification structures that actually perform the
  1524. * modification, otherwise a png_modifier is functionally equivalent to a
  1525. * png_store. There is a special read function, set_modifier_for_read, which
  1526. * replaces set_store_for_read.
  1527. */
  1528. typedef enum modifier_state
  1529. {
  1530. modifier_start, /* Initial value */
  1531. modifier_signature, /* Have a signature */
  1532. modifier_IHDR /* Have an IHDR */
  1533. } modifier_state;
  1534. typedef struct CIE_color
  1535. {
  1536. /* A single CIE tristimulus value, representing the unique response of a
  1537. * standard observer to a variety of light spectra. The observer recognizes
  1538. * all spectra that produce this response as the same color, therefore this
  1539. * is effectively a description of a color.
  1540. */
  1541. double X, Y, Z;
  1542. } CIE_color;
  1543. typedef struct color_encoding
  1544. {
  1545. /* A description of an (R,G,B) encoding of color (as defined above); this
  1546. * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
  1547. * (0,0,1) plus an encoding value that is used to encode the linear
  1548. * components R, G and B to give the actual values R^gamma, G^gamma and
  1549. * B^gamma that are stored.
  1550. */
  1551. double gamma; /* Encoding (file) gamma of space */
  1552. CIE_color red, green, blue; /* End points */
  1553. } color_encoding;
  1554. #ifdef PNG_READ_SUPPORTED
  1555. #if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED
  1556. static double
  1557. chromaticity_x(CIE_color c)
  1558. {
  1559. return c.X / (c.X + c.Y + c.Z);
  1560. }
  1561. static double
  1562. chromaticity_y(CIE_color c)
  1563. {
  1564. return c.Y / (c.X + c.Y + c.Z);
  1565. }
  1566. static CIE_color
  1567. white_point(const color_encoding *encoding)
  1568. {
  1569. CIE_color white;
  1570. white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
  1571. white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
  1572. white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
  1573. return white;
  1574. }
  1575. #endif /* READ_TRANSFORMS && READ_cHRM */
  1576. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1577. static void
  1578. normalize_color_encoding(color_encoding *encoding)
  1579. {
  1580. const double whiteY = encoding->red.Y + encoding->green.Y +
  1581. encoding->blue.Y;
  1582. if (whiteY != 1)
  1583. {
  1584. encoding->red.X /= whiteY;
  1585. encoding->red.Y /= whiteY;
  1586. encoding->red.Z /= whiteY;
  1587. encoding->green.X /= whiteY;
  1588. encoding->green.Y /= whiteY;
  1589. encoding->green.Z /= whiteY;
  1590. encoding->blue.X /= whiteY;
  1591. encoding->blue.Y /= whiteY;
  1592. encoding->blue.Z /= whiteY;
  1593. }
  1594. }
  1595. #endif
  1596. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  1597. static size_t
  1598. safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
  1599. const color_encoding *e, double encoding_gamma)
  1600. {
  1601. if (e != 0)
  1602. {
  1603. if (encoding_gamma != 0)
  1604. pos = safecat(buffer, bufsize, pos, "(");
  1605. pos = safecat(buffer, bufsize, pos, "R(");
  1606. pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
  1607. pos = safecat(buffer, bufsize, pos, ",");
  1608. pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
  1609. pos = safecat(buffer, bufsize, pos, ",");
  1610. pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
  1611. pos = safecat(buffer, bufsize, pos, "),G(");
  1612. pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
  1613. pos = safecat(buffer, bufsize, pos, ",");
  1614. pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
  1615. pos = safecat(buffer, bufsize, pos, ",");
  1616. pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
  1617. pos = safecat(buffer, bufsize, pos, "),B(");
  1618. pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
  1619. pos = safecat(buffer, bufsize, pos, ",");
  1620. pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
  1621. pos = safecat(buffer, bufsize, pos, ",");
  1622. pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
  1623. pos = safecat(buffer, bufsize, pos, ")");
  1624. if (encoding_gamma != 0)
  1625. pos = safecat(buffer, bufsize, pos, ")");
  1626. }
  1627. if (encoding_gamma != 0)
  1628. {
  1629. pos = safecat(buffer, bufsize, pos, "^");
  1630. pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
  1631. }
  1632. return pos;
  1633. }
  1634. #endif /* READ_TRANSFORMS */
  1635. #endif /* PNG_READ_SUPPORTED */
  1636. typedef struct png_modifier
  1637. {
  1638. png_store this; /* I am a png_store */
  1639. struct png_modification *modifications; /* Changes to make */
  1640. modifier_state state; /* My state */
  1641. /* Information from IHDR: */
  1642. png_byte bit_depth; /* From IHDR */
  1643. png_byte colour_type; /* From IHDR */
  1644. /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
  1645. * other chunks to be inserted.
  1646. */
  1647. png_uint_32 pending_len;
  1648. png_uint_32 pending_chunk;
  1649. /* Test values */
  1650. double *gammas;
  1651. unsigned int ngammas;
  1652. unsigned int ngamma_tests; /* Number of gamma tests to run*/
  1653. double current_gamma; /* 0 if not set */
  1654. const color_encoding *encodings;
  1655. unsigned int nencodings;
  1656. const color_encoding *current_encoding; /* If an encoding has been set */
  1657. unsigned int encoding_counter; /* For iteration */
  1658. int encoding_ignored; /* Something overwrote it */
  1659. /* Control variables used to iterate through possible encodings, the
  1660. * following must be set to 0 and tested by the function that uses the
  1661. * png_modifier because the modifier only sets it to 1 (true.)
  1662. */
  1663. unsigned int repeat :1; /* Repeat this transform test. */
  1664. unsigned int test_uses_encoding :1;
  1665. /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */
  1666. png_byte sbitlow;
  1667. /* Error control - these are the limits on errors accepted by the gamma tests
  1668. * below.
  1669. */
  1670. double maxout8; /* Maximum output value error */
  1671. double maxabs8; /* Absolute sample error 0..1 */
  1672. double maxcalc8; /* Absolute sample error 0..1 */
  1673. double maxpc8; /* Percentage sample error 0..100% */
  1674. double maxout16; /* Maximum output value error */
  1675. double maxabs16; /* Absolute sample error 0..1 */
  1676. double maxcalc16;/* Absolute sample error 0..1 */
  1677. double maxcalcG; /* Absolute sample error 0..1 */
  1678. double maxpc16; /* Percentage sample error 0..100% */
  1679. /* This is set by transforms that need to allow a higher limit, it is an
  1680. * internal check on pngvalid to ensure that the calculated error limits are
  1681. * not ridiculous; without this it is too easy to make a mistake in pngvalid
  1682. * that allows any value through.
  1683. */
  1684. double limit; /* limit on error values, normally 4E-3 */
  1685. /* Log limits - values above this are logged, but not necessarily
  1686. * warned.
  1687. */
  1688. double log8; /* Absolute error in 8 bits to log */
  1689. double log16; /* Absolute error in 16 bits to log */
  1690. /* Logged 8 and 16 bit errors ('output' values): */
  1691. double error_gray_2;
  1692. double error_gray_4;
  1693. double error_gray_8;
  1694. double error_gray_16;
  1695. double error_color_8;
  1696. double error_color_16;
  1697. double error_indexed;
  1698. /* Flags: */
  1699. /* Whether to call png_read_update_info, not png_read_start_image, and how
  1700. * many times to call it.
  1701. */
  1702. int use_update_info;
  1703. /* Whether or not to interlace. */
  1704. int interlace_type :9; /* int, but must store '1' */
  1705. /* Run the standard tests? */
  1706. unsigned int test_standard :1;
  1707. /* Run the odd-sized image and interlace read/write tests? */
  1708. unsigned int test_size :1;
  1709. /* Run tests on reading with a combination of transforms, */
  1710. unsigned int test_transform :1;
  1711. unsigned int test_tRNS :1; /* Includes tRNS images */
  1712. /* When to use the use_input_precision option, this controls the gamma
  1713. * validation code checks. If set any value that is within the transformed
  1714. * range input-.5 to input+.5 will be accepted, otherwise the value must be
  1715. * within the normal limits. It should not be necessary to set this; the
  1716. * result should always be exact within the permitted error limits.
  1717. */
  1718. unsigned int use_input_precision :1;
  1719. unsigned int use_input_precision_sbit :1;
  1720. unsigned int use_input_precision_16to8 :1;
  1721. /* If set assume that the calculation bit depth is set by the input
  1722. * precision, not the output precision.
  1723. */
  1724. unsigned int calculations_use_input_precision :1;
  1725. /* If set assume that the calculations are done in 16 bits even if the sample
  1726. * depth is 8 bits.
  1727. */
  1728. unsigned int assume_16_bit_calculations :1;
  1729. /* Which gamma tests to run: */
  1730. unsigned int test_gamma_threshold :1;
  1731. unsigned int test_gamma_transform :1; /* main tests */
  1732. unsigned int test_gamma_sbit :1;
  1733. unsigned int test_gamma_scale16 :1;
  1734. unsigned int test_gamma_background :1;
  1735. unsigned int test_gamma_alpha_mode :1;
  1736. unsigned int test_gamma_expand16 :1;
  1737. unsigned int test_exhaustive :1;
  1738. /* Whether or not to run the low-bit-depth grayscale tests. This fails on
  1739. * gamma images in some cases because of gross inaccuracies in the grayscale
  1740. * gamma handling for low bit depth.
  1741. */
  1742. unsigned int test_lbg :1;
  1743. unsigned int test_lbg_gamma_threshold :1;
  1744. unsigned int test_lbg_gamma_transform :1;
  1745. unsigned int test_lbg_gamma_sbit :1;
  1746. unsigned int test_lbg_gamma_composition :1;
  1747. unsigned int log :1; /* Log max error */
  1748. /* Buffer information, the buffer size limits the size of the chunks that can
  1749. * be modified - they must fit (including header and CRC) into the buffer!
  1750. */
  1751. size_t flush; /* Count of bytes to flush */
  1752. size_t buffer_count; /* Bytes in buffer */
  1753. size_t buffer_position; /* Position in buffer */
  1754. png_byte buffer[1024];
  1755. } png_modifier;
  1756. /* This returns true if the test should be stopped now because it has already
  1757. * failed and it is running silently.
  1758. */
  1759. static int fail(png_modifier *pm)
  1760. {
  1761. return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
  1762. (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
  1763. }
  1764. static void
  1765. modifier_init(png_modifier *pm)
  1766. {
  1767. memset(pm, 0, sizeof *pm);
  1768. store_init(&pm->this);
  1769. pm->modifications = NULL;
  1770. pm->state = modifier_start;
  1771. pm->sbitlow = 1U;
  1772. pm->ngammas = 0;
  1773. pm->ngamma_tests = 0;
  1774. pm->gammas = 0;
  1775. pm->current_gamma = 0;
  1776. pm->encodings = 0;
  1777. pm->nencodings = 0;
  1778. pm->current_encoding = 0;
  1779. pm->encoding_counter = 0;
  1780. pm->encoding_ignored = 0;
  1781. pm->repeat = 0;
  1782. pm->test_uses_encoding = 0;
  1783. pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
  1784. pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
  1785. pm->maxcalcG = 0;
  1786. pm->limit = 4E-3;
  1787. pm->log8 = pm->log16 = 0; /* Means 'off' */
  1788. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
  1789. pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
  1790. pm->error_indexed = 0;
  1791. pm->use_update_info = 0;
  1792. pm->interlace_type = PNG_INTERLACE_NONE;
  1793. pm->test_standard = 0;
  1794. pm->test_size = 0;
  1795. pm->test_transform = 0;
  1796. # ifdef PNG_WRITE_tRNS_SUPPORTED
  1797. pm->test_tRNS = 1;
  1798. # else
  1799. pm->test_tRNS = 0;
  1800. # endif
  1801. pm->use_input_precision = 0;
  1802. pm->use_input_precision_sbit = 0;
  1803. pm->use_input_precision_16to8 = 0;
  1804. pm->calculations_use_input_precision = 0;
  1805. pm->assume_16_bit_calculations = 0;
  1806. pm->test_gamma_threshold = 0;
  1807. pm->test_gamma_transform = 0;
  1808. pm->test_gamma_sbit = 0;
  1809. pm->test_gamma_scale16 = 0;
  1810. pm->test_gamma_background = 0;
  1811. pm->test_gamma_alpha_mode = 0;
  1812. pm->test_gamma_expand16 = 0;
  1813. pm->test_lbg = 1;
  1814. pm->test_lbg_gamma_threshold = 1;
  1815. pm->test_lbg_gamma_transform = 1;
  1816. pm->test_lbg_gamma_sbit = 1;
  1817. pm->test_lbg_gamma_composition = 1;
  1818. pm->test_exhaustive = 0;
  1819. pm->log = 0;
  1820. /* Rely on the memset for all the other fields - there are no pointers */
  1821. }
  1822. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  1823. /* This controls use of checks that explicitly know how libpng digitizes the
  1824. * samples in calculations; setting this circumvents simple error limit checking
  1825. * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
  1826. * algorithm.
  1827. */
  1828. #define DIGITIZE PNG_LIBPNG_VER < 10700
  1829. /* If pm->calculations_use_input_precision is set then operations will happen
  1830. * with the precision of the input, not the precision of the output depth.
  1831. *
  1832. * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
  1833. * bit precision. This only affects those of the following limits that pertain
  1834. * to a calculation - not a digitization operation - unless the following API is
  1835. * called directly.
  1836. */
  1837. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1838. #if DIGITIZE
  1839. static double digitize(double value, int depth, int do_round)
  1840. {
  1841. /* 'value' is in the range 0 to 1, the result is the same value rounded to a
  1842. * multiple of the digitization factor - 8 or 16 bits depending on both the
  1843. * sample depth and the 'assume' setting. Digitization is normally by
  1844. * rounding and 'do_round' should be 1, if it is 0 the digitized value will
  1845. * be truncated.
  1846. */
  1847. const unsigned int digitization_factor = (1U << depth) -1;
  1848. /* Limiting the range is done as a convenience to the caller - it's easier to
  1849. * do it once here than every time at the call site.
  1850. */
  1851. if (value <= 0)
  1852. value = 0;
  1853. else if (value >= 1)
  1854. value = 1;
  1855. value *= digitization_factor;
  1856. if (do_round) value += .5;
  1857. return floor(value)/digitization_factor;
  1858. }
  1859. #endif
  1860. #endif /* RGB_TO_GRAY */
  1861. #ifdef PNG_READ_GAMMA_SUPPORTED
  1862. static double abserr(const png_modifier *pm, int in_depth, int out_depth)
  1863. {
  1864. /* Absolute error permitted in linear values - affected by the bit depth of
  1865. * the calculations.
  1866. */
  1867. if (pm->assume_16_bit_calculations ||
  1868. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1869. return pm->maxabs16;
  1870. else
  1871. return pm->maxabs8;
  1872. }
  1873. static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
  1874. {
  1875. /* Error in the linear composition arithmetic - only relevant when
  1876. * composition actually happens (0 < alpha < 1).
  1877. */
  1878. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1879. return pm->maxcalc16;
  1880. else if (pm->assume_16_bit_calculations)
  1881. return pm->maxcalcG;
  1882. else
  1883. return pm->maxcalc8;
  1884. }
  1885. static double pcerr(const png_modifier *pm, int in_depth, int out_depth)
  1886. {
  1887. /* Percentage error permitted in the linear values. Note that the specified
  1888. * value is a percentage but this routine returns a simple number.
  1889. */
  1890. if (pm->assume_16_bit_calculations ||
  1891. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1892. return pm->maxpc16 * .01;
  1893. else
  1894. return pm->maxpc8 * .01;
  1895. }
  1896. /* Output error - the error in the encoded value. This is determined by the
  1897. * digitization of the output so can be +/-0.5 in the actual output value. In
  1898. * the expand_16 case with the current code in libpng the expand happens after
  1899. * all the calculations are done in 8 bit arithmetic, so even though the output
  1900. * depth is 16 the output error is determined by the 8 bit calculation.
  1901. *
  1902. * This limit is not determined by the bit depth of internal calculations.
  1903. *
  1904. * The specified parameter does *not* include the base .5 digitization error but
  1905. * it is added here.
  1906. */
  1907. static double outerr(const png_modifier *pm, int in_depth, int out_depth)
  1908. {
  1909. /* There is a serious error in the 2 and 4 bit grayscale transform because
  1910. * the gamma table value (8 bits) is simply shifted, not rounded, so the
  1911. * error in 4 bit grayscale gamma is up to the value below. This is a hack
  1912. * to allow pngvalid to succeed:
  1913. *
  1914. * TODO: fix this in libpng
  1915. */
  1916. if (out_depth == 2)
  1917. return .73182-.5;
  1918. if (out_depth == 4)
  1919. return .90644-.5;
  1920. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1921. return pm->maxout16;
  1922. /* This is the case where the value was calculated at 8-bit precision then
  1923. * scaled to 16 bits.
  1924. */
  1925. else if (out_depth == 16)
  1926. return pm->maxout8 * 257;
  1927. else
  1928. return pm->maxout8;
  1929. }
  1930. /* This does the same thing as the above however it returns the value to log,
  1931. * rather than raising a warning. This is useful for debugging to track down
  1932. * exactly what set of parameters cause high error values.
  1933. */
  1934. static double outlog(const png_modifier *pm, int in_depth, int out_depth)
  1935. {
  1936. /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
  1937. * and so must be adjusted for low bit depth grayscale:
  1938. */
  1939. if (out_depth <= 8)
  1940. {
  1941. if (pm->log8 == 0) /* switched off */
  1942. return 256;
  1943. if (out_depth < 8)
  1944. return pm->log8 / 255 * ((1<<out_depth)-1);
  1945. return pm->log8;
  1946. }
  1947. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  1948. {
  1949. if (pm->log16 == 0)
  1950. return 65536;
  1951. return pm->log16;
  1952. }
  1953. /* This is the case where the value was calculated at 8-bit precision then
  1954. * scaled to 16 bits.
  1955. */
  1956. if (pm->log8 == 0)
  1957. return 65536;
  1958. return pm->log8 * 257;
  1959. }
  1960. /* This complements the above by providing the appropriate quantization for the
  1961. * final value. Normally this would just be quantization to an integral value,
  1962. * but in the 8 bit calculation case it's actually quantization to a multiple of
  1963. * 257!
  1964. */
  1965. static int output_quantization_factor(const png_modifier *pm, int in_depth,
  1966. int out_depth)
  1967. {
  1968. if (out_depth == 16 && in_depth != 16 &&
  1969. pm->calculations_use_input_precision)
  1970. return 257;
  1971. else
  1972. return 1;
  1973. }
  1974. #endif /* PNG_READ_GAMMA_SUPPORTED */
  1975. /* One modification structure must be provided for each chunk to be modified (in
  1976. * fact more than one can be provided if multiple separate changes are desired
  1977. * for a single chunk.) Modifications include adding a new chunk when a
  1978. * suitable chunk does not exist.
  1979. *
  1980. * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
  1981. * or 'added' as appropriate if the modify_fn returns 1 (true). If the
  1982. * modify_fn is NULL the chunk is simply removed.
  1983. */
  1984. typedef struct png_modification
  1985. {
  1986. struct png_modification *next;
  1987. png_uint_32 chunk;
  1988. /* If the following is NULL all matching chunks will be removed: */
  1989. int (*modify_fn)(struct png_modifier *pm,
  1990. struct png_modification *me, int add);
  1991. /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
  1992. * found and modified (and there is a modify_fn) the modify_fn will be called
  1993. * to add the chunk before the relevant chunk.
  1994. */
  1995. png_uint_32 add;
  1996. unsigned int modified :1; /* Chunk was modified */
  1997. unsigned int added :1; /* Chunk was added */
  1998. unsigned int removed :1; /* Chunk was removed */
  1999. } png_modification;
  2000. static void
  2001. modification_reset(png_modification *pmm)
  2002. {
  2003. if (pmm != NULL)
  2004. {
  2005. pmm->modified = 0;
  2006. pmm->added = 0;
  2007. pmm->removed = 0;
  2008. modification_reset(pmm->next);
  2009. }
  2010. }
  2011. static void
  2012. modification_init(png_modification *pmm)
  2013. {
  2014. memset(pmm, 0, sizeof *pmm);
  2015. pmm->next = NULL;
  2016. pmm->chunk = 0;
  2017. pmm->modify_fn = NULL;
  2018. pmm->add = 0;
  2019. modification_reset(pmm);
  2020. }
  2021. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  2022. static void
  2023. modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
  2024. {
  2025. if (pm->current_encoding != 0)
  2026. *ce = *pm->current_encoding;
  2027. else
  2028. memset(ce, 0, sizeof *ce);
  2029. ce->gamma = pm->current_gamma;
  2030. }
  2031. #endif
  2032. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  2033. static size_t
  2034. safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
  2035. const png_modifier *pm)
  2036. {
  2037. pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
  2038. pm->current_gamma);
  2039. if (pm->encoding_ignored)
  2040. pos = safecat(buffer, bufsize, pos, "[overridden]");
  2041. return pos;
  2042. }
  2043. #endif
  2044. /* Iterate through the usefully testable color encodings. An encoding is one
  2045. * of:
  2046. *
  2047. * 1) Nothing (no color space, no gamma).
  2048. * 2) Just a gamma value from the gamma array (including 1.0)
  2049. * 3) A color space from the encodings array with the corresponding gamma.
  2050. * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
  2051. *
  2052. * The iterator selects these in turn, the randomizer selects one at random,
  2053. * which is used depends on the setting of the 'test_exhaustive' flag. Notice
  2054. * that this function changes the colour space encoding so it must only be
  2055. * called on completion of the previous test. This is what 'modifier_reset'
  2056. * does, below.
  2057. *
  2058. * After the function has been called the 'repeat' flag will still be set; the
  2059. * caller of modifier_reset must reset it at the start of each run of the test!
  2060. */
  2061. static unsigned int
  2062. modifier_total_encodings(const png_modifier *pm)
  2063. {
  2064. return 1 + /* (1) nothing */
  2065. pm->ngammas + /* (2) gamma values to test */
  2066. pm->nencodings + /* (3) total number of encodings */
  2067. /* The following test only works after the first time through the
  2068. * png_modifier code because 'bit_depth' is set when the IHDR is read.
  2069. * modifier_reset, below, preserves the setting until after it has called
  2070. * the iterate function (also below.)
  2071. *
  2072. * For this reason do not rely on this function outside a call to
  2073. * modifier_reset.
  2074. */
  2075. ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
  2076. pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
  2077. }
  2078. static void
  2079. modifier_encoding_iterate(png_modifier *pm)
  2080. {
  2081. if (!pm->repeat && /* Else something needs the current encoding again. */
  2082. pm->test_uses_encoding) /* Some transform is encoding dependent */
  2083. {
  2084. if (pm->test_exhaustive)
  2085. {
  2086. if (++pm->encoding_counter >= modifier_total_encodings(pm))
  2087. pm->encoding_counter = 0; /* This will stop the repeat */
  2088. }
  2089. else
  2090. {
  2091. /* Not exhaustive - choose an encoding at random; generate a number in
  2092. * the range 1..(max-1), so the result is always non-zero:
  2093. */
  2094. if (pm->encoding_counter == 0)
  2095. pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
  2096. else
  2097. pm->encoding_counter = 0;
  2098. }
  2099. if (pm->encoding_counter > 0)
  2100. pm->repeat = 1;
  2101. }
  2102. else if (!pm->repeat)
  2103. pm->encoding_counter = 0;
  2104. }
  2105. static void
  2106. modifier_reset(png_modifier *pm)
  2107. {
  2108. store_read_reset(&pm->this);
  2109. pm->limit = 4E-3;
  2110. pm->pending_len = pm->pending_chunk = 0;
  2111. pm->flush = pm->buffer_count = pm->buffer_position = 0;
  2112. pm->modifications = NULL;
  2113. pm->state = modifier_start;
  2114. modifier_encoding_iterate(pm);
  2115. /* The following must be set in the next run. In particular
  2116. * test_uses_encodings must be set in the _ini function of each transform
  2117. * that looks at the encodings. (Not the 'add' function!)
  2118. */
  2119. pm->test_uses_encoding = 0;
  2120. pm->current_gamma = 0;
  2121. pm->current_encoding = 0;
  2122. pm->encoding_ignored = 0;
  2123. /* These only become value after IHDR is read: */
  2124. pm->bit_depth = pm->colour_type = 0;
  2125. }
  2126. /* The following must be called before anything else to get the encoding set up
  2127. * on the modifier. In particular it must be called before the transform init
  2128. * functions are called.
  2129. */
  2130. static void
  2131. modifier_set_encoding(png_modifier *pm)
  2132. {
  2133. /* Set the encoding to the one specified by the current encoding counter,
  2134. * first clear out all the settings - this corresponds to an encoding_counter
  2135. * of 0.
  2136. */
  2137. pm->current_gamma = 0;
  2138. pm->current_encoding = 0;
  2139. pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
  2140. /* Now, if required, set the gamma and encoding fields. */
  2141. if (pm->encoding_counter > 0)
  2142. {
  2143. /* The gammas[] array is an array of screen gammas, not encoding gammas,
  2144. * so we need the inverse:
  2145. */
  2146. if (pm->encoding_counter <= pm->ngammas)
  2147. pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
  2148. else
  2149. {
  2150. unsigned int i = pm->encoding_counter - pm->ngammas;
  2151. if (i >= pm->nencodings)
  2152. {
  2153. i %= pm->nencodings;
  2154. pm->current_gamma = 1; /* Linear, only in the 16 bit case */
  2155. }
  2156. else
  2157. pm->current_gamma = pm->encodings[i].gamma;
  2158. pm->current_encoding = pm->encodings + i;
  2159. }
  2160. }
  2161. }
  2162. /* Enquiry functions to find out what is set. Notice that there is an implicit
  2163. * assumption below that the first encoding in the list is the one for sRGB.
  2164. */
  2165. static int
  2166. modifier_color_encoding_is_sRGB(const png_modifier *pm)
  2167. {
  2168. return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
  2169. pm->current_encoding->gamma == pm->current_gamma;
  2170. }
  2171. static int
  2172. modifier_color_encoding_is_set(const png_modifier *pm)
  2173. {
  2174. return pm->current_gamma != 0;
  2175. }
  2176. /* Convenience macros. */
  2177. #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
  2178. #define CHUNK_IHDR CHUNK(73,72,68,82)
  2179. #define CHUNK_PLTE CHUNK(80,76,84,69)
  2180. #define CHUNK_IDAT CHUNK(73,68,65,84)
  2181. #define CHUNK_IEND CHUNK(73,69,78,68)
  2182. #define CHUNK_cHRM CHUNK(99,72,82,77)
  2183. #define CHUNK_gAMA CHUNK(103,65,77,65)
  2184. #define CHUNK_sBIT CHUNK(115,66,73,84)
  2185. #define CHUNK_sRGB CHUNK(115,82,71,66)
  2186. /* The guts of modification are performed during a read. */
  2187. static void
  2188. modifier_crc(png_bytep buffer)
  2189. {
  2190. /* Recalculate the chunk CRC - a complete chunk must be in
  2191. * the buffer, at the start.
  2192. */
  2193. uInt datalen = png_get_uint_32(buffer);
  2194. uLong crc = crc32(0, buffer+4, datalen+4);
  2195. /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
  2196. */
  2197. png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
  2198. }
  2199. static void
  2200. modifier_setbuffer(png_modifier *pm)
  2201. {
  2202. modifier_crc(pm->buffer);
  2203. pm->buffer_count = png_get_uint_32(pm->buffer)+12;
  2204. pm->buffer_position = 0;
  2205. }
  2206. /* Separate the callback into the actual implementation (which is passed the
  2207. * png_modifier explicitly) and the callback, which gets the modifier from the
  2208. * png_struct.
  2209. */
  2210. static void
  2211. modifier_read_imp(png_modifier *pm, png_bytep pb, png_size_t st)
  2212. {
  2213. while (st > 0)
  2214. {
  2215. size_t cb;
  2216. png_uint_32 len, chunk;
  2217. png_modification *mod;
  2218. if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
  2219. {
  2220. static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
  2221. case modifier_start:
  2222. store_read_imp(&pm->this, pm->buffer, 8); /* size of signature. */
  2223. pm->buffer_count = 8;
  2224. pm->buffer_position = 0;
  2225. if (memcmp(pm->buffer, sign, 8) != 0)
  2226. png_error(pm->this.pread, "invalid PNG file signature");
  2227. pm->state = modifier_signature;
  2228. break;
  2229. case modifier_signature:
  2230. store_read_imp(&pm->this, pm->buffer, 13+12); /* size of IHDR */
  2231. pm->buffer_count = 13+12;
  2232. pm->buffer_position = 0;
  2233. if (png_get_uint_32(pm->buffer) != 13 ||
  2234. png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
  2235. png_error(pm->this.pread, "invalid IHDR");
  2236. /* Check the list of modifiers for modifications to the IHDR. */
  2237. mod = pm->modifications;
  2238. while (mod != NULL)
  2239. {
  2240. if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
  2241. (*mod->modify_fn)(pm, mod, 0))
  2242. {
  2243. mod->modified = 1;
  2244. modifier_setbuffer(pm);
  2245. }
  2246. /* Ignore removal or add if IHDR! */
  2247. mod = mod->next;
  2248. }
  2249. /* Cache information from the IHDR (the modified one.) */
  2250. pm->bit_depth = pm->buffer[8+8];
  2251. pm->colour_type = pm->buffer[8+8+1];
  2252. pm->state = modifier_IHDR;
  2253. pm->flush = 0;
  2254. break;
  2255. case modifier_IHDR:
  2256. default:
  2257. /* Read a new chunk and process it until we see PLTE, IDAT or
  2258. * IEND. 'flush' indicates that there is still some data to
  2259. * output from the preceding chunk.
  2260. */
  2261. if ((cb = pm->flush) > 0)
  2262. {
  2263. if (cb > st) cb = st;
  2264. pm->flush -= cb;
  2265. store_read_imp(&pm->this, pb, cb);
  2266. pb += cb;
  2267. st -= cb;
  2268. if (st == 0) return;
  2269. }
  2270. /* No more bytes to flush, read a header, or handle a pending
  2271. * chunk.
  2272. */
  2273. if (pm->pending_chunk != 0)
  2274. {
  2275. png_save_uint_32(pm->buffer, pm->pending_len);
  2276. png_save_uint_32(pm->buffer+4, pm->pending_chunk);
  2277. pm->pending_len = 0;
  2278. pm->pending_chunk = 0;
  2279. }
  2280. else
  2281. store_read_imp(&pm->this, pm->buffer, 8);
  2282. pm->buffer_count = 8;
  2283. pm->buffer_position = 0;
  2284. /* Check for something to modify or a terminator chunk. */
  2285. len = png_get_uint_32(pm->buffer);
  2286. chunk = png_get_uint_32(pm->buffer+4);
  2287. /* Terminators first, they may have to be delayed for added
  2288. * chunks
  2289. */
  2290. if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
  2291. chunk == CHUNK_IEND)
  2292. {
  2293. mod = pm->modifications;
  2294. while (mod != NULL)
  2295. {
  2296. if ((mod->add == chunk ||
  2297. (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
  2298. mod->modify_fn != NULL && !mod->modified && !mod->added)
  2299. {
  2300. /* Regardless of what the modify function does do not run
  2301. * this again.
  2302. */
  2303. mod->added = 1;
  2304. if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
  2305. {
  2306. /* Reset the CRC on a new chunk */
  2307. if (pm->buffer_count > 0)
  2308. modifier_setbuffer(pm);
  2309. else
  2310. {
  2311. pm->buffer_position = 0;
  2312. mod->removed = 1;
  2313. }
  2314. /* The buffer has been filled with something (we assume)
  2315. * so output this. Pend the current chunk.
  2316. */
  2317. pm->pending_len = len;
  2318. pm->pending_chunk = chunk;
  2319. break; /* out of while */
  2320. }
  2321. }
  2322. mod = mod->next;
  2323. }
  2324. /* Don't do any further processing if the buffer was modified -
  2325. * otherwise the code will end up modifying a chunk that was
  2326. * just added.
  2327. */
  2328. if (mod != NULL)
  2329. break; /* out of switch */
  2330. }
  2331. /* If we get to here then this chunk may need to be modified. To
  2332. * do this it must be less than 1024 bytes in total size, otherwise
  2333. * it just gets flushed.
  2334. */
  2335. if (len+12 <= sizeof pm->buffer)
  2336. {
  2337. store_read_imp(&pm->this, pm->buffer+pm->buffer_count,
  2338. len+12-pm->buffer_count);
  2339. pm->buffer_count = len+12;
  2340. /* Check for a modification, else leave it be. */
  2341. mod = pm->modifications;
  2342. while (mod != NULL)
  2343. {
  2344. if (mod->chunk == chunk)
  2345. {
  2346. if (mod->modify_fn == NULL)
  2347. {
  2348. /* Remove this chunk */
  2349. pm->buffer_count = pm->buffer_position = 0;
  2350. mod->removed = 1;
  2351. break; /* Terminate the while loop */
  2352. }
  2353. else if ((*mod->modify_fn)(pm, mod, 0))
  2354. {
  2355. mod->modified = 1;
  2356. /* The chunk may have been removed: */
  2357. if (pm->buffer_count == 0)
  2358. {
  2359. pm->buffer_position = 0;
  2360. break;
  2361. }
  2362. modifier_setbuffer(pm);
  2363. }
  2364. }
  2365. mod = mod->next;
  2366. }
  2367. }
  2368. else
  2369. pm->flush = len+12 - pm->buffer_count; /* data + crc */
  2370. /* Take the data from the buffer (if there is any). */
  2371. break;
  2372. }
  2373. /* Here to read from the modifier buffer (not directly from
  2374. * the store, as in the flush case above.)
  2375. */
  2376. cb = pm->buffer_count - pm->buffer_position;
  2377. if (cb > st)
  2378. cb = st;
  2379. memcpy(pb, pm->buffer + pm->buffer_position, cb);
  2380. st -= cb;
  2381. pb += cb;
  2382. pm->buffer_position += cb;
  2383. }
  2384. }
  2385. /* The callback: */
  2386. static void PNGCBAPI
  2387. modifier_read(png_structp ppIn, png_bytep pb, png_size_t st)
  2388. {
  2389. png_const_structp pp = ppIn;
  2390. png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
  2391. if (pm == NULL || pm->this.pread != pp)
  2392. png_error(pp, "bad modifier_read call");
  2393. modifier_read_imp(pm, pb, st);
  2394. }
  2395. /* Like store_progressive_read but the data is getting changed as we go so we
  2396. * need a local buffer.
  2397. */
  2398. static void
  2399. modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
  2400. {
  2401. if (pm->this.pread != pp || pm->this.current == NULL ||
  2402. pm->this.next == NULL)
  2403. png_error(pp, "store state damaged (progressive)");
  2404. /* This is another Horowitz and Hill random noise generator. In this case
  2405. * the aim is to stress the progressive reader with truly horrible variable
  2406. * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
  2407. * is generated. We could probably just count from 1 to 32767 and get as
  2408. * good a result.
  2409. */
  2410. for (;;)
  2411. {
  2412. static png_uint_32 noise = 1;
  2413. png_size_t cb, cbAvail;
  2414. png_byte buffer[512];
  2415. /* Generate 15 more bits of stuff: */
  2416. noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
  2417. cb = noise & 0x1ff;
  2418. /* Check that this number of bytes are available (in the current buffer.)
  2419. * (This doesn't quite work - the modifier might delete a chunk; unlikely
  2420. * but possible, it doesn't happen at present because the modifier only
  2421. * adds chunks to standard images.)
  2422. */
  2423. cbAvail = store_read_buffer_avail(&pm->this);
  2424. if (pm->buffer_count > pm->buffer_position)
  2425. cbAvail += pm->buffer_count - pm->buffer_position;
  2426. if (cb > cbAvail)
  2427. {
  2428. /* Check for EOF: */
  2429. if (cbAvail == 0)
  2430. break;
  2431. cb = cbAvail;
  2432. }
  2433. modifier_read_imp(pm, buffer, cb);
  2434. png_process_data(pp, pi, buffer, cb);
  2435. }
  2436. /* Check the invariants at the end (if this fails it's a problem in this
  2437. * file!)
  2438. */
  2439. if (pm->buffer_count > pm->buffer_position ||
  2440. pm->this.next != &pm->this.current->data ||
  2441. pm->this.readpos < pm->this.current->datacount)
  2442. png_error(pp, "progressive read implementation error");
  2443. }
  2444. /* Set up a modifier. */
  2445. static png_structp
  2446. set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
  2447. const char *name)
  2448. {
  2449. /* Do this first so that the modifier fields are cleared even if an error
  2450. * happens allocating the png_struct. No allocation is done here so no
  2451. * cleanup is required.
  2452. */
  2453. pm->state = modifier_start;
  2454. pm->bit_depth = 0;
  2455. pm->colour_type = 255;
  2456. pm->pending_len = 0;
  2457. pm->pending_chunk = 0;
  2458. pm->flush = 0;
  2459. pm->buffer_count = 0;
  2460. pm->buffer_position = 0;
  2461. return set_store_for_read(&pm->this, ppi, id, name);
  2462. }
  2463. /******************************** MODIFICATIONS *******************************/
  2464. /* Standard modifications to add chunks. These do not require the _SUPPORTED
  2465. * macros because the chunks can be there regardless of whether this specific
  2466. * libpng supports them.
  2467. */
  2468. typedef struct gama_modification
  2469. {
  2470. png_modification this;
  2471. png_fixed_point gamma;
  2472. } gama_modification;
  2473. static int
  2474. gama_modify(png_modifier *pm, png_modification *me, int add)
  2475. {
  2476. UNUSED(add)
  2477. /* This simply dumps the given gamma value into the buffer. */
  2478. png_save_uint_32(pm->buffer, 4);
  2479. png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
  2480. png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
  2481. return 1;
  2482. }
  2483. static void
  2484. gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
  2485. {
  2486. double g;
  2487. modification_init(&me->this);
  2488. me->this.chunk = CHUNK_gAMA;
  2489. me->this.modify_fn = gama_modify;
  2490. me->this.add = CHUNK_PLTE;
  2491. g = fix(gammad);
  2492. me->gamma = (png_fixed_point)g;
  2493. me->this.next = pm->modifications;
  2494. pm->modifications = &me->this;
  2495. }
  2496. typedef struct chrm_modification
  2497. {
  2498. png_modification this;
  2499. const color_encoding *encoding;
  2500. png_fixed_point wx, wy, rx, ry, gx, gy, bx, by;
  2501. } chrm_modification;
  2502. static int
  2503. chrm_modify(png_modifier *pm, png_modification *me, int add)
  2504. {
  2505. UNUSED(add)
  2506. /* As with gAMA this just adds the required cHRM chunk to the buffer. */
  2507. png_save_uint_32(pm->buffer , 32);
  2508. png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
  2509. png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
  2510. png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
  2511. png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
  2512. png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
  2513. png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
  2514. png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
  2515. png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
  2516. png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
  2517. return 1;
  2518. }
  2519. static void
  2520. chrm_modification_init(chrm_modification *me, png_modifier *pm,
  2521. const color_encoding *encoding)
  2522. {
  2523. CIE_color white = white_point(encoding);
  2524. /* Original end points: */
  2525. me->encoding = encoding;
  2526. /* Chromaticities (in fixed point): */
  2527. me->wx = fix(chromaticity_x(white));
  2528. me->wy = fix(chromaticity_y(white));
  2529. me->rx = fix(chromaticity_x(encoding->red));
  2530. me->ry = fix(chromaticity_y(encoding->red));
  2531. me->gx = fix(chromaticity_x(encoding->green));
  2532. me->gy = fix(chromaticity_y(encoding->green));
  2533. me->bx = fix(chromaticity_x(encoding->blue));
  2534. me->by = fix(chromaticity_y(encoding->blue));
  2535. modification_init(&me->this);
  2536. me->this.chunk = CHUNK_cHRM;
  2537. me->this.modify_fn = chrm_modify;
  2538. me->this.add = CHUNK_PLTE;
  2539. me->this.next = pm->modifications;
  2540. pm->modifications = &me->this;
  2541. }
  2542. typedef struct srgb_modification
  2543. {
  2544. png_modification this;
  2545. png_byte intent;
  2546. } srgb_modification;
  2547. static int
  2548. srgb_modify(png_modifier *pm, png_modification *me, int add)
  2549. {
  2550. UNUSED(add)
  2551. /* As above, ignore add and just make a new chunk */
  2552. png_save_uint_32(pm->buffer, 1);
  2553. png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
  2554. pm->buffer[8] = ((srgb_modification*)me)->intent;
  2555. return 1;
  2556. }
  2557. static void
  2558. srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
  2559. {
  2560. modification_init(&me->this);
  2561. me->this.chunk = CHUNK_sBIT;
  2562. if (intent <= 3) /* if valid, else *delete* sRGB chunks */
  2563. {
  2564. me->this.modify_fn = srgb_modify;
  2565. me->this.add = CHUNK_PLTE;
  2566. me->intent = intent;
  2567. }
  2568. else
  2569. {
  2570. me->this.modify_fn = 0;
  2571. me->this.add = 0;
  2572. me->intent = 0;
  2573. }
  2574. me->this.next = pm->modifications;
  2575. pm->modifications = &me->this;
  2576. }
  2577. #ifdef PNG_READ_GAMMA_SUPPORTED
  2578. typedef struct sbit_modification
  2579. {
  2580. png_modification this;
  2581. png_byte sbit;
  2582. } sbit_modification;
  2583. static int
  2584. sbit_modify(png_modifier *pm, png_modification *me, int add)
  2585. {
  2586. png_byte sbit = ((sbit_modification*)me)->sbit;
  2587. if (pm->bit_depth > sbit)
  2588. {
  2589. int cb = 0;
  2590. switch (pm->colour_type)
  2591. {
  2592. case 0:
  2593. cb = 1;
  2594. break;
  2595. case 2:
  2596. case 3:
  2597. cb = 3;
  2598. break;
  2599. case 4:
  2600. cb = 2;
  2601. break;
  2602. case 6:
  2603. cb = 4;
  2604. break;
  2605. default:
  2606. png_error(pm->this.pread,
  2607. "unexpected colour type in sBIT modification");
  2608. }
  2609. png_save_uint_32(pm->buffer, cb);
  2610. png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
  2611. while (cb > 0)
  2612. (pm->buffer+8)[--cb] = sbit;
  2613. return 1;
  2614. }
  2615. else if (!add)
  2616. {
  2617. /* Remove the sBIT chunk */
  2618. pm->buffer_count = pm->buffer_position = 0;
  2619. return 1;
  2620. }
  2621. else
  2622. return 0; /* do nothing */
  2623. }
  2624. static void
  2625. sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
  2626. {
  2627. modification_init(&me->this);
  2628. me->this.chunk = CHUNK_sBIT;
  2629. me->this.modify_fn = sbit_modify;
  2630. me->this.add = CHUNK_PLTE;
  2631. me->sbit = sbit;
  2632. me->this.next = pm->modifications;
  2633. pm->modifications = &me->this;
  2634. }
  2635. #endif /* PNG_READ_GAMMA_SUPPORTED */
  2636. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  2637. /***************************** STANDARD PNG FILES *****************************/
  2638. /* Standard files - write and save standard files. */
  2639. /* There are two basic forms of standard images. Those which attempt to have
  2640. * all the possible pixel values (not possible for 16bpp images, but a range of
  2641. * values are produced) and those which have a range of image sizes. The former
  2642. * are used for testing transforms, in particular gamma correction and bit
  2643. * reduction and increase. The latter are reserved for testing the behavior of
  2644. * libpng with respect to 'odd' image sizes - particularly small images where
  2645. * rows become 1 byte and interlace passes disappear.
  2646. *
  2647. * The first, most useful, set are the 'transform' images, the second set of
  2648. * small images are the 'size' images.
  2649. *
  2650. * The transform files are constructed with rows which fit into a 1024 byte row
  2651. * buffer. This makes allocation easier below. Further regardless of the file
  2652. * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
  2653. *
  2654. * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
  2655. * and with an ID derived from the colour type, bit depth and interlace type
  2656. * as above (FILEID). The width (128) and height (variable) are not stored in
  2657. * the FILEID - instead the fields are set to 0, indicating a transform file.
  2658. *
  2659. * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
  2660. * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum
  2661. * height of 16 rows. The width and height are stored in the FILEID and, being
  2662. * non-zero, indicate a size file.
  2663. *
  2664. * Because the PNG filter code is typically the largest CPU consumer within
  2665. * libpng itself there is a tendency to attempt to optimize it. This results in
  2666. * special case code which needs to be validated. To cause this to happen the
  2667. * 'size' images are made to use each possible filter, in so far as this is
  2668. * possible for smaller images.
  2669. *
  2670. * For palette image (colour type 3) multiple transform images are stored with
  2671. * the same bit depth to allow testing of more colour combinations -
  2672. * particularly important for testing the gamma code because libpng uses a
  2673. * different code path for palette images. For size images a single palette is
  2674. * used.
  2675. */
  2676. /* Make a 'standard' palette. Because there are only 256 entries in a palette
  2677. * (maximum) this actually makes a random palette in the hope that enough tests
  2678. * will catch enough errors. (Note that the same palette isn't produced every
  2679. * time for the same test - it depends on what previous tests have been run -
  2680. * but a given set of arguments to pngvalid will always produce the same palette
  2681. * at the same test! This is why pseudo-random number generators are useful for
  2682. * testing.)
  2683. *
  2684. * The store must be open for write when this is called, otherwise an internal
  2685. * error will occur. This routine contains its own magic number seed, so the
  2686. * palettes generated don't change if there are intervening errors (changing the
  2687. * calls to the store_mark seed.)
  2688. */
  2689. static store_palette_entry *
  2690. make_standard_palette(png_store* ps, int npalette, int do_tRNS)
  2691. {
  2692. static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
  2693. int i = 0;
  2694. png_byte values[256][4];
  2695. /* Always put in black and white plus the six primary and secondary colors.
  2696. */
  2697. for (; i<8; ++i)
  2698. {
  2699. values[i][1] = (png_byte)((i&1) ? 255U : 0U);
  2700. values[i][2] = (png_byte)((i&2) ? 255U : 0U);
  2701. values[i][3] = (png_byte)((i&4) ? 255U : 0U);
  2702. }
  2703. /* Then add 62 grays (one quarter of the remaining 256 slots). */
  2704. {
  2705. int j = 0;
  2706. png_byte random_bytes[4];
  2707. png_byte need[256];
  2708. need[0] = 0; /*got black*/
  2709. memset(need+1, 1, (sizeof need)-2); /*need these*/
  2710. need[255] = 0; /*but not white*/
  2711. while (i<70)
  2712. {
  2713. png_byte b;
  2714. if (j==0)
  2715. {
  2716. make_four_random_bytes(palette_seed, random_bytes);
  2717. j = 4;
  2718. }
  2719. b = random_bytes[--j];
  2720. if (need[b])
  2721. {
  2722. values[i][1] = b;
  2723. values[i][2] = b;
  2724. values[i++][3] = b;
  2725. }
  2726. }
  2727. }
  2728. /* Finally add 192 colors at random - don't worry about matches to things we
  2729. * already have, chance is less than 1/65536. Don't worry about grays,
  2730. * chance is the same, so we get a duplicate or extra gray less than 1 time
  2731. * in 170.
  2732. */
  2733. for (; i<256; ++i)
  2734. make_four_random_bytes(palette_seed, values[i]);
  2735. /* Fill in the alpha values in the first byte. Just use all possible values
  2736. * (0..255) in an apparently random order:
  2737. */
  2738. {
  2739. store_palette_entry *palette;
  2740. png_byte selector[4];
  2741. make_four_random_bytes(palette_seed, selector);
  2742. if (do_tRNS)
  2743. for (i=0; i<256; ++i)
  2744. values[i][0] = (png_byte)(i ^ selector[0]);
  2745. else
  2746. for (i=0; i<256; ++i)
  2747. values[i][0] = 255; /* no transparency/tRNS chunk */
  2748. /* 'values' contains 256 ARGB values, but we only need 'npalette'.
  2749. * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low
  2750. * bit depth cases select colors at random, else it is difficult to have
  2751. * a set of low bit depth palette test with any chance of a reasonable
  2752. * range of colors. Do this by randomly permuting values into the low
  2753. * 'npalette' entries using an XOR mask generated here. This also
  2754. * permutes the npalette == 256 case in a potentially useful way (there is
  2755. * no relationship between palette index and the color value therein!)
  2756. */
  2757. palette = store_write_palette(ps, npalette);
  2758. for (i=0; i<npalette; ++i)
  2759. {
  2760. palette[i].alpha = values[i ^ selector[1]][0];
  2761. palette[i].red = values[i ^ selector[1]][1];
  2762. palette[i].green = values[i ^ selector[1]][2];
  2763. palette[i].blue = values[i ^ selector[1]][3];
  2764. }
  2765. return palette;
  2766. }
  2767. }
  2768. /* Initialize a standard palette on a write stream. The 'do_tRNS' argument
  2769. * indicates whether or not to also set the tRNS chunk.
  2770. */
  2771. /* TODO: the png_structp here can probably be 'const' in the future */
  2772. static void
  2773. init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
  2774. int do_tRNS)
  2775. {
  2776. store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
  2777. {
  2778. int i;
  2779. png_color palette[256];
  2780. /* Set all entries to detect overread errors. */
  2781. for (i=0; i<npalette; ++i)
  2782. {
  2783. palette[i].red = ppal[i].red;
  2784. palette[i].green = ppal[i].green;
  2785. palette[i].blue = ppal[i].blue;
  2786. }
  2787. /* Just in case fill in the rest with detectable values: */
  2788. for (; i<256; ++i)
  2789. palette[i].red = palette[i].green = palette[i].blue = 42;
  2790. png_set_PLTE(pp, pi, palette, npalette);
  2791. }
  2792. if (do_tRNS)
  2793. {
  2794. int i, j;
  2795. png_byte tRNS[256];
  2796. /* Set all the entries, but skip trailing opaque entries */
  2797. for (i=j=0; i<npalette; ++i)
  2798. if ((tRNS[i] = ppal[i].alpha) < 255)
  2799. j = i+1;
  2800. /* Fill in the remainder with a detectable value: */
  2801. for (; i<256; ++i)
  2802. tRNS[i] = 24;
  2803. # ifdef PNG_WRITE_tRNS_SUPPORTED
  2804. if (j > 0)
  2805. png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
  2806. # endif
  2807. }
  2808. }
  2809. #ifdef PNG_WRITE_tRNS_SUPPORTED
  2810. static void
  2811. set_random_tRNS(png_structp pp, png_infop pi, const png_byte colour_type,
  2812. const int bit_depth)
  2813. {
  2814. /* To make this useful the tRNS color needs to match at least one pixel.
  2815. * Random values are fine for gray, including the 16-bit case where we know
  2816. * that the test image contains all the gray values. For RGB we need more
  2817. * method as only 65536 different RGB values are generated.
  2818. */
  2819. png_color_16 tRNS;
  2820. const png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1);
  2821. RANDOMIZE(tRNS);
  2822. if (colour_type & 2/*RGB*/)
  2823. {
  2824. if (bit_depth == 8)
  2825. {
  2826. tRNS.blue = tRNS.red ^ tRNS.green;
  2827. tRNS.red &= mask;
  2828. tRNS.green &= mask;
  2829. tRNS.blue &= mask;
  2830. }
  2831. else /* bit_depth == 16 */
  2832. {
  2833. tRNS.green = (png_uint_16)(tRNS.red * 257);
  2834. tRNS.blue = (png_uint_16)(tRNS.green * 17);
  2835. }
  2836. }
  2837. else
  2838. tRNS.gray &= mask;
  2839. png_set_tRNS(pp, pi, NULL, 0, &tRNS);
  2840. }
  2841. #endif
  2842. /* The number of passes is related to the interlace type. There was no libpng
  2843. * API to determine this prior to 1.5, so we need an inquiry function:
  2844. */
  2845. static int
  2846. npasses_from_interlace_type(png_const_structp pp, int interlace_type)
  2847. {
  2848. switch (interlace_type)
  2849. {
  2850. default:
  2851. png_error(pp, "invalid interlace type");
  2852. case PNG_INTERLACE_NONE:
  2853. return 1;
  2854. case PNG_INTERLACE_ADAM7:
  2855. return PNG_INTERLACE_ADAM7_PASSES;
  2856. }
  2857. }
  2858. static unsigned int
  2859. bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  2860. {
  2861. switch (colour_type)
  2862. {
  2863. default: png_error(pp, "invalid color type");
  2864. case 0: return bit_depth;
  2865. case 2: return 3*bit_depth;
  2866. case 3: return bit_depth;
  2867. case 4: return 2*bit_depth;
  2868. case 6: return 4*bit_depth;
  2869. }
  2870. }
  2871. #define TRANSFORM_WIDTH 128U
  2872. #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
  2873. #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
  2874. #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
  2875. #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
  2876. static size_t
  2877. transform_rowsize(png_const_structp pp, png_byte colour_type,
  2878. png_byte bit_depth)
  2879. {
  2880. return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
  2881. }
  2882. /* transform_width(pp, colour_type, bit_depth) current returns the same number
  2883. * every time, so just use a macro:
  2884. */
  2885. #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
  2886. static png_uint_32
  2887. transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  2888. {
  2889. switch (bit_size(pp, colour_type, bit_depth))
  2890. {
  2891. case 1:
  2892. case 2:
  2893. case 4:
  2894. return 1; /* Total of 128 pixels */
  2895. case 8:
  2896. return 2; /* Total of 256 pixels/bytes */
  2897. case 16:
  2898. return 512; /* Total of 65536 pixels */
  2899. case 24:
  2900. case 32:
  2901. return 512; /* 65536 pixels */
  2902. case 48:
  2903. case 64:
  2904. return 2048;/* 4 x 65536 pixels. */
  2905. # define TRANSFORM_HEIGHTMAX 2048
  2906. default:
  2907. return 0; /* Error, will be caught later */
  2908. }
  2909. }
  2910. #ifdef PNG_READ_SUPPORTED
  2911. /* The following can only be defined here, now we have the definitions
  2912. * of the transform image sizes.
  2913. */
  2914. static png_uint_32
  2915. standard_width(png_const_structp pp, png_uint_32 id)
  2916. {
  2917. png_uint_32 width = WIDTH_FROM_ID(id);
  2918. UNUSED(pp)
  2919. if (width == 0)
  2920. width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  2921. return width;
  2922. }
  2923. static png_uint_32
  2924. standard_height(png_const_structp pp, png_uint_32 id)
  2925. {
  2926. png_uint_32 height = HEIGHT_FROM_ID(id);
  2927. if (height == 0)
  2928. height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  2929. return height;
  2930. }
  2931. static png_uint_32
  2932. standard_rowsize(png_const_structp pp, png_uint_32 id)
  2933. {
  2934. png_uint_32 width = standard_width(pp, id);
  2935. /* This won't overflow: */
  2936. width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  2937. return (width + 7) / 8;
  2938. }
  2939. #endif /* PNG_READ_SUPPORTED */
  2940. static void
  2941. transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
  2942. png_byte colour_type, png_byte bit_depth, png_uint_32 y)
  2943. {
  2944. png_uint_32 v = y << 7;
  2945. png_uint_32 i = 0;
  2946. switch (bit_size(pp, colour_type, bit_depth))
  2947. {
  2948. case 1:
  2949. while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
  2950. return;
  2951. case 2:
  2952. while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
  2953. return;
  2954. case 4:
  2955. while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
  2956. return;
  2957. case 8:
  2958. /* 256 bytes total, 128 bytes in each row set as follows: */
  2959. while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
  2960. return;
  2961. case 16:
  2962. /* Generate all 65536 pixel values in order, which includes the 8 bit
  2963. * GA case as well as the 16 bit G case.
  2964. */
  2965. while (i<128)
  2966. {
  2967. buffer[2*i] = (png_byte)((v>>8) & 0xff);
  2968. buffer[2*i+1] = (png_byte)(v & 0xff);
  2969. ++v;
  2970. ++i;
  2971. }
  2972. return;
  2973. case 24:
  2974. /* 65535 pixels, but rotate the values. */
  2975. while (i<128)
  2976. {
  2977. /* Three bytes per pixel, r, g, b, make b by r^g */
  2978. buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
  2979. buffer[3*i+1] = (png_byte)(v & 0xff);
  2980. buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
  2981. ++v;
  2982. ++i;
  2983. }
  2984. return;
  2985. case 32:
  2986. /* 65535 pixels, r, g, b, a; just replicate */
  2987. while (i<128)
  2988. {
  2989. buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
  2990. buffer[4*i+1] = (png_byte)(v & 0xff);
  2991. buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
  2992. buffer[4*i+3] = (png_byte)(v & 0xff);
  2993. ++v;
  2994. ++i;
  2995. }
  2996. return;
  2997. case 48:
  2998. /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
  2999. * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
  3000. */
  3001. while (i<128)
  3002. {
  3003. png_uint_32 t = v++;
  3004. buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
  3005. buffer[6*i+1] = (png_byte)(t & 0xff);
  3006. t *= 257;
  3007. buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
  3008. buffer[6*i+3] = (png_byte)(t & 0xff);
  3009. t *= 17;
  3010. buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
  3011. buffer[6*i+5] = (png_byte)(t & 0xff);
  3012. ++i;
  3013. }
  3014. return;
  3015. case 64:
  3016. /* As above in the 32 bit case. */
  3017. while (i<128)
  3018. {
  3019. png_uint_32 t = v++;
  3020. buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
  3021. buffer[8*i+1] = (png_byte)(t & 0xff);
  3022. buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
  3023. buffer[8*i+5] = (png_byte)(t & 0xff);
  3024. t *= 257;
  3025. buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
  3026. buffer[8*i+3] = (png_byte)(t & 0xff);
  3027. buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
  3028. buffer[8*i+7] = (png_byte)(t & 0xff);
  3029. ++i;
  3030. }
  3031. return;
  3032. default:
  3033. break;
  3034. }
  3035. png_error(pp, "internal error");
  3036. }
  3037. /* This is just to do the right cast - could be changed to a function to check
  3038. * 'bd' but there isn't much point.
  3039. */
  3040. #define DEPTH(bd) ((png_byte)(1U << (bd)))
  3041. /* This is just a helper for compiling on minimal systems with no write
  3042. * interlacing support. If there is no write interlacing we can't generate test
  3043. * cases with interlace:
  3044. */
  3045. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  3046. # define INTERLACE_LAST PNG_INTERLACE_LAST
  3047. # define check_interlace_type(type) ((void)(type))
  3048. # define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp)
  3049. # define do_own_interlace 0
  3050. #elif PNG_LIBPNG_VER < 10700
  3051. # define set_write_interlace_handling(pp,type) (1)
  3052. static void
  3053. check_interlace_type(int const interlace_type)
  3054. {
  3055. /* Prior to 1.7.0 libpng does not support the write of an interlaced image
  3056. * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
  3057. * code here does the pixel interlace itself, so:
  3058. */
  3059. if (interlace_type != PNG_INTERLACE_NONE)
  3060. {
  3061. /* This is an internal error - --interlace tests should be skipped, not
  3062. * attempted.
  3063. */
  3064. fprintf(stderr, "pngvalid: no interlace support\n");
  3065. exit(99);
  3066. }
  3067. }
  3068. # define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
  3069. # define do_own_interlace 0
  3070. #else /* libpng 1.7+ */
  3071. # define set_write_interlace_handling(pp,type)\
  3072. npasses_from_interlace_type(pp,type)
  3073. # define check_interlace_type(type) ((void)(type))
  3074. # define INTERLACE_LAST PNG_INTERLACE_LAST
  3075. # define do_own_interlace 1
  3076. #endif /* WRITE_INTERLACING tests */
  3077. #define CAN_WRITE_INTERLACE\
  3078. PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED
  3079. /* Do the same thing for read interlacing; this controls whether read tests do
  3080. * their own de-interlace or use libpng.
  3081. */
  3082. #ifdef PNG_READ_INTERLACING_SUPPORTED
  3083. # define do_read_interlace 0
  3084. #else /* no libpng read interlace support */
  3085. # define do_read_interlace 1
  3086. #endif
  3087. /* The following two routines use the PNG interlace support macros from
  3088. * png.h to interlace or deinterlace rows.
  3089. */
  3090. static void
  3091. interlace_row(png_bytep buffer, png_const_bytep imageRow,
  3092. unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
  3093. {
  3094. png_uint_32 xin, xout, xstep;
  3095. /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
  3096. * code is presented this way to make it easier to understand. In practice
  3097. * consult the code in the libpng source to see other ways of doing this.
  3098. *
  3099. * It is OK for buffer and imageRow to be identical, because 'xin' moves
  3100. * faster than 'xout' and we copy up.
  3101. */
  3102. xin = PNG_PASS_START_COL(pass);
  3103. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3104. for (xout=0; xin<w; xin+=xstep)
  3105. {
  3106. pixel_copy(buffer, xout, imageRow, xin, pixel_size, littleendian);
  3107. ++xout;
  3108. }
  3109. }
  3110. #ifdef PNG_READ_SUPPORTED
  3111. static void
  3112. deinterlace_row(png_bytep buffer, png_const_bytep row,
  3113. unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
  3114. {
  3115. /* The inverse of the above, 'row' is part of row 'y' of the output image,
  3116. * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
  3117. * the pixels of row into buffer and return the number written (to allow
  3118. * this to be checked).
  3119. */
  3120. png_uint_32 xin, xout, xstep;
  3121. xout = PNG_PASS_START_COL(pass);
  3122. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3123. for (xin=0; xout<w; xout+=xstep)
  3124. {
  3125. pixel_copy(buffer, xout, row, xin, pixel_size, littleendian);
  3126. ++xin;
  3127. }
  3128. }
  3129. #endif /* PNG_READ_SUPPORTED */
  3130. /* Make a standardized image given an image colour type, bit depth and
  3131. * interlace type. The standard images have a very restricted range of
  3132. * rows and heights and are used for testing transforms rather than image
  3133. * layout details. See make_size_images below for a way to make images
  3134. * that test odd sizes along with the libpng interlace handling.
  3135. */
  3136. static void
  3137. make_transform_image(png_store* const ps, png_byte const colour_type,
  3138. png_byte const bit_depth, unsigned int palette_number,
  3139. int interlace_type, png_const_charp name)
  3140. {
  3141. context(ps, fault);
  3142. check_interlace_type(interlace_type);
  3143. Try
  3144. {
  3145. png_infop pi;
  3146. png_structp pp = set_store_for_write(ps, &pi, name);
  3147. png_uint_32 h, w;
  3148. /* In the event of a problem return control to the Catch statement below
  3149. * to do the clean up - it is not possible to 'return' directly from a Try
  3150. * block.
  3151. */
  3152. if (pp == NULL)
  3153. Throw ps;
  3154. w = transform_width(pp, colour_type, bit_depth);
  3155. h = transform_height(pp, colour_type, bit_depth);
  3156. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3157. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3158. #ifdef PNG_TEXT_SUPPORTED
  3159. # if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
  3160. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
  3161. # else
  3162. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
  3163. # endif
  3164. {
  3165. static char key[] = "image name"; /* must be writeable */
  3166. size_t pos;
  3167. png_text text;
  3168. char copy[FILE_NAME_SIZE];
  3169. /* Use a compressed text string to test the correct interaction of text
  3170. * compression and IDAT compression.
  3171. */
  3172. text.compression = TEXT_COMPRESSION;
  3173. text.key = key;
  3174. /* Yuck: the text must be writable! */
  3175. pos = safecat(copy, sizeof copy, 0, ps->wname);
  3176. text.text = copy;
  3177. text.text_length = pos;
  3178. text.itxt_length = 0;
  3179. text.lang = 0;
  3180. text.lang_key = 0;
  3181. png_set_text(pp, pi, &text, 1);
  3182. }
  3183. #endif
  3184. if (colour_type == 3) /* palette */
  3185. init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
  3186. # ifdef PNG_WRITE_tRNS_SUPPORTED
  3187. else if (palette_number)
  3188. set_random_tRNS(pp, pi, colour_type, bit_depth);
  3189. # endif
  3190. png_write_info(pp, pi);
  3191. if (png_get_rowbytes(pp, pi) !=
  3192. transform_rowsize(pp, colour_type, bit_depth))
  3193. png_error(pp, "transform row size incorrect");
  3194. else
  3195. {
  3196. /* Somewhat confusingly this must be called *after* png_write_info
  3197. * because if it is called before, the information in *pp has not been
  3198. * updated to reflect the interlaced image.
  3199. */
  3200. int npasses = set_write_interlace_handling(pp, interlace_type);
  3201. int pass;
  3202. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  3203. png_error(pp, "write: png_set_interlace_handling failed");
  3204. for (pass=0; pass<npasses; ++pass)
  3205. {
  3206. png_uint_32 y;
  3207. /* do_own_interlace is a pre-defined boolean (a #define) which is
  3208. * set if we have to work out the interlaced rows here.
  3209. */
  3210. for (y=0; y<h; ++y)
  3211. {
  3212. png_byte buffer[TRANSFORM_ROWMAX];
  3213. transform_row(pp, buffer, colour_type, bit_depth, y);
  3214. # if do_own_interlace
  3215. /* If do_own_interlace *and* the image is interlaced we need a
  3216. * reduced interlace row; this may be reduced to empty.
  3217. */
  3218. if (interlace_type == PNG_INTERLACE_ADAM7)
  3219. {
  3220. /* The row must not be written if it doesn't exist, notice
  3221. * that there are two conditions here, either the row isn't
  3222. * ever in the pass or the row would be but isn't wide
  3223. * enough to contribute any pixels. In fact the wPass test
  3224. * can be used to skip the whole y loop in this case.
  3225. */
  3226. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  3227. PNG_PASS_COLS(w, pass) > 0)
  3228. interlace_row(buffer, buffer,
  3229. bit_size(pp, colour_type, bit_depth), w, pass,
  3230. 0/*data always bigendian*/);
  3231. else
  3232. continue;
  3233. }
  3234. # endif /* do_own_interlace */
  3235. png_write_row(pp, buffer);
  3236. }
  3237. }
  3238. }
  3239. #ifdef PNG_TEXT_SUPPORTED
  3240. {
  3241. static char key[] = "end marker";
  3242. static char comment[] = "end";
  3243. png_text text;
  3244. /* Use a compressed text string to test the correct interaction of text
  3245. * compression and IDAT compression.
  3246. */
  3247. text.compression = TEXT_COMPRESSION;
  3248. text.key = key;
  3249. text.text = comment;
  3250. text.text_length = (sizeof comment)-1;
  3251. text.itxt_length = 0;
  3252. text.lang = 0;
  3253. text.lang_key = 0;
  3254. png_set_text(pp, pi, &text, 1);
  3255. }
  3256. #endif
  3257. png_write_end(pp, pi);
  3258. /* And store this under the appropriate id, then clean up. */
  3259. store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
  3260. interlace_type, 0, 0, 0));
  3261. store_write_reset(ps);
  3262. }
  3263. Catch(fault)
  3264. {
  3265. /* Use the png_store returned by the exception. This may help the compiler
  3266. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3267. * and ps will always be the same value.
  3268. */
  3269. store_write_reset(fault);
  3270. }
  3271. }
  3272. static void
  3273. make_transform_images(png_modifier *pm)
  3274. {
  3275. png_byte colour_type = 0;
  3276. png_byte bit_depth = 0;
  3277. unsigned int palette_number = 0;
  3278. /* This is in case of errors. */
  3279. safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
  3280. /* Use next_format to enumerate all the combinations we test, including
  3281. * generating multiple low bit depth palette images. Non-A images (palette
  3282. * and direct) are created with and without tRNS chunks.
  3283. */
  3284. while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
  3285. {
  3286. int interlace_type;
  3287. for (interlace_type = PNG_INTERLACE_NONE;
  3288. interlace_type < INTERLACE_LAST; ++interlace_type)
  3289. {
  3290. char name[FILE_NAME_SIZE];
  3291. standard_name(name, sizeof name, 0, colour_type, bit_depth,
  3292. palette_number, interlace_type, 0, 0, do_own_interlace);
  3293. make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
  3294. interlace_type, name);
  3295. }
  3296. }
  3297. }
  3298. /* Build a single row for the 'size' test images; this fills in only the
  3299. * first bit_width bits of the sample row.
  3300. */
  3301. static void
  3302. size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
  3303. {
  3304. /* height is in the range 1 to 16, so: */
  3305. y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
  3306. /* the following ensures bits are set in small images: */
  3307. y ^= 0xA5;
  3308. while (bit_width >= 8)
  3309. *buffer++ = (png_byte)y++, bit_width -= 8;
  3310. /* There may be up to 7 remaining bits, these go in the most significant
  3311. * bits of the byte.
  3312. */
  3313. if (bit_width > 0)
  3314. {
  3315. png_uint_32 mask = (1U<<(8-bit_width))-1;
  3316. *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
  3317. }
  3318. }
  3319. static void
  3320. make_size_image(png_store* const ps, png_byte const colour_type,
  3321. png_byte const bit_depth, int const interlace_type,
  3322. png_uint_32 const w, png_uint_32 const h,
  3323. int const do_interlace)
  3324. {
  3325. context(ps, fault);
  3326. check_interlace_type(interlace_type);
  3327. Try
  3328. {
  3329. png_infop pi;
  3330. png_structp pp;
  3331. unsigned int pixel_size;
  3332. /* Make a name and get an appropriate id for the store: */
  3333. char name[FILE_NAME_SIZE];
  3334. const png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
  3335. interlace_type, w, h, do_interlace);
  3336. standard_name_from_id(name, sizeof name, 0, id);
  3337. pp = set_store_for_write(ps, &pi, name);
  3338. /* In the event of a problem return control to the Catch statement below
  3339. * to do the clean up - it is not possible to 'return' directly from a Try
  3340. * block.
  3341. */
  3342. if (pp == NULL)
  3343. Throw ps;
  3344. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3345. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3346. #ifdef PNG_TEXT_SUPPORTED
  3347. {
  3348. static char key[] = "image name"; /* must be writeable */
  3349. size_t pos;
  3350. png_text text;
  3351. char copy[FILE_NAME_SIZE];
  3352. /* Use a compressed text string to test the correct interaction of text
  3353. * compression and IDAT compression.
  3354. */
  3355. text.compression = TEXT_COMPRESSION;
  3356. text.key = key;
  3357. /* Yuck: the text must be writable! */
  3358. pos = safecat(copy, sizeof copy, 0, ps->wname);
  3359. text.text = copy;
  3360. text.text_length = pos;
  3361. text.itxt_length = 0;
  3362. text.lang = 0;
  3363. text.lang_key = 0;
  3364. png_set_text(pp, pi, &text, 1);
  3365. }
  3366. #endif
  3367. if (colour_type == 3) /* palette */
  3368. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  3369. png_write_info(pp, pi);
  3370. /* Calculate the bit size, divide by 8 to get the byte size - this won't
  3371. * overflow because we know the w values are all small enough even for
  3372. * a system where 'unsigned int' is only 16 bits.
  3373. */
  3374. pixel_size = bit_size(pp, colour_type, bit_depth);
  3375. if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
  3376. png_error(pp, "size row size incorrect");
  3377. else
  3378. {
  3379. int npasses = npasses_from_interlace_type(pp, interlace_type);
  3380. png_uint_32 y;
  3381. int pass;
  3382. # ifdef PNG_WRITE_FILTER_SUPPORTED
  3383. int nfilter = PNG_FILTER_VALUE_LAST;
  3384. # endif
  3385. png_byte image[16][SIZE_ROWMAX];
  3386. /* To help consistent error detection make the parts of this buffer
  3387. * that aren't set below all '1':
  3388. */
  3389. memset(image, 0xff, sizeof image);
  3390. if (!do_interlace &&
  3391. npasses != set_write_interlace_handling(pp, interlace_type))
  3392. png_error(pp, "write: png_set_interlace_handling failed");
  3393. /* Prepare the whole image first to avoid making it 7 times: */
  3394. for (y=0; y<h; ++y)
  3395. size_row(image[y], w * pixel_size, y);
  3396. for (pass=0; pass<npasses; ++pass)
  3397. {
  3398. /* The following two are for checking the macros: */
  3399. const png_uint_32 wPass = PNG_PASS_COLS(w, pass);
  3400. /* If do_interlace is set we don't call png_write_row for every
  3401. * row because some of them are empty. In fact, for a 1x1 image,
  3402. * most of them are empty!
  3403. */
  3404. for (y=0; y<h; ++y)
  3405. {
  3406. png_const_bytep row = image[y];
  3407. png_byte tempRow[SIZE_ROWMAX];
  3408. /* If do_interlace *and* the image is interlaced we
  3409. * need a reduced interlace row; this may be reduced
  3410. * to empty.
  3411. */
  3412. if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
  3413. {
  3414. /* The row must not be written if it doesn't exist, notice
  3415. * that there are two conditions here, either the row isn't
  3416. * ever in the pass or the row would be but isn't wide
  3417. * enough to contribute any pixels. In fact the wPass test
  3418. * can be used to skip the whole y loop in this case.
  3419. */
  3420. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
  3421. {
  3422. /* Set to all 1's for error detection (libpng tends to
  3423. * set unset things to 0).
  3424. */
  3425. memset(tempRow, 0xff, sizeof tempRow);
  3426. interlace_row(tempRow, row, pixel_size, w, pass,
  3427. 0/*data always bigendian*/);
  3428. row = tempRow;
  3429. }
  3430. else
  3431. continue;
  3432. }
  3433. # ifdef PNG_WRITE_FILTER_SUPPORTED
  3434. /* Only get to here if the row has some pixels in it, set the
  3435. * filters to 'all' for the very first row and thereafter to a
  3436. * single filter. It isn't well documented, but png_set_filter
  3437. * does accept a filter number (per the spec) as well as a bit
  3438. * mask.
  3439. *
  3440. * The apparent wackiness of decrementing nfilter rather than
  3441. * incrementing is so that Paeth gets used in all images bigger
  3442. * than 1 row - it's the tricky one.
  3443. */
  3444. png_set_filter(pp, 0/*method*/,
  3445. nfilter >= PNG_FILTER_VALUE_LAST ? PNG_ALL_FILTERS : nfilter);
  3446. if (nfilter-- == 0)
  3447. nfilter = PNG_FILTER_VALUE_LAST-1;
  3448. # endif
  3449. png_write_row(pp, row);
  3450. }
  3451. }
  3452. }
  3453. #ifdef PNG_TEXT_SUPPORTED
  3454. {
  3455. static char key[] = "end marker";
  3456. static char comment[] = "end";
  3457. png_text text;
  3458. /* Use a compressed text string to test the correct interaction of text
  3459. * compression and IDAT compression.
  3460. */
  3461. text.compression = TEXT_COMPRESSION;
  3462. text.key = key;
  3463. text.text = comment;
  3464. text.text_length = (sizeof comment)-1;
  3465. text.itxt_length = 0;
  3466. text.lang = 0;
  3467. text.lang_key = 0;
  3468. png_set_text(pp, pi, &text, 1);
  3469. }
  3470. #endif
  3471. png_write_end(pp, pi);
  3472. /* And store this under the appropriate id, then clean up. */
  3473. store_storefile(ps, id);
  3474. store_write_reset(ps);
  3475. }
  3476. Catch(fault)
  3477. {
  3478. /* Use the png_store returned by the exception. This may help the compiler
  3479. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3480. * and ps will always be the same value.
  3481. */
  3482. store_write_reset(fault);
  3483. }
  3484. }
  3485. static void
  3486. make_size(png_store* const ps, png_byte const colour_type, int bdlo,
  3487. int const bdhi)
  3488. {
  3489. for (; bdlo <= bdhi; ++bdlo)
  3490. {
  3491. png_uint_32 width;
  3492. for (width = 1; width <= 16; ++width)
  3493. {
  3494. png_uint_32 height;
  3495. for (height = 1; height <= 16; ++height)
  3496. {
  3497. /* The four combinations of DIY interlace and interlace or not -
  3498. * no interlace + DIY should be identical to no interlace with
  3499. * libpng doing it.
  3500. */
  3501. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3502. width, height, 0);
  3503. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3504. width, height, 1);
  3505. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  3506. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3507. width, height, 0);
  3508. # endif
  3509. # if CAN_WRITE_INTERLACE
  3510. /* 1.7.0 removes the hack that prevented app write of an interlaced
  3511. * image if WRITE_INTERLACE was not supported
  3512. */
  3513. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3514. width, height, 1);
  3515. # endif
  3516. }
  3517. }
  3518. }
  3519. }
  3520. static void
  3521. make_size_images(png_store *ps)
  3522. {
  3523. /* This is in case of errors. */
  3524. safecat(ps->test, sizeof ps->test, 0, "make size images");
  3525. /* Arguments are colour_type, low bit depth, high bit depth
  3526. */
  3527. make_size(ps, 0, 0, WRITE_BDHI);
  3528. make_size(ps, 2, 3, WRITE_BDHI);
  3529. make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
  3530. make_size(ps, 4, 3, WRITE_BDHI);
  3531. make_size(ps, 6, 3, WRITE_BDHI);
  3532. }
  3533. #ifdef PNG_READ_SUPPORTED
  3534. /* Return a row based on image id and 'y' for checking: */
  3535. static void
  3536. standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
  3537. png_uint_32 id, png_uint_32 y)
  3538. {
  3539. if (WIDTH_FROM_ID(id) == 0)
  3540. transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
  3541. else
  3542. size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
  3543. DEPTH_FROM_ID(id)), y);
  3544. }
  3545. #endif /* PNG_READ_SUPPORTED */
  3546. /* Tests - individual test cases */
  3547. /* Like 'make_standard' but errors are deliberately introduced into the calls
  3548. * to ensure that they get detected - it should not be possible to write an
  3549. * invalid image with libpng!
  3550. */
  3551. /* TODO: the 'set' functions can probably all be made to take a
  3552. * png_const_structp rather than a modifiable one.
  3553. */
  3554. #ifdef PNG_WARNINGS_SUPPORTED
  3555. static void
  3556. sBIT0_error_fn(png_structp pp, png_infop pi)
  3557. {
  3558. /* 0 is invalid... */
  3559. png_color_8 bad;
  3560. bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
  3561. png_set_sBIT(pp, pi, &bad);
  3562. }
  3563. static void
  3564. sBIT_error_fn(png_structp pp, png_infop pi)
  3565. {
  3566. png_byte bit_depth;
  3567. png_color_8 bad;
  3568. if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
  3569. bit_depth = 8;
  3570. else
  3571. bit_depth = png_get_bit_depth(pp, pi);
  3572. /* Now we know the bit depth we can easily generate an invalid sBIT entry */
  3573. bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
  3574. (png_byte)(bit_depth+1);
  3575. png_set_sBIT(pp, pi, &bad);
  3576. }
  3577. static const struct
  3578. {
  3579. void (*fn)(png_structp, png_infop);
  3580. const char *msg;
  3581. unsigned int warning :1; /* the error is a warning... */
  3582. } error_test[] =
  3583. {
  3584. /* no warnings makes these errors undetectable prior to 1.7.0 */
  3585. { sBIT0_error_fn, "sBIT(0): failed to detect error",
  3586. PNG_LIBPNG_VER < 10700 },
  3587. { sBIT_error_fn, "sBIT(too big): failed to detect error",
  3588. PNG_LIBPNG_VER < 10700 },
  3589. };
  3590. static void
  3591. make_error(png_store* const ps, png_byte const colour_type,
  3592. png_byte bit_depth, int interlace_type, int test, png_const_charp name)
  3593. {
  3594. context(ps, fault);
  3595. check_interlace_type(interlace_type);
  3596. Try
  3597. {
  3598. png_infop pi;
  3599. const png_structp pp = set_store_for_write(ps, &pi, name);
  3600. png_uint_32 w, h;
  3601. gnu_volatile(pp)
  3602. if (pp == NULL)
  3603. Throw ps;
  3604. w = transform_width(pp, colour_type, bit_depth);
  3605. gnu_volatile(w)
  3606. h = transform_height(pp, colour_type, bit_depth);
  3607. gnu_volatile(h)
  3608. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3609. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3610. if (colour_type == 3) /* palette */
  3611. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  3612. /* Time for a few errors; these are in various optional chunks, the
  3613. * standard tests test the standard chunks pretty well.
  3614. */
  3615. # define exception__prev exception_prev_1
  3616. # define exception__env exception_env_1
  3617. Try
  3618. {
  3619. gnu_volatile(exception__prev)
  3620. /* Expect this to throw: */
  3621. ps->expect_error = !error_test[test].warning;
  3622. ps->expect_warning = error_test[test].warning;
  3623. ps->saw_warning = 0;
  3624. error_test[test].fn(pp, pi);
  3625. /* Normally the error is only detected here: */
  3626. png_write_info(pp, pi);
  3627. /* And handle the case where it was only a warning: */
  3628. if (ps->expect_warning && ps->saw_warning)
  3629. Throw ps;
  3630. /* If we get here there is a problem, we have success - no error or
  3631. * no warning - when we shouldn't have success. Log an error.
  3632. */
  3633. store_log(ps, pp, error_test[test].msg, 1 /*error*/);
  3634. }
  3635. Catch (fault)
  3636. { /* expected exit */
  3637. }
  3638. #undef exception__prev
  3639. #undef exception__env
  3640. /* And clear these flags */
  3641. ps->expect_error = 0;
  3642. ps->expect_warning = 0;
  3643. /* Now write the whole image, just to make sure that the detected, or
  3644. * undetected, errro has not created problems inside libpng.
  3645. */
  3646. if (png_get_rowbytes(pp, pi) !=
  3647. transform_rowsize(pp, colour_type, bit_depth))
  3648. png_error(pp, "row size incorrect");
  3649. else
  3650. {
  3651. int npasses = set_write_interlace_handling(pp, interlace_type);
  3652. int pass;
  3653. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  3654. png_error(pp, "write: png_set_interlace_handling failed");
  3655. for (pass=0; pass<npasses; ++pass)
  3656. {
  3657. png_uint_32 y;
  3658. for (y=0; y<h; ++y)
  3659. {
  3660. png_byte buffer[TRANSFORM_ROWMAX];
  3661. transform_row(pp, buffer, colour_type, bit_depth, y);
  3662. # if do_own_interlace
  3663. /* If do_own_interlace *and* the image is interlaced we need a
  3664. * reduced interlace row; this may be reduced to empty.
  3665. */
  3666. if (interlace_type == PNG_INTERLACE_ADAM7)
  3667. {
  3668. /* The row must not be written if it doesn't exist, notice
  3669. * that there are two conditions here, either the row isn't
  3670. * ever in the pass or the row would be but isn't wide
  3671. * enough to contribute any pixels. In fact the wPass test
  3672. * can be used to skip the whole y loop in this case.
  3673. */
  3674. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  3675. PNG_PASS_COLS(w, pass) > 0)
  3676. interlace_row(buffer, buffer,
  3677. bit_size(pp, colour_type, bit_depth), w, pass,
  3678. 0/*data always bigendian*/);
  3679. else
  3680. continue;
  3681. }
  3682. # endif /* do_own_interlace */
  3683. png_write_row(pp, buffer);
  3684. }
  3685. }
  3686. }
  3687. png_write_end(pp, pi);
  3688. /* The following deletes the file that was just written. */
  3689. store_write_reset(ps);
  3690. }
  3691. Catch(fault)
  3692. {
  3693. store_write_reset(fault);
  3694. }
  3695. }
  3696. static int
  3697. make_errors(png_modifier* const pm, png_byte const colour_type,
  3698. int bdlo, int const bdhi)
  3699. {
  3700. for (; bdlo <= bdhi; ++bdlo)
  3701. {
  3702. int interlace_type;
  3703. for (interlace_type = PNG_INTERLACE_NONE;
  3704. interlace_type < INTERLACE_LAST; ++interlace_type)
  3705. {
  3706. unsigned int test;
  3707. char name[FILE_NAME_SIZE];
  3708. standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
  3709. interlace_type, 0, 0, do_own_interlace);
  3710. for (test=0; test<ARRAY_SIZE(error_test); ++test)
  3711. {
  3712. make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
  3713. test, name);
  3714. if (fail(pm))
  3715. return 0;
  3716. }
  3717. }
  3718. }
  3719. return 1; /* keep going */
  3720. }
  3721. #endif /* PNG_WARNINGS_SUPPORTED */
  3722. static void
  3723. perform_error_test(png_modifier *pm)
  3724. {
  3725. #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
  3726. /* Need to do this here because we just write in this test. */
  3727. safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
  3728. if (!make_errors(pm, 0, 0, WRITE_BDHI))
  3729. return;
  3730. if (!make_errors(pm, 2, 3, WRITE_BDHI))
  3731. return;
  3732. if (!make_errors(pm, 3, 0, 3))
  3733. return;
  3734. if (!make_errors(pm, 4, 3, WRITE_BDHI))
  3735. return;
  3736. if (!make_errors(pm, 6, 3, WRITE_BDHI))
  3737. return;
  3738. #else
  3739. UNUSED(pm)
  3740. #endif
  3741. }
  3742. /* This is just to validate the internal PNG formatting code - if this fails
  3743. * then the warning messages the library outputs will probably be garbage.
  3744. */
  3745. static void
  3746. perform_formatting_test(png_store *ps)
  3747. {
  3748. #ifdef PNG_TIME_RFC1123_SUPPORTED
  3749. /* The handle into the formatting code is the RFC1123 support; this test does
  3750. * nothing if that is compiled out.
  3751. */
  3752. context(ps, fault);
  3753. Try
  3754. {
  3755. png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
  3756. png_const_charp result;
  3757. # if PNG_LIBPNG_VER >= 10600
  3758. char timestring[29];
  3759. # endif
  3760. png_structp pp;
  3761. png_time pt;
  3762. pp = set_store_for_write(ps, NULL, "libpng formatting test");
  3763. if (pp == NULL)
  3764. Throw ps;
  3765. /* Arbitrary settings: */
  3766. pt.year = 2079;
  3767. pt.month = 8;
  3768. pt.day = 29;
  3769. pt.hour = 13;
  3770. pt.minute = 53;
  3771. pt.second = 60; /* a leap second */
  3772. # if PNG_LIBPNG_VER < 10600
  3773. result = png_convert_to_rfc1123(pp, &pt);
  3774. # else
  3775. if (png_convert_to_rfc1123_buffer(timestring, &pt))
  3776. result = timestring;
  3777. else
  3778. result = NULL;
  3779. # endif
  3780. if (result == NULL)
  3781. png_error(pp, "png_convert_to_rfc1123 failed");
  3782. if (strcmp(result, correct) != 0)
  3783. {
  3784. size_t pos = 0;
  3785. char msg[128];
  3786. pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
  3787. pos = safecat(msg, sizeof msg, pos, correct);
  3788. pos = safecat(msg, sizeof msg, pos, ") returned: '");
  3789. pos = safecat(msg, sizeof msg, pos, result);
  3790. pos = safecat(msg, sizeof msg, pos, "'");
  3791. png_error(pp, msg);
  3792. }
  3793. store_write_reset(ps);
  3794. }
  3795. Catch(fault)
  3796. {
  3797. store_write_reset(fault);
  3798. }
  3799. #else
  3800. UNUSED(ps)
  3801. #endif
  3802. }
  3803. #ifdef PNG_READ_SUPPORTED
  3804. /* Because we want to use the same code in both the progressive reader and the
  3805. * sequential reader it is necessary to deal with the fact that the progressive
  3806. * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
  3807. * must contain all the test parameters and all the local variables directly
  3808. * accessible to the sequential reader implementation.
  3809. *
  3810. * The technique adopted is to reinvent part of what Dijkstra termed a
  3811. * 'display'; an array of pointers to the stack frames of enclosing functions so
  3812. * that a nested function definition can access the local (C auto) variables of
  3813. * the functions that contain its definition. In fact C provides the first
  3814. * pointer (the local variables - the stack frame pointer) and the last (the
  3815. * global variables - the BCPL global vector typically implemented as global
  3816. * addresses), this code requires one more pointer to make the display - the
  3817. * local variables (and function call parameters) of the function that actually
  3818. * invokes either the progressive or sequential reader.
  3819. *
  3820. * Perhaps confusingly this technique is confounded with classes - the
  3821. * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
  3822. * A gamma_display is a standard_display, taking advantage of the ANSI-C
  3823. * requirement that the pointer to the first member of a structure must be the
  3824. * same as the pointer to the structure. This allows us to reuse standard_
  3825. * functions in the gamma test code; something that could not be done with
  3826. * nested functions!
  3827. */
  3828. typedef struct standard_display
  3829. {
  3830. png_store* ps; /* Test parameters (passed to the function) */
  3831. png_byte colour_type;
  3832. png_byte bit_depth;
  3833. png_byte red_sBIT; /* Input data sBIT values. */
  3834. png_byte green_sBIT;
  3835. png_byte blue_sBIT;
  3836. png_byte alpha_sBIT;
  3837. png_byte interlace_type;
  3838. png_byte filler; /* Output has a filler */
  3839. png_uint_32 id; /* Calculated file ID */
  3840. png_uint_32 w; /* Width of image */
  3841. png_uint_32 h; /* Height of image */
  3842. int npasses; /* Number of interlaced passes */
  3843. png_uint_32 pixel_size; /* Width of one pixel in bits */
  3844. png_uint_32 bit_width; /* Width of output row in bits */
  3845. size_t cbRow; /* Bytes in a row of the output image */
  3846. int do_interlace; /* Do interlacing internally */
  3847. int littleendian; /* App (row) data is little endian */
  3848. int is_transparent; /* Transparency information was present. */
  3849. int has_tRNS; /* color type GRAY or RGB with a tRNS chunk. */
  3850. int speed; /* Doing a speed test */
  3851. int use_update_info;/* Call update_info, not start_image */
  3852. struct
  3853. {
  3854. png_uint_16 red;
  3855. png_uint_16 green;
  3856. png_uint_16 blue;
  3857. } transparent; /* The transparent color, if set. */
  3858. int npalette; /* Number of entries in the palette. */
  3859. store_palette
  3860. palette;
  3861. } standard_display;
  3862. static void
  3863. standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
  3864. int do_interlace, int use_update_info)
  3865. {
  3866. memset(dp, 0, sizeof *dp);
  3867. dp->ps = ps;
  3868. dp->colour_type = COL_FROM_ID(id);
  3869. dp->bit_depth = DEPTH_FROM_ID(id);
  3870. if (dp->bit_depth < 1 || dp->bit_depth > 16)
  3871. internal_error(ps, "internal: bad bit depth");
  3872. if (dp->colour_type == 3)
  3873. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
  3874. else
  3875. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
  3876. dp->bit_depth;
  3877. dp->interlace_type = INTERLACE_FROM_ID(id);
  3878. check_interlace_type(dp->interlace_type);
  3879. dp->id = id;
  3880. /* All the rest are filled in after the read_info: */
  3881. dp->w = 0;
  3882. dp->h = 0;
  3883. dp->npasses = 0;
  3884. dp->pixel_size = 0;
  3885. dp->bit_width = 0;
  3886. dp->cbRow = 0;
  3887. dp->do_interlace = do_interlace;
  3888. dp->littleendian = 0;
  3889. dp->is_transparent = 0;
  3890. dp->speed = ps->speed;
  3891. dp->use_update_info = use_update_info;
  3892. dp->npalette = 0;
  3893. /* Preset the transparent color to black: */
  3894. memset(&dp->transparent, 0, sizeof dp->transparent);
  3895. /* Preset the palette to full intensity/opaque througout: */
  3896. memset(dp->palette, 0xff, sizeof dp->palette);
  3897. }
  3898. /* Initialize the palette fields - this must be done later because the palette
  3899. * comes from the particular png_store_file that is selected.
  3900. */
  3901. static void
  3902. standard_palette_init(standard_display *dp)
  3903. {
  3904. store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
  3905. /* The remaining entries remain white/opaque. */
  3906. if (dp->npalette > 0)
  3907. {
  3908. int i = dp->npalette;
  3909. memcpy(dp->palette, palette, i * sizeof *palette);
  3910. /* Check for a non-opaque palette entry: */
  3911. while (--i >= 0)
  3912. if (palette[i].alpha < 255)
  3913. break;
  3914. # ifdef __GNUC__
  3915. /* GCC can't handle the more obviously optimizable version. */
  3916. if (i >= 0)
  3917. dp->is_transparent = 1;
  3918. else
  3919. dp->is_transparent = 0;
  3920. # else
  3921. dp->is_transparent = (i >= 0);
  3922. # endif
  3923. }
  3924. }
  3925. /* Utility to read the palette from the PNG file and convert it into
  3926. * store_palette format. This returns 1 if there is any transparency in the
  3927. * palette (it does not check for a transparent colour in the non-palette case.)
  3928. */
  3929. static int
  3930. read_palette(store_palette palette, int *npalette, png_const_structp pp,
  3931. png_infop pi)
  3932. {
  3933. png_colorp pal;
  3934. png_bytep trans_alpha;
  3935. int num;
  3936. pal = 0;
  3937. *npalette = -1;
  3938. if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
  3939. {
  3940. int i = *npalette;
  3941. if (i <= 0 || i > 256)
  3942. png_error(pp, "validate: invalid PLTE count");
  3943. while (--i >= 0)
  3944. {
  3945. palette[i].red = pal[i].red;
  3946. palette[i].green = pal[i].green;
  3947. palette[i].blue = pal[i].blue;
  3948. }
  3949. /* Mark the remainder of the entries with a flag value (other than
  3950. * white/opaque which is the flag value stored above.)
  3951. */
  3952. memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
  3953. }
  3954. else /* !png_get_PLTE */
  3955. {
  3956. if (*npalette != (-1))
  3957. png_error(pp, "validate: invalid PLTE result");
  3958. /* But there is no palette, so record this: */
  3959. *npalette = 0;
  3960. memset(palette, 113, sizeof (store_palette));
  3961. }
  3962. trans_alpha = 0;
  3963. num = 2; /* force error below */
  3964. if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
  3965. (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
  3966. /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
  3967. * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
  3968. * so in the above call we get a success, we get a pointer (who knows what
  3969. * to) and we get num_trans == 0:
  3970. */
  3971. !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
  3972. {
  3973. int i;
  3974. /* Any of these are crash-worthy - given the implementation of
  3975. * png_get_tRNS up to 1.5 an app won't crash if it just checks the
  3976. * result above and fails to check that the variables it passed have
  3977. * actually been filled in! Note that if the app were to pass the
  3978. * last, png_color_16p, variable too it couldn't rely on this.
  3979. */
  3980. if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
  3981. png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
  3982. for (i=0; i<num; ++i)
  3983. palette[i].alpha = trans_alpha[i];
  3984. for (num=*npalette; i<num; ++i)
  3985. palette[i].alpha = 255;
  3986. for (; i<256; ++i)
  3987. palette[i].alpha = 33; /* flag value */
  3988. return 1; /* transparency */
  3989. }
  3990. else
  3991. {
  3992. /* No palette transparency - just set the alpha channel to opaque. */
  3993. int i;
  3994. for (i=0, num=*npalette; i<num; ++i)
  3995. palette[i].alpha = 255;
  3996. for (; i<256; ++i)
  3997. palette[i].alpha = 55; /* flag value */
  3998. return 0; /* no transparency */
  3999. }
  4000. }
  4001. /* Utility to validate the palette if it should not have changed (the
  4002. * non-transform case).
  4003. */
  4004. static void
  4005. standard_palette_validate(standard_display *dp, png_const_structp pp,
  4006. png_infop pi)
  4007. {
  4008. int npalette;
  4009. store_palette palette;
  4010. if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
  4011. png_error(pp, "validate: palette transparency changed");
  4012. if (npalette != dp->npalette)
  4013. {
  4014. size_t pos = 0;
  4015. char msg[64];
  4016. pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
  4017. pos = safecatn(msg, sizeof msg, pos, dp->npalette);
  4018. pos = safecat(msg, sizeof msg, pos, " -> ");
  4019. pos = safecatn(msg, sizeof msg, pos, npalette);
  4020. png_error(pp, msg);
  4021. }
  4022. {
  4023. int i = npalette; /* npalette is aliased */
  4024. while (--i >= 0)
  4025. if (palette[i].red != dp->palette[i].red ||
  4026. palette[i].green != dp->palette[i].green ||
  4027. palette[i].blue != dp->palette[i].blue ||
  4028. palette[i].alpha != dp->palette[i].alpha)
  4029. png_error(pp, "validate: PLTE or tRNS chunk changed");
  4030. }
  4031. }
  4032. /* By passing a 'standard_display' the progressive callbacks can be used
  4033. * directly by the sequential code, the functions suffixed "_imp" are the
  4034. * implementations, the functions without the suffix are the callbacks.
  4035. *
  4036. * The code for the info callback is split into two because this callback calls
  4037. * png_read_update_info or png_start_read_image and what gets called depends on
  4038. * whether the info needs updating (we want to test both calls in pngvalid.)
  4039. */
  4040. static void
  4041. standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
  4042. {
  4043. if (png_get_bit_depth(pp, pi) != dp->bit_depth)
  4044. png_error(pp, "validate: bit depth changed");
  4045. if (png_get_color_type(pp, pi) != dp->colour_type)
  4046. png_error(pp, "validate: color type changed");
  4047. if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
  4048. png_error(pp, "validate: filter type changed");
  4049. if (png_get_interlace_type(pp, pi) != dp->interlace_type)
  4050. png_error(pp, "validate: interlacing changed");
  4051. if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
  4052. png_error(pp, "validate: compression type changed");
  4053. dp->w = png_get_image_width(pp, pi);
  4054. if (dp->w != standard_width(pp, dp->id))
  4055. png_error(pp, "validate: image width changed");
  4056. dp->h = png_get_image_height(pp, pi);
  4057. if (dp->h != standard_height(pp, dp->id))
  4058. png_error(pp, "validate: image height changed");
  4059. /* Record (but don't check at present) the input sBIT according to the colour
  4060. * type information.
  4061. */
  4062. {
  4063. png_color_8p sBIT = 0;
  4064. if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
  4065. {
  4066. int sBIT_invalid = 0;
  4067. if (sBIT == 0)
  4068. png_error(pp, "validate: unexpected png_get_sBIT result");
  4069. if (dp->colour_type & PNG_COLOR_MASK_COLOR)
  4070. {
  4071. if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
  4072. sBIT_invalid = 1;
  4073. else
  4074. dp->red_sBIT = sBIT->red;
  4075. if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
  4076. sBIT_invalid = 1;
  4077. else
  4078. dp->green_sBIT = sBIT->green;
  4079. if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
  4080. sBIT_invalid = 1;
  4081. else
  4082. dp->blue_sBIT = sBIT->blue;
  4083. }
  4084. else /* !COLOR */
  4085. {
  4086. if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
  4087. sBIT_invalid = 1;
  4088. else
  4089. dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
  4090. }
  4091. /* All 8 bits in tRNS for a palette image are significant - see the
  4092. * spec.
  4093. */
  4094. if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
  4095. {
  4096. if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
  4097. sBIT_invalid = 1;
  4098. else
  4099. dp->alpha_sBIT = sBIT->alpha;
  4100. }
  4101. if (sBIT_invalid)
  4102. png_error(pp, "validate: sBIT value out of range");
  4103. }
  4104. }
  4105. /* Important: this is validating the value *before* any transforms have been
  4106. * put in place. It doesn't matter for the standard tests, where there are
  4107. * no transforms, but it does for other tests where rowbytes may change after
  4108. * png_read_update_info.
  4109. */
  4110. if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
  4111. png_error(pp, "validate: row size changed");
  4112. /* Validate the colour type 3 palette (this can be present on other color
  4113. * types.)
  4114. */
  4115. standard_palette_validate(dp, pp, pi);
  4116. /* In any case always check for a tranparent color (notice that the
  4117. * colour type 3 case must not give a successful return on the get_tRNS call
  4118. * with these arguments!)
  4119. */
  4120. {
  4121. png_color_16p trans_color = 0;
  4122. if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
  4123. {
  4124. if (trans_color == 0)
  4125. png_error(pp, "validate: unexpected png_get_tRNS (color) result");
  4126. switch (dp->colour_type)
  4127. {
  4128. case 0:
  4129. dp->transparent.red = dp->transparent.green = dp->transparent.blue =
  4130. trans_color->gray;
  4131. dp->has_tRNS = 1;
  4132. break;
  4133. case 2:
  4134. dp->transparent.red = trans_color->red;
  4135. dp->transparent.green = trans_color->green;
  4136. dp->transparent.blue = trans_color->blue;
  4137. dp->has_tRNS = 1;
  4138. break;
  4139. case 3:
  4140. /* Not expected because it should result in the array case
  4141. * above.
  4142. */
  4143. png_error(pp, "validate: unexpected png_get_tRNS result");
  4144. break;
  4145. default:
  4146. png_error(pp, "validate: invalid tRNS chunk with alpha image");
  4147. }
  4148. }
  4149. }
  4150. /* Read the number of passes - expected to match the value used when
  4151. * creating the image (interlaced or not). This has the side effect of
  4152. * turning on interlace handling (if do_interlace is not set.)
  4153. */
  4154. dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
  4155. if (!dp->do_interlace)
  4156. {
  4157. # ifdef PNG_READ_INTERLACING_SUPPORTED
  4158. if (dp->npasses != png_set_interlace_handling(pp))
  4159. png_error(pp, "validate: file changed interlace type");
  4160. # else /* !READ_INTERLACING */
  4161. /* This should never happen: the relevant tests (!do_interlace) should
  4162. * not be run.
  4163. */
  4164. if (dp->npasses > 1)
  4165. png_error(pp, "validate: no libpng interlace support");
  4166. # endif /* !READ_INTERLACING */
  4167. }
  4168. /* Caller calls png_read_update_info or png_start_read_image now, then calls
  4169. * part2.
  4170. */
  4171. }
  4172. /* This must be called *after* the png_read_update_info call to get the correct
  4173. * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
  4174. * image.
  4175. */
  4176. static void
  4177. standard_info_part2(standard_display *dp, png_const_structp pp,
  4178. png_const_infop pi, int nImages)
  4179. {
  4180. /* Record cbRow now that it can be found. */
  4181. {
  4182. png_byte ct = png_get_color_type(pp, pi);
  4183. png_byte bd = png_get_bit_depth(pp, pi);
  4184. if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
  4185. dp->filler)
  4186. ct |= 4; /* handle filler as faked alpha channel */
  4187. dp->pixel_size = bit_size(pp, ct, bd);
  4188. }
  4189. dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
  4190. dp->cbRow = png_get_rowbytes(pp, pi);
  4191. /* Validate the rowbytes here again. */
  4192. if (dp->cbRow != (dp->bit_width+7)/8)
  4193. png_error(pp, "bad png_get_rowbytes calculation");
  4194. /* Then ensure there is enough space for the output image(s). */
  4195. store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
  4196. }
  4197. static void
  4198. standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
  4199. int nImages)
  4200. {
  4201. /* Note that the validation routine has the side effect of turning on
  4202. * interlace handling in the subsequent code.
  4203. */
  4204. standard_info_part1(dp, pp, pi);
  4205. /* And the info callback has to call this (or png_read_update_info - see
  4206. * below in the png_modifier code for that variant.
  4207. */
  4208. if (dp->use_update_info)
  4209. {
  4210. /* For debugging the effect of multiple calls: */
  4211. int i = dp->use_update_info;
  4212. while (i-- > 0)
  4213. png_read_update_info(pp, pi);
  4214. }
  4215. else
  4216. png_start_read_image(pp);
  4217. /* Validate the height, width and rowbytes plus ensure that sufficient buffer
  4218. * exists for decoding the image.
  4219. */
  4220. standard_info_part2(dp, pp, pi, nImages);
  4221. }
  4222. static void PNGCBAPI
  4223. standard_info(png_structp pp, png_infop pi)
  4224. {
  4225. standard_display *dp = voidcast(standard_display*,
  4226. png_get_progressive_ptr(pp));
  4227. /* Call with nImages==1 because the progressive reader can only produce one
  4228. * image.
  4229. */
  4230. standard_info_imp(dp, pp, pi, 1 /*only one image*/);
  4231. }
  4232. static void PNGCBAPI
  4233. progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
  4234. {
  4235. png_const_structp pp = ppIn;
  4236. const standard_display *dp = voidcast(standard_display*,
  4237. png_get_progressive_ptr(pp));
  4238. /* When handling interlacing some rows will be absent in each pass, the
  4239. * callback still gets called, but with a NULL pointer. This is checked
  4240. * in the 'else' clause below. We need our own 'cbRow', but we can't call
  4241. * png_get_rowbytes because we got no info structure.
  4242. */
  4243. if (new_row != NULL)
  4244. {
  4245. png_bytep row;
  4246. /* In the case where the reader doesn't do the interlace it gives
  4247. * us the y in the sub-image:
  4248. */
  4249. if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
  4250. {
  4251. #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
  4252. /* Use this opportunity to validate the png 'current' APIs: */
  4253. if (y != png_get_current_row_number(pp))
  4254. png_error(pp, "png_get_current_row_number is broken");
  4255. if (pass != png_get_current_pass_number(pp))
  4256. png_error(pp, "png_get_current_pass_number is broken");
  4257. #endif /* USER_TRANSFORM_INFO */
  4258. y = PNG_ROW_FROM_PASS_ROW(y, pass);
  4259. }
  4260. /* Validate this just in case. */
  4261. if (y >= dp->h)
  4262. png_error(pp, "invalid y to progressive row callback");
  4263. row = store_image_row(dp->ps, pp, 0, y);
  4264. /* Combine the new row into the old: */
  4265. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4266. if (dp->do_interlace)
  4267. #endif /* READ_INTERLACING */
  4268. {
  4269. if (dp->interlace_type == PNG_INTERLACE_ADAM7)
  4270. deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass,
  4271. dp->littleendian);
  4272. else
  4273. row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian);
  4274. }
  4275. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4276. else
  4277. png_progressive_combine_row(pp, row, new_row);
  4278. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  4279. }
  4280. else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
  4281. PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  4282. PNG_PASS_COLS(dp->w, pass) > 0)
  4283. png_error(pp, "missing row in progressive de-interlacing");
  4284. }
  4285. static void
  4286. sequential_row(standard_display *dp, png_structp pp, png_infop pi,
  4287. const int iImage, const int iDisplay)
  4288. {
  4289. const int npasses = dp->npasses;
  4290. const int do_interlace = dp->do_interlace &&
  4291. dp->interlace_type == PNG_INTERLACE_ADAM7;
  4292. const png_uint_32 height = standard_height(pp, dp->id);
  4293. const png_uint_32 width = standard_width(pp, dp->id);
  4294. const png_store* ps = dp->ps;
  4295. int pass;
  4296. for (pass=0; pass<npasses; ++pass)
  4297. {
  4298. png_uint_32 y;
  4299. png_uint_32 wPass = PNG_PASS_COLS(width, pass);
  4300. for (y=0; y<height; ++y)
  4301. {
  4302. if (do_interlace)
  4303. {
  4304. /* wPass may be zero or this row may not be in this pass.
  4305. * png_read_row must not be called in either case.
  4306. */
  4307. if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
  4308. {
  4309. /* Read the row into a pair of temporary buffers, then do the
  4310. * merge here into the output rows.
  4311. */
  4312. png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
  4313. /* The following aids (to some extent) error detection - we can
  4314. * see where png_read_row wrote. Use opposite values in row and
  4315. * display to make this easier. Don't use 0xff (which is used in
  4316. * the image write code to fill unused bits) or 0 (which is a
  4317. * likely value to overwrite unused bits with).
  4318. */
  4319. memset(row, 0xc5, sizeof row);
  4320. memset(display, 0x5c, sizeof display);
  4321. png_read_row(pp, row, display);
  4322. if (iImage >= 0)
  4323. deinterlace_row(store_image_row(ps, pp, iImage, y), row,
  4324. dp->pixel_size, dp->w, pass, dp->littleendian);
  4325. if (iDisplay >= 0)
  4326. deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
  4327. dp->pixel_size, dp->w, pass, dp->littleendian);
  4328. }
  4329. }
  4330. else
  4331. png_read_row(pp,
  4332. iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
  4333. iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
  4334. }
  4335. }
  4336. /* And finish the read operation (only really necessary if the caller wants
  4337. * to find additional data in png_info from chunks after the last IDAT.)
  4338. */
  4339. png_read_end(pp, pi);
  4340. }
  4341. #ifdef PNG_TEXT_SUPPORTED
  4342. static void
  4343. standard_check_text(png_const_structp pp, png_const_textp tp,
  4344. png_const_charp keyword, png_const_charp text)
  4345. {
  4346. char msg[1024];
  4347. size_t pos = safecat(msg, sizeof msg, 0, "text: ");
  4348. size_t ok;
  4349. pos = safecat(msg, sizeof msg, pos, keyword);
  4350. pos = safecat(msg, sizeof msg, pos, ": ");
  4351. ok = pos;
  4352. if (tp->compression != TEXT_COMPRESSION)
  4353. {
  4354. char buf[64];
  4355. sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
  4356. tp->compression);
  4357. pos = safecat(msg, sizeof msg, pos, buf);
  4358. }
  4359. if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
  4360. {
  4361. pos = safecat(msg, sizeof msg, pos, "keyword \"");
  4362. if (tp->key != NULL)
  4363. {
  4364. pos = safecat(msg, sizeof msg, pos, tp->key);
  4365. pos = safecat(msg, sizeof msg, pos, "\", ");
  4366. }
  4367. else
  4368. pos = safecat(msg, sizeof msg, pos, "null, ");
  4369. }
  4370. if (tp->text == NULL)
  4371. pos = safecat(msg, sizeof msg, pos, "text lost, ");
  4372. else
  4373. {
  4374. if (tp->text_length != strlen(text))
  4375. {
  4376. char buf[64];
  4377. sprintf(buf, "text length changed[%lu->%lu], ",
  4378. (unsigned long)strlen(text), (unsigned long)tp->text_length);
  4379. pos = safecat(msg, sizeof msg, pos, buf);
  4380. }
  4381. if (strcmp(tp->text, text) != 0)
  4382. {
  4383. pos = safecat(msg, sizeof msg, pos, "text becomes \"");
  4384. pos = safecat(msg, sizeof msg, pos, tp->text);
  4385. pos = safecat(msg, sizeof msg, pos, "\" (was \"");
  4386. pos = safecat(msg, sizeof msg, pos, text);
  4387. pos = safecat(msg, sizeof msg, pos, "\"), ");
  4388. }
  4389. }
  4390. if (tp->itxt_length != 0)
  4391. pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
  4392. if (tp->lang != NULL)
  4393. {
  4394. pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
  4395. pos = safecat(msg, sizeof msg, pos, tp->lang);
  4396. pos = safecat(msg, sizeof msg, pos, "\", ");
  4397. }
  4398. if (tp->lang_key != NULL)
  4399. {
  4400. pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
  4401. pos = safecat(msg, sizeof msg, pos, tp->lang_key);
  4402. pos = safecat(msg, sizeof msg, pos, "\", ");
  4403. }
  4404. if (pos > ok)
  4405. {
  4406. msg[pos-2] = '\0'; /* Remove the ", " at the end */
  4407. png_error(pp, msg);
  4408. }
  4409. }
  4410. static void
  4411. standard_text_validate(standard_display *dp, png_const_structp pp,
  4412. png_infop pi, int check_end)
  4413. {
  4414. png_textp tp = NULL;
  4415. png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
  4416. if (num_text == 2 && tp != NULL)
  4417. {
  4418. standard_check_text(pp, tp, "image name", dp->ps->current->name);
  4419. /* This exists because prior to 1.5.18 the progressive reader left the
  4420. * png_struct z_stream unreset at the end of the image, so subsequent
  4421. * attempts to use it simply returns Z_STREAM_END.
  4422. */
  4423. if (check_end)
  4424. standard_check_text(pp, tp+1, "end marker", "end");
  4425. }
  4426. else
  4427. {
  4428. char msg[64];
  4429. sprintf(msg, "expected two text items, got %lu",
  4430. (unsigned long)num_text);
  4431. png_error(pp, msg);
  4432. }
  4433. }
  4434. #else
  4435. # define standard_text_validate(dp,pp,pi,check_end) ((void)0)
  4436. #endif
  4437. static void
  4438. standard_row_validate(standard_display *dp, png_const_structp pp,
  4439. int iImage, int iDisplay, png_uint_32 y)
  4440. {
  4441. int where;
  4442. png_byte std[STANDARD_ROWMAX];
  4443. /* The row must be pre-initialized to the magic number here for the size
  4444. * tests to pass:
  4445. */
  4446. memset(std, 178, sizeof std);
  4447. standard_row(pp, std, dp->id, y);
  4448. /* At the end both the 'row' and 'display' arrays should end up identical.
  4449. * In earlier passes 'row' will be partially filled in, with only the pixels
  4450. * that have been read so far, but 'display' will have those pixels
  4451. * replicated to fill the unread pixels while reading an interlaced image.
  4452. */
  4453. if (iImage >= 0 &&
  4454. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
  4455. dp->bit_width)) != 0)
  4456. {
  4457. char msg[64];
  4458. sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
  4459. (unsigned long)y, where-1, std[where-1],
  4460. store_image_row(dp->ps, pp, iImage, y)[where-1]);
  4461. png_error(pp, msg);
  4462. }
  4463. if (iDisplay >= 0 &&
  4464. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
  4465. dp->bit_width)) != 0)
  4466. {
  4467. char msg[64];
  4468. sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
  4469. (unsigned long)y, where-1, std[where-1],
  4470. store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
  4471. png_error(pp, msg);
  4472. }
  4473. }
  4474. static void
  4475. standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
  4476. int iDisplay)
  4477. {
  4478. png_uint_32 y;
  4479. if (iImage >= 0)
  4480. store_image_check(dp->ps, pp, iImage);
  4481. if (iDisplay >= 0)
  4482. store_image_check(dp->ps, pp, iDisplay);
  4483. for (y=0; y<dp->h; ++y)
  4484. standard_row_validate(dp, pp, iImage, iDisplay, y);
  4485. /* This avoids false positives if the validation code is never called! */
  4486. dp->ps->validated = 1;
  4487. }
  4488. static void PNGCBAPI
  4489. standard_end(png_structp ppIn, png_infop pi)
  4490. {
  4491. png_const_structp pp = ppIn;
  4492. standard_display *dp = voidcast(standard_display*,
  4493. png_get_progressive_ptr(pp));
  4494. UNUSED(pi)
  4495. /* Validate the image - progressive reading only produces one variant for
  4496. * interlaced images.
  4497. */
  4498. standard_text_validate(dp, pp, pi,
  4499. PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
  4500. standard_image_validate(dp, pp, 0, -1);
  4501. }
  4502. /* A single test run checking the standard image to ensure it is not damaged. */
  4503. static void
  4504. standard_test(png_store* const psIn, png_uint_32 const id,
  4505. int do_interlace, int use_update_info)
  4506. {
  4507. standard_display d;
  4508. context(psIn, fault);
  4509. /* Set up the display (stack frame) variables from the arguments to the
  4510. * function and initialize the locals that are filled in later.
  4511. */
  4512. standard_display_init(&d, psIn, id, do_interlace, use_update_info);
  4513. /* Everything is protected by a Try/Catch. The functions called also
  4514. * typically have local Try/Catch blocks.
  4515. */
  4516. Try
  4517. {
  4518. png_structp pp;
  4519. png_infop pi;
  4520. /* Get a png_struct for reading the image. This will throw an error if it
  4521. * fails, so we don't need to check the result.
  4522. */
  4523. pp = set_store_for_read(d.ps, &pi, d.id,
  4524. d.do_interlace ? (d.ps->progressive ?
  4525. "pngvalid progressive deinterlacer" :
  4526. "pngvalid sequential deinterlacer") : (d.ps->progressive ?
  4527. "progressive reader" : "sequential reader"));
  4528. /* Initialize the palette correctly from the png_store_file. */
  4529. standard_palette_init(&d);
  4530. /* Introduce the correct read function. */
  4531. if (d.ps->progressive)
  4532. {
  4533. png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
  4534. standard_end);
  4535. /* Now feed data into the reader until we reach the end: */
  4536. store_progressive_read(d.ps, pp, pi);
  4537. }
  4538. else
  4539. {
  4540. /* Note that this takes the store, not the display. */
  4541. png_set_read_fn(pp, d.ps, store_read);
  4542. /* Check the header values: */
  4543. png_read_info(pp, pi);
  4544. /* The code tests both versions of the images that the sequential
  4545. * reader can produce.
  4546. */
  4547. standard_info_imp(&d, pp, pi, 2 /*images*/);
  4548. /* Need the total bytes in the image below; we can't get to this point
  4549. * unless the PNG file values have been checked against the expected
  4550. * values.
  4551. */
  4552. {
  4553. sequential_row(&d, pp, pi, 0, 1);
  4554. /* After the last pass loop over the rows again to check that the
  4555. * image is correct.
  4556. */
  4557. if (!d.speed)
  4558. {
  4559. standard_text_validate(&d, pp, pi, 1/*check_end*/);
  4560. standard_image_validate(&d, pp, 0, 1);
  4561. }
  4562. else
  4563. d.ps->validated = 1;
  4564. }
  4565. }
  4566. /* Check for validation. */
  4567. if (!d.ps->validated)
  4568. png_error(pp, "image read failed silently");
  4569. /* Successful completion. */
  4570. }
  4571. Catch(fault)
  4572. d.ps = fault; /* make sure this hasn't been clobbered. */
  4573. /* In either case clean up the store. */
  4574. store_read_reset(d.ps);
  4575. }
  4576. static int
  4577. test_standard(png_modifier* const pm, png_byte const colour_type,
  4578. int bdlo, int const bdhi)
  4579. {
  4580. for (; bdlo <= bdhi; ++bdlo)
  4581. {
  4582. int interlace_type;
  4583. for (interlace_type = PNG_INTERLACE_NONE;
  4584. interlace_type < INTERLACE_LAST; ++interlace_type)
  4585. {
  4586. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4587. interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info);
  4588. if (fail(pm))
  4589. return 0;
  4590. }
  4591. }
  4592. return 1; /* keep going */
  4593. }
  4594. static void
  4595. perform_standard_test(png_modifier *pm)
  4596. {
  4597. /* Test each colour type over the valid range of bit depths (expressed as
  4598. * log2(bit_depth) in turn, stop as soon as any error is detected.
  4599. */
  4600. if (!test_standard(pm, 0, 0, READ_BDHI))
  4601. return;
  4602. if (!test_standard(pm, 2, 3, READ_BDHI))
  4603. return;
  4604. if (!test_standard(pm, 3, 0, 3))
  4605. return;
  4606. if (!test_standard(pm, 4, 3, READ_BDHI))
  4607. return;
  4608. if (!test_standard(pm, 6, 3, READ_BDHI))
  4609. return;
  4610. }
  4611. /********************************** SIZE TESTS ********************************/
  4612. static int
  4613. test_size(png_modifier* const pm, png_byte const colour_type,
  4614. int bdlo, int const bdhi)
  4615. {
  4616. /* Run the tests on each combination.
  4617. *
  4618. * NOTE: on my 32 bit x86 each of the following blocks takes
  4619. * a total of 3.5 seconds if done across every combo of bit depth
  4620. * width and height. This is a waste of time in practice, hence the
  4621. * hinc and winc stuff:
  4622. */
  4623. static const png_byte hinc[] = {1, 3, 11, 1, 5};
  4624. static const png_byte winc[] = {1, 9, 5, 7, 1};
  4625. const int save_bdlo = bdlo;
  4626. for (; bdlo <= bdhi; ++bdlo)
  4627. {
  4628. png_uint_32 h, w;
  4629. for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
  4630. {
  4631. /* First test all the 'size' images against the sequential
  4632. * reader using libpng to deinterlace (where required.) This
  4633. * validates the write side of libpng. There are four possibilities
  4634. * to validate.
  4635. */
  4636. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4637. PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
  4638. pm->use_update_info);
  4639. if (fail(pm))
  4640. return 0;
  4641. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4642. PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
  4643. pm->use_update_info);
  4644. if (fail(pm))
  4645. return 0;
  4646. /* Now validate the interlaced read side - do_interlace true,
  4647. * in the progressive case this does actually make a difference
  4648. * to the code used in the non-interlaced case too.
  4649. */
  4650. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4651. PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
  4652. pm->use_update_info);
  4653. if (fail(pm))
  4654. return 0;
  4655. # if CAN_WRITE_INTERLACE
  4656. /* Validate the pngvalid code itself: */
  4657. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4658. PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
  4659. pm->use_update_info);
  4660. if (fail(pm))
  4661. return 0;
  4662. # endif
  4663. }
  4664. }
  4665. /* Now do the tests of libpng interlace handling, after we have made sure
  4666. * that the pngvalid version works:
  4667. */
  4668. for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
  4669. {
  4670. png_uint_32 h, w;
  4671. for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
  4672. {
  4673. # ifdef PNG_READ_INTERLACING_SUPPORTED
  4674. /* Test with pngvalid generated interlaced images first; we have
  4675. * already verify these are ok (unless pngvalid has self-consistent
  4676. * read/write errors, which is unlikely), so this detects errors in the
  4677. * read side first:
  4678. */
  4679. # if CAN_WRITE_INTERLACE
  4680. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4681. PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
  4682. pm->use_update_info);
  4683. if (fail(pm))
  4684. return 0;
  4685. # endif
  4686. # endif /* READ_INTERLACING */
  4687. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  4688. /* Test the libpng write side against the pngvalid read side: */
  4689. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4690. PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
  4691. pm->use_update_info);
  4692. if (fail(pm))
  4693. return 0;
  4694. # endif
  4695. # ifdef PNG_READ_INTERLACING_SUPPORTED
  4696. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  4697. /* Test both together: */
  4698. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4699. PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
  4700. pm->use_update_info);
  4701. if (fail(pm))
  4702. return 0;
  4703. # endif
  4704. # endif /* READ_INTERLACING */
  4705. }
  4706. }
  4707. return 1; /* keep going */
  4708. }
  4709. static void
  4710. perform_size_test(png_modifier *pm)
  4711. {
  4712. /* Test each colour type over the valid range of bit depths (expressed as
  4713. * log2(bit_depth) in turn, stop as soon as any error is detected.
  4714. */
  4715. if (!test_size(pm, 0, 0, READ_BDHI))
  4716. return;
  4717. if (!test_size(pm, 2, 3, READ_BDHI))
  4718. return;
  4719. /* For the moment don't do the palette test - it's a waste of time when
  4720. * compared to the grayscale test.
  4721. */
  4722. #if 0
  4723. if (!test_size(pm, 3, 0, 3))
  4724. return;
  4725. #endif
  4726. if (!test_size(pm, 4, 3, READ_BDHI))
  4727. return;
  4728. if (!test_size(pm, 6, 3, READ_BDHI))
  4729. return;
  4730. }
  4731. /******************************* TRANSFORM TESTS ******************************/
  4732. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  4733. /* A set of tests to validate libpng image transforms. The possibilities here
  4734. * are legion because the transforms can be combined in a combinatorial
  4735. * fashion. To deal with this some measure of restraint is required, otherwise
  4736. * the tests would take forever.
  4737. */
  4738. typedef struct image_pixel
  4739. {
  4740. /* A local (pngvalid) representation of a PNG pixel, in all its
  4741. * various forms.
  4742. */
  4743. unsigned int red, green, blue, alpha; /* For non-palette images. */
  4744. unsigned int palette_index; /* For a palette image. */
  4745. png_byte colour_type; /* As in the spec. */
  4746. png_byte bit_depth; /* Defines bit size in row */
  4747. png_byte sample_depth; /* Scale of samples */
  4748. unsigned int have_tRNS :1; /* tRNS chunk may need processing */
  4749. unsigned int swap_rgb :1; /* RGB swapped to BGR */
  4750. unsigned int alpha_first :1; /* Alpha at start, not end */
  4751. unsigned int alpha_inverted :1; /* Alpha channel inverted */
  4752. unsigned int mono_inverted :1; /* Gray channel inverted */
  4753. unsigned int swap16 :1; /* Byte swap 16-bit components */
  4754. unsigned int littleendian :1; /* High bits on right */
  4755. unsigned int sig_bits :1; /* Pixel shifted (sig bits only) */
  4756. /* For checking the code calculates double precision floating point values
  4757. * along with an error value, accumulated from the transforms. Because an
  4758. * sBIT setting allows larger error bounds (indeed, by the spec, apparently
  4759. * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
  4760. * channel is stored. This sBIT value is folded in to the stored error value
  4761. * at the end of the application of the transforms to the pixel.
  4762. *
  4763. * If sig_bits is set above the red, green, blue and alpha values have been
  4764. * scaled so they only contain the significant bits of the component values.
  4765. */
  4766. double redf, greenf, bluef, alphaf;
  4767. double rede, greene, bluee, alphae;
  4768. png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
  4769. } image_pixel;
  4770. /* Shared utility function, see below. */
  4771. static void
  4772. image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
  4773. unsigned int bMax, unsigned int aMax)
  4774. {
  4775. this->redf = this->red / (double)rMax;
  4776. this->greenf = this->green / (double)gMax;
  4777. this->bluef = this->blue / (double)bMax;
  4778. this->alphaf = this->alpha / (double)aMax;
  4779. if (this->red < rMax)
  4780. this->rede = this->redf * DBL_EPSILON;
  4781. else
  4782. this->rede = 0;
  4783. if (this->green < gMax)
  4784. this->greene = this->greenf * DBL_EPSILON;
  4785. else
  4786. this->greene = 0;
  4787. if (this->blue < bMax)
  4788. this->bluee = this->bluef * DBL_EPSILON;
  4789. else
  4790. this->bluee = 0;
  4791. if (this->alpha < aMax)
  4792. this->alphae = this->alphaf * DBL_EPSILON;
  4793. else
  4794. this->alphae = 0;
  4795. }
  4796. /* Initialize the structure for the next pixel - call this before doing any
  4797. * transforms and call it for each pixel since all the fields may need to be
  4798. * reset.
  4799. */
  4800. static void
  4801. image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
  4802. png_byte bit_depth, png_uint_32 x, store_palette palette,
  4803. const image_pixel *format /*from pngvalid transform of input*/)
  4804. {
  4805. const png_byte sample_depth = (png_byte)(colour_type ==
  4806. PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
  4807. const unsigned int max = (1U<<sample_depth)-1;
  4808. const int swap16 = (format != 0 && format->swap16);
  4809. const int littleendian = (format != 0 && format->littleendian);
  4810. const int sig_bits = (format != 0 && format->sig_bits);
  4811. /* Initially just set everything to the same number and the alpha to opaque.
  4812. * Note that this currently assumes a simple palette where entry x has colour
  4813. * rgb(x,x,x)!
  4814. */
  4815. this->palette_index = this->red = this->green = this->blue =
  4816. sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
  4817. this->alpha = max;
  4818. this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
  4819. sample_depth;
  4820. /* Then override as appropriate: */
  4821. if (colour_type == 3) /* palette */
  4822. {
  4823. /* This permits the caller to default to the sample value. */
  4824. if (palette != 0)
  4825. {
  4826. const unsigned int i = this->palette_index;
  4827. this->red = palette[i].red;
  4828. this->green = palette[i].green;
  4829. this->blue = palette[i].blue;
  4830. this->alpha = palette[i].alpha;
  4831. }
  4832. }
  4833. else /* not palette */
  4834. {
  4835. unsigned int i = 0;
  4836. if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
  4837. {
  4838. this->alpha = this->red;
  4839. /* This handles the gray case for 'AG' pixels */
  4840. this->palette_index = this->red = this->green = this->blue =
  4841. sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
  4842. i = 1;
  4843. }
  4844. if (colour_type & 2)
  4845. {
  4846. /* Green is second for both BGR and RGB: */
  4847. this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
  4848. littleendian);
  4849. if (format != 0 && format->swap_rgb) /* BGR */
  4850. this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
  4851. littleendian);
  4852. else
  4853. this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
  4854. littleendian);
  4855. }
  4856. else /* grayscale */ if (format != 0 && format->mono_inverted)
  4857. this->red = this->green = this->blue = this->red ^ max;
  4858. if ((colour_type & 4) != 0) /* alpha */
  4859. {
  4860. if (format == 0 || !format->alpha_first)
  4861. this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
  4862. littleendian);
  4863. if (format != 0 && format->alpha_inverted)
  4864. this->alpha ^= max;
  4865. }
  4866. }
  4867. /* Calculate the scaled values, these are simply the values divided by
  4868. * 'max' and the error is initialized to the double precision epsilon value
  4869. * from the header file.
  4870. */
  4871. image_pixel_setf(this,
  4872. sig_bits ? (1U << format->red_sBIT)-1 : max,
  4873. sig_bits ? (1U << format->green_sBIT)-1 : max,
  4874. sig_bits ? (1U << format->blue_sBIT)-1 : max,
  4875. sig_bits ? (1U << format->alpha_sBIT)-1 : max);
  4876. /* Store the input information for use in the transforms - these will
  4877. * modify the information.
  4878. */
  4879. this->colour_type = colour_type;
  4880. this->bit_depth = bit_depth;
  4881. this->sample_depth = sample_depth;
  4882. this->have_tRNS = 0;
  4883. this->swap_rgb = 0;
  4884. this->alpha_first = 0;
  4885. this->alpha_inverted = 0;
  4886. this->mono_inverted = 0;
  4887. this->swap16 = 0;
  4888. this->littleendian = 0;
  4889. this->sig_bits = 0;
  4890. }
  4891. #if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\
  4892. || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\
  4893. || defined PNG_READ_BACKGROUND_SUPPORTED
  4894. /* Convert a palette image to an rgb image. This necessarily converts the tRNS
  4895. * chunk at the same time, because the tRNS will be in palette form. The way
  4896. * palette validation works means that the original palette is never updated,
  4897. * instead the image_pixel value from the row contains the RGB of the
  4898. * corresponding palette entry and *this* is updated. Consequently this routine
  4899. * only needs to change the colour type information.
  4900. */
  4901. static void
  4902. image_pixel_convert_PLTE(image_pixel *this)
  4903. {
  4904. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  4905. {
  4906. if (this->have_tRNS)
  4907. {
  4908. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  4909. this->have_tRNS = 0;
  4910. }
  4911. else
  4912. this->colour_type = PNG_COLOR_TYPE_RGB;
  4913. /* The bit depth of the row changes at this point too (notice that this is
  4914. * the row format, not the sample depth, which is separate.)
  4915. */
  4916. this->bit_depth = 8;
  4917. }
  4918. }
  4919. /* Add an alpha channel; this will import the tRNS information because tRNS is
  4920. * not valid in an alpha image. The bit depth will invariably be set to at
  4921. * least 8 prior to 1.7.0. Palette images will be converted to alpha (using
  4922. * the above API). With png_set_background the alpha channel is never expanded
  4923. * but this routine is used by pngvalid to simplify code; 'for_background'
  4924. * records this.
  4925. */
  4926. static void
  4927. image_pixel_add_alpha(image_pixel *this, const standard_display *display,
  4928. int for_background)
  4929. {
  4930. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  4931. image_pixel_convert_PLTE(this);
  4932. if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
  4933. {
  4934. if (this->colour_type == PNG_COLOR_TYPE_GRAY)
  4935. {
  4936. # if PNG_LIBPNG_VER < 10700
  4937. if (!for_background && this->bit_depth < 8)
  4938. this->bit_depth = this->sample_depth = 8;
  4939. # endif
  4940. if (this->have_tRNS)
  4941. {
  4942. /* After 1.7 the expansion of bit depth only happens if there is a
  4943. * tRNS chunk to expand at this point.
  4944. */
  4945. # if PNG_LIBPNG_VER >= 10700
  4946. if (!for_background && this->bit_depth < 8)
  4947. this->bit_depth = this->sample_depth = 8;
  4948. # endif
  4949. this->have_tRNS = 0;
  4950. /* Check the input, original, channel value here against the
  4951. * original tRNS gray chunk valie.
  4952. */
  4953. if (this->red == display->transparent.red)
  4954. this->alphaf = 0;
  4955. else
  4956. this->alphaf = 1;
  4957. }
  4958. else
  4959. this->alphaf = 1;
  4960. this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  4961. }
  4962. else if (this->colour_type == PNG_COLOR_TYPE_RGB)
  4963. {
  4964. if (this->have_tRNS)
  4965. {
  4966. this->have_tRNS = 0;
  4967. /* Again, check the exact input values, not the current transformed
  4968. * value!
  4969. */
  4970. if (this->red == display->transparent.red &&
  4971. this->green == display->transparent.green &&
  4972. this->blue == display->transparent.blue)
  4973. this->alphaf = 0;
  4974. else
  4975. this->alphaf = 1;
  4976. }
  4977. else
  4978. this->alphaf = 1;
  4979. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  4980. }
  4981. /* The error in the alpha is zero and the sBIT value comes from the
  4982. * original sBIT data (actually it will always be the original bit depth).
  4983. */
  4984. this->alphae = 0;
  4985. this->alpha_sBIT = display->alpha_sBIT;
  4986. }
  4987. }
  4988. #endif /* transforms that need image_pixel_add_alpha */
  4989. struct transform_display;
  4990. typedef struct image_transform
  4991. {
  4992. /* The name of this transform: a string. */
  4993. const char *name;
  4994. /* Each transform can be disabled from the command line: */
  4995. int enable;
  4996. /* The global list of transforms; read only. */
  4997. struct image_transform *const list;
  4998. /* The global count of the number of times this transform has been set on an
  4999. * image.
  5000. */
  5001. unsigned int global_use;
  5002. /* The local count of the number of times this transform has been set. */
  5003. unsigned int local_use;
  5004. /* The next transform in the list, each transform must call its own next
  5005. * transform after it has processed the pixel successfully.
  5006. */
  5007. const struct image_transform *next;
  5008. /* A single transform for the image, expressed as a series of function
  5009. * callbacks and some space for values.
  5010. *
  5011. * First a callback to add any required modifications to the png_modifier;
  5012. * this gets called just before the modifier is set up for read.
  5013. */
  5014. void (*ini)(const struct image_transform *this,
  5015. struct transform_display *that);
  5016. /* And a callback to set the transform on the current png_read_struct:
  5017. */
  5018. void (*set)(const struct image_transform *this,
  5019. struct transform_display *that, png_structp pp, png_infop pi);
  5020. /* Then a transform that takes an input pixel in one PNG format or another
  5021. * and modifies it by a pngvalid implementation of the transform (thus
  5022. * duplicating the libpng intent without, we hope, duplicating the bugs
  5023. * in the libpng implementation!) The png_structp is solely to allow error
  5024. * reporting via png_error and png_warning.
  5025. */
  5026. void (*mod)(const struct image_transform *this, image_pixel *that,
  5027. png_const_structp pp, const struct transform_display *display);
  5028. /* Add this transform to the list and return true if the transform is
  5029. * meaningful for this colour type and bit depth - if false then the
  5030. * transform should have no effect on the image so there's not a lot of
  5031. * point running it.
  5032. */
  5033. int (*add)(struct image_transform *this,
  5034. const struct image_transform **that, png_byte colour_type,
  5035. png_byte bit_depth);
  5036. } image_transform;
  5037. typedef struct transform_display
  5038. {
  5039. standard_display this;
  5040. /* Parameters */
  5041. png_modifier* pm;
  5042. const image_transform* transform_list;
  5043. unsigned int max_gamma_8;
  5044. /* Local variables */
  5045. png_byte output_colour_type;
  5046. png_byte output_bit_depth;
  5047. png_byte unpacked;
  5048. /* Modifications (not necessarily used.) */
  5049. gama_modification gama_mod;
  5050. chrm_modification chrm_mod;
  5051. srgb_modification srgb_mod;
  5052. } transform_display;
  5053. /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
  5054. static void
  5055. transform_set_encoding(transform_display *this)
  5056. {
  5057. /* Set up the png_modifier '_current' fields then use these to determine how
  5058. * to add appropriate chunks.
  5059. */
  5060. png_modifier *pm = this->pm;
  5061. modifier_set_encoding(pm);
  5062. if (modifier_color_encoding_is_set(pm))
  5063. {
  5064. if (modifier_color_encoding_is_sRGB(pm))
  5065. srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
  5066. else
  5067. {
  5068. /* Set gAMA and cHRM separately. */
  5069. gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
  5070. if (pm->current_encoding != 0)
  5071. chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
  5072. }
  5073. }
  5074. }
  5075. /* Three functions to end the list: */
  5076. static void
  5077. image_transform_ini_end(const image_transform *this,
  5078. transform_display *that)
  5079. {
  5080. UNUSED(this)
  5081. UNUSED(that)
  5082. }
  5083. static void
  5084. image_transform_set_end(const image_transform *this,
  5085. transform_display *that, png_structp pp, png_infop pi)
  5086. {
  5087. UNUSED(this)
  5088. UNUSED(that)
  5089. UNUSED(pp)
  5090. UNUSED(pi)
  5091. }
  5092. /* At the end of the list recalculate the output image pixel value from the
  5093. * double precision values set up by the preceding 'mod' calls:
  5094. */
  5095. static unsigned int
  5096. sample_scale(double sample_value, unsigned int scale)
  5097. {
  5098. sample_value = floor(sample_value * scale + .5);
  5099. /* Return NaN as 0: */
  5100. if (!(sample_value > 0))
  5101. sample_value = 0;
  5102. else if (sample_value > scale)
  5103. sample_value = scale;
  5104. return (unsigned int)sample_value;
  5105. }
  5106. static void
  5107. image_transform_mod_end(const image_transform *this, image_pixel *that,
  5108. png_const_structp pp, const transform_display *display)
  5109. {
  5110. const unsigned int scale = (1U<<that->sample_depth)-1;
  5111. const int sig_bits = that->sig_bits;
  5112. UNUSED(this)
  5113. UNUSED(pp)
  5114. UNUSED(display)
  5115. /* At the end recalculate the digitized red green and blue values according
  5116. * to the current sample_depth of the pixel.
  5117. *
  5118. * The sample value is simply scaled to the maximum, checking for over
  5119. * and underflow (which can both happen for some image transforms,
  5120. * including simple size scaling, though libpng doesn't do that at present.
  5121. */
  5122. that->red = sample_scale(that->redf, scale);
  5123. /* This is a bit bogus; really the above calculation should use the red_sBIT
  5124. * value, not sample_depth, but because libpng does png_set_shift by just
  5125. * shifting the bits we get errors if we don't do it the same way.
  5126. */
  5127. if (sig_bits && that->red_sBIT < that->sample_depth)
  5128. that->red >>= that->sample_depth - that->red_sBIT;
  5129. /* The error value is increased, at the end, according to the lowest sBIT
  5130. * value seen. Common sense tells us that the intermediate integer
  5131. * representations are no more accurate than +/- 0.5 in the integral values,
  5132. * the sBIT allows the implementation to be worse than this. In addition the
  5133. * PNG specification actually permits any error within the range (-1..+1),
  5134. * but that is ignored here. Instead the final digitized value is compared,
  5135. * below to the digitized value of the error limits - this has the net effect
  5136. * of allowing (almost) +/-1 in the output value. It's difficult to see how
  5137. * any algorithm that digitizes intermediate results can be more accurate.
  5138. */
  5139. that->rede += 1./(2*((1U<<that->red_sBIT)-1));
  5140. if (that->colour_type & PNG_COLOR_MASK_COLOR)
  5141. {
  5142. that->green = sample_scale(that->greenf, scale);
  5143. if (sig_bits && that->green_sBIT < that->sample_depth)
  5144. that->green >>= that->sample_depth - that->green_sBIT;
  5145. that->blue = sample_scale(that->bluef, scale);
  5146. if (sig_bits && that->blue_sBIT < that->sample_depth)
  5147. that->blue >>= that->sample_depth - that->blue_sBIT;
  5148. that->greene += 1./(2*((1U<<that->green_sBIT)-1));
  5149. that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
  5150. }
  5151. else
  5152. {
  5153. that->blue = that->green = that->red;
  5154. that->bluef = that->greenf = that->redf;
  5155. that->bluee = that->greene = that->rede;
  5156. }
  5157. if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
  5158. that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5159. {
  5160. that->alpha = sample_scale(that->alphaf, scale);
  5161. that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
  5162. }
  5163. else
  5164. {
  5165. that->alpha = scale; /* opaque */
  5166. that->alphaf = 1; /* Override this. */
  5167. that->alphae = 0; /* It's exact ;-) */
  5168. }
  5169. if (sig_bits && that->alpha_sBIT < that->sample_depth)
  5170. that->alpha >>= that->sample_depth - that->alpha_sBIT;
  5171. }
  5172. /* Static 'end' structure: */
  5173. static image_transform image_transform_end =
  5174. {
  5175. "(end)", /* name */
  5176. 1, /* enable */
  5177. 0, /* list */
  5178. 0, /* global_use */
  5179. 0, /* local_use */
  5180. 0, /* next */
  5181. image_transform_ini_end,
  5182. image_transform_set_end,
  5183. image_transform_mod_end,
  5184. 0 /* never called, I want it to crash if it is! */
  5185. };
  5186. /* Reader callbacks and implementations, where they differ from the standard
  5187. * ones.
  5188. */
  5189. static void
  5190. transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
  5191. const image_transform *transform_list)
  5192. {
  5193. memset(dp, 0, sizeof *dp);
  5194. /* Standard fields */
  5195. standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
  5196. pm->use_update_info);
  5197. /* Parameter fields */
  5198. dp->pm = pm;
  5199. dp->transform_list = transform_list;
  5200. dp->max_gamma_8 = 16;
  5201. /* Local variable fields */
  5202. dp->output_colour_type = 255; /* invalid */
  5203. dp->output_bit_depth = 255; /* invalid */
  5204. dp->unpacked = 0; /* not unpacked */
  5205. }
  5206. static void
  5207. transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
  5208. {
  5209. /* Reuse the standard stuff as appropriate. */
  5210. standard_info_part1(&dp->this, pp, pi);
  5211. /* Now set the list of transforms. */
  5212. dp->transform_list->set(dp->transform_list, dp, pp, pi);
  5213. /* Update the info structure for these transforms: */
  5214. {
  5215. int i = dp->this.use_update_info;
  5216. /* Always do one call, even if use_update_info is 0. */
  5217. do
  5218. png_read_update_info(pp, pi);
  5219. while (--i > 0);
  5220. }
  5221. /* And get the output information into the standard_display */
  5222. standard_info_part2(&dp->this, pp, pi, 1/*images*/);
  5223. /* Plus the extra stuff we need for the transform tests: */
  5224. dp->output_colour_type = png_get_color_type(pp, pi);
  5225. dp->output_bit_depth = png_get_bit_depth(pp, pi);
  5226. /* If png_set_filler is in action then fake the output color type to include
  5227. * an alpha channel where appropriate.
  5228. */
  5229. if (dp->output_bit_depth >= 8 &&
  5230. (dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
  5231. dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
  5232. dp->output_colour_type |= 4;
  5233. /* Validate the combination of colour type and bit depth that we are getting
  5234. * out of libpng; the semantics of something not in the PNG spec are, at
  5235. * best, unclear.
  5236. */
  5237. switch (dp->output_colour_type)
  5238. {
  5239. case PNG_COLOR_TYPE_PALETTE:
  5240. if (dp->output_bit_depth > 8) goto error;
  5241. /*FALL THROUGH*/
  5242. case PNG_COLOR_TYPE_GRAY:
  5243. if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
  5244. dp->output_bit_depth == 4)
  5245. break;
  5246. /*FALL THROUGH*/
  5247. default:
  5248. if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
  5249. break;
  5250. /*FALL THROUGH*/
  5251. error:
  5252. {
  5253. char message[128];
  5254. size_t pos;
  5255. pos = safecat(message, sizeof message, 0,
  5256. "invalid final bit depth: colour type(");
  5257. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  5258. pos = safecat(message, sizeof message, pos, ") with bit depth: ");
  5259. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5260. png_error(pp, message);
  5261. }
  5262. }
  5263. /* Use a test pixel to check that the output agrees with what we expect -
  5264. * this avoids running the whole test if the output is unexpected. This also
  5265. * checks for internal errors.
  5266. */
  5267. {
  5268. image_pixel test_pixel;
  5269. memset(&test_pixel, 0, sizeof test_pixel);
  5270. test_pixel.colour_type = dp->this.colour_type; /* input */
  5271. test_pixel.bit_depth = dp->this.bit_depth;
  5272. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
  5273. test_pixel.sample_depth = 8;
  5274. else
  5275. test_pixel.sample_depth = test_pixel.bit_depth;
  5276. /* Don't need sBIT here, but it must be set to non-zero to avoid
  5277. * arithmetic overflows.
  5278. */
  5279. test_pixel.have_tRNS = dp->this.is_transparent != 0;
  5280. test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
  5281. test_pixel.alpha_sBIT = test_pixel.sample_depth;
  5282. dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
  5283. if (test_pixel.colour_type != dp->output_colour_type)
  5284. {
  5285. char message[128];
  5286. size_t pos = safecat(message, sizeof message, 0, "colour type ");
  5287. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  5288. pos = safecat(message, sizeof message, pos, " expected ");
  5289. pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
  5290. png_error(pp, message);
  5291. }
  5292. if (test_pixel.bit_depth != dp->output_bit_depth)
  5293. {
  5294. char message[128];
  5295. size_t pos = safecat(message, sizeof message, 0, "bit depth ");
  5296. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5297. pos = safecat(message, sizeof message, pos, " expected ");
  5298. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5299. png_error(pp, message);
  5300. }
  5301. /* If both bit depth and colour type are correct check the sample depth.
  5302. */
  5303. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
  5304. test_pixel.sample_depth != 8) /* oops - internal error! */
  5305. png_error(pp, "pngvalid: internal: palette sample depth not 8");
  5306. else if (dp->unpacked && test_pixel.bit_depth != 8)
  5307. png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
  5308. else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
  5309. && test_pixel.bit_depth != test_pixel.sample_depth)
  5310. {
  5311. char message[128];
  5312. size_t pos = safecat(message, sizeof message, 0,
  5313. "internal: sample depth ");
  5314. /* Because unless something has set 'unpacked' or the image is palette
  5315. * mapped we expect the transform to keep sample depth and bit depth
  5316. * the same.
  5317. */
  5318. pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
  5319. pos = safecat(message, sizeof message, pos, " expected ");
  5320. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5321. png_error(pp, message);
  5322. }
  5323. else if (test_pixel.bit_depth != dp->output_bit_depth)
  5324. {
  5325. /* This could be a libpng error too; libpng has not produced what we
  5326. * expect for the output bit depth.
  5327. */
  5328. char message[128];
  5329. size_t pos = safecat(message, sizeof message, 0,
  5330. "internal: bit depth ");
  5331. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5332. pos = safecat(message, sizeof message, pos, " expected ");
  5333. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5334. png_error(pp, message);
  5335. }
  5336. }
  5337. }
  5338. static void PNGCBAPI
  5339. transform_info(png_structp pp, png_infop pi)
  5340. {
  5341. transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
  5342. pp, pi);
  5343. }
  5344. static void
  5345. transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
  5346. unsigned int b, unsigned int a, unsigned int in_digitized, double in,
  5347. unsigned int out, png_byte sample_depth, double err, double limit,
  5348. const char *name, double digitization_error)
  5349. {
  5350. /* Compare the scaled, digitzed, values of our local calculation (in+-err)
  5351. * with the digitized values libpng produced; 'sample_depth' is the actual
  5352. * digitization depth of the libpng output colors (the bit depth except for
  5353. * palette images where it is always 8.) The check on 'err' is to detect
  5354. * internal errors in pngvalid itself.
  5355. */
  5356. unsigned int max = (1U<<sample_depth)-1;
  5357. double in_min = ceil((in-err)*max - digitization_error);
  5358. double in_max = floor((in+err)*max + digitization_error);
  5359. if (err > limit || !(out >= in_min && out <= in_max))
  5360. {
  5361. char message[256];
  5362. size_t pos;
  5363. pos = safecat(message, sizeof message, 0, name);
  5364. pos = safecat(message, sizeof message, pos, " output value error: rgba(");
  5365. pos = safecatn(message, sizeof message, pos, r);
  5366. pos = safecat(message, sizeof message, pos, ",");
  5367. pos = safecatn(message, sizeof message, pos, g);
  5368. pos = safecat(message, sizeof message, pos, ",");
  5369. pos = safecatn(message, sizeof message, pos, b);
  5370. pos = safecat(message, sizeof message, pos, ",");
  5371. pos = safecatn(message, sizeof message, pos, a);
  5372. pos = safecat(message, sizeof message, pos, "): ");
  5373. pos = safecatn(message, sizeof message, pos, out);
  5374. pos = safecat(message, sizeof message, pos, " expected: ");
  5375. pos = safecatn(message, sizeof message, pos, in_digitized);
  5376. pos = safecat(message, sizeof message, pos, " (");
  5377. pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
  5378. pos = safecat(message, sizeof message, pos, "..");
  5379. pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
  5380. pos = safecat(message, sizeof message, pos, ")");
  5381. png_error(pp, message);
  5382. }
  5383. }
  5384. static void
  5385. transform_image_validate(transform_display *dp, png_const_structp pp,
  5386. png_infop pi)
  5387. {
  5388. /* Constants for the loop below: */
  5389. const png_store* const ps = dp->this.ps;
  5390. const png_byte in_ct = dp->this.colour_type;
  5391. const png_byte in_bd = dp->this.bit_depth;
  5392. const png_uint_32 w = dp->this.w;
  5393. const png_uint_32 h = dp->this.h;
  5394. const png_byte out_ct = dp->output_colour_type;
  5395. const png_byte out_bd = dp->output_bit_depth;
  5396. const png_byte sample_depth = (png_byte)(out_ct ==
  5397. PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
  5398. const png_byte red_sBIT = dp->this.red_sBIT;
  5399. const png_byte green_sBIT = dp->this.green_sBIT;
  5400. const png_byte blue_sBIT = dp->this.blue_sBIT;
  5401. const png_byte alpha_sBIT = dp->this.alpha_sBIT;
  5402. const int have_tRNS = dp->this.is_transparent;
  5403. double digitization_error;
  5404. store_palette out_palette;
  5405. png_uint_32 y;
  5406. UNUSED(pi)
  5407. /* Check for row overwrite errors */
  5408. store_image_check(dp->this.ps, pp, 0);
  5409. /* Read the palette corresponding to the output if the output colour type
  5410. * indicates a palette, othewise set out_palette to garbage.
  5411. */
  5412. if (out_ct == PNG_COLOR_TYPE_PALETTE)
  5413. {
  5414. /* Validate that the palette count itself has not changed - this is not
  5415. * expected.
  5416. */
  5417. int npalette = (-1);
  5418. (void)read_palette(out_palette, &npalette, pp, pi);
  5419. if (npalette != dp->this.npalette)
  5420. png_error(pp, "unexpected change in palette size");
  5421. digitization_error = .5;
  5422. }
  5423. else
  5424. {
  5425. png_byte in_sample_depth;
  5426. memset(out_palette, 0x5e, sizeof out_palette);
  5427. /* use-input-precision means assume that if the input has 8 bit (or less)
  5428. * samples and the output has 16 bit samples the calculations will be done
  5429. * with 8 bit precision, not 16.
  5430. */
  5431. if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
  5432. in_sample_depth = 8;
  5433. else
  5434. in_sample_depth = in_bd;
  5435. if (sample_depth != 16 || in_sample_depth > 8 ||
  5436. !dp->pm->calculations_use_input_precision)
  5437. digitization_error = .5;
  5438. /* Else calculations are at 8 bit precision, and the output actually
  5439. * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
  5440. */
  5441. else
  5442. digitization_error = .5 * 257;
  5443. }
  5444. for (y=0; y<h; ++y)
  5445. {
  5446. png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
  5447. png_uint_32 x;
  5448. /* The original, standard, row pre-transforms. */
  5449. png_byte std[STANDARD_ROWMAX];
  5450. transform_row(pp, std, in_ct, in_bd, y);
  5451. /* Go through each original pixel transforming it and comparing with what
  5452. * libpng did to the same pixel.
  5453. */
  5454. for (x=0; x<w; ++x)
  5455. {
  5456. image_pixel in_pixel, out_pixel;
  5457. unsigned int r, g, b, a;
  5458. /* Find out what we think the pixel should be: */
  5459. image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
  5460. NULL);
  5461. in_pixel.red_sBIT = red_sBIT;
  5462. in_pixel.green_sBIT = green_sBIT;
  5463. in_pixel.blue_sBIT = blue_sBIT;
  5464. in_pixel.alpha_sBIT = alpha_sBIT;
  5465. in_pixel.have_tRNS = have_tRNS != 0;
  5466. /* For error detection, below. */
  5467. r = in_pixel.red;
  5468. g = in_pixel.green;
  5469. b = in_pixel.blue;
  5470. a = in_pixel.alpha;
  5471. /* This applies the transforms to the input data, including output
  5472. * format operations which must be used when reading the output
  5473. * pixel that libpng produces.
  5474. */
  5475. dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
  5476. /* Read the output pixel and compare it to what we got, we don't
  5477. * use the error field here, so no need to update sBIT. in_pixel
  5478. * says whether we expect libpng to change the output format.
  5479. */
  5480. image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
  5481. &in_pixel);
  5482. /* We don't expect changes to the index here even if the bit depth is
  5483. * changed.
  5484. */
  5485. if (in_ct == PNG_COLOR_TYPE_PALETTE &&
  5486. out_ct == PNG_COLOR_TYPE_PALETTE)
  5487. {
  5488. if (in_pixel.palette_index != out_pixel.palette_index)
  5489. png_error(pp, "unexpected transformed palette index");
  5490. }
  5491. /* Check the colours for palette images too - in fact the palette could
  5492. * be separately verified itself in most cases.
  5493. */
  5494. if (in_pixel.red != out_pixel.red)
  5495. transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
  5496. out_pixel.red, sample_depth, in_pixel.rede,
  5497. dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
  5498. digitization_error);
  5499. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5500. in_pixel.green != out_pixel.green)
  5501. transform_range_check(pp, r, g, b, a, in_pixel.green,
  5502. in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
  5503. dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
  5504. digitization_error);
  5505. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5506. in_pixel.blue != out_pixel.blue)
  5507. transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
  5508. out_pixel.blue, sample_depth, in_pixel.bluee,
  5509. dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
  5510. digitization_error);
  5511. if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
  5512. in_pixel.alpha != out_pixel.alpha)
  5513. transform_range_check(pp, r, g, b, a, in_pixel.alpha,
  5514. in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
  5515. dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
  5516. digitization_error);
  5517. } /* pixel (x) loop */
  5518. } /* row (y) loop */
  5519. /* Record that something was actually checked to avoid a false positive. */
  5520. dp->this.ps->validated = 1;
  5521. }
  5522. static void PNGCBAPI
  5523. transform_end(png_structp ppIn, png_infop pi)
  5524. {
  5525. png_const_structp pp = ppIn;
  5526. transform_display *dp = voidcast(transform_display*,
  5527. png_get_progressive_ptr(pp));
  5528. if (!dp->this.speed)
  5529. transform_image_validate(dp, pp, pi);
  5530. else
  5531. dp->this.ps->validated = 1;
  5532. }
  5533. /* A single test run. */
  5534. static void
  5535. transform_test(png_modifier *pmIn, const png_uint_32 idIn,
  5536. const image_transform* transform_listIn, const char * const name)
  5537. {
  5538. transform_display d;
  5539. context(&pmIn->this, fault);
  5540. transform_display_init(&d, pmIn, idIn, transform_listIn);
  5541. Try
  5542. {
  5543. size_t pos = 0;
  5544. png_structp pp;
  5545. png_infop pi;
  5546. char full_name[256];
  5547. /* Make sure the encoding fields are correct and enter the required
  5548. * modifications.
  5549. */
  5550. transform_set_encoding(&d);
  5551. /* Add any modifications required by the transform list. */
  5552. d.transform_list->ini(d.transform_list, &d);
  5553. /* Add the color space information, if any, to the name. */
  5554. pos = safecat(full_name, sizeof full_name, pos, name);
  5555. pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
  5556. /* Get a png_struct for reading the image. */
  5557. pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
  5558. standard_palette_init(&d.this);
  5559. # if 0
  5560. /* Logging (debugging only) */
  5561. {
  5562. char buffer[256];
  5563. (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
  5564. "running test");
  5565. fprintf(stderr, "%s\n", buffer);
  5566. }
  5567. # endif
  5568. /* Introduce the correct read function. */
  5569. if (d.pm->this.progressive)
  5570. {
  5571. /* Share the row function with the standard implementation. */
  5572. png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
  5573. transform_end);
  5574. /* Now feed data into the reader until we reach the end: */
  5575. modifier_progressive_read(d.pm, pp, pi);
  5576. }
  5577. else
  5578. {
  5579. /* modifier_read expects a png_modifier* */
  5580. png_set_read_fn(pp, d.pm, modifier_read);
  5581. /* Check the header values: */
  5582. png_read_info(pp, pi);
  5583. /* Process the 'info' requirements. Only one image is generated */
  5584. transform_info_imp(&d, pp, pi);
  5585. sequential_row(&d.this, pp, pi, -1, 0);
  5586. if (!d.this.speed)
  5587. transform_image_validate(&d, pp, pi);
  5588. else
  5589. d.this.ps->validated = 1;
  5590. }
  5591. modifier_reset(d.pm);
  5592. }
  5593. Catch(fault)
  5594. {
  5595. modifier_reset(voidcast(png_modifier*,(void*)fault));
  5596. }
  5597. }
  5598. /* The transforms: */
  5599. #define ITSTRUCT(name) image_transform_##name
  5600. #define ITDATA(name) image_transform_data_##name
  5601. #define image_transform_ini image_transform_default_ini
  5602. #define IT(name)\
  5603. static image_transform ITSTRUCT(name) =\
  5604. {\
  5605. #name,\
  5606. 1, /*enable*/\
  5607. &PT, /*list*/\
  5608. 0, /*global_use*/\
  5609. 0, /*local_use*/\
  5610. 0, /*next*/\
  5611. image_transform_ini,\
  5612. image_transform_png_set_##name##_set,\
  5613. image_transform_png_set_##name##_mod,\
  5614. image_transform_png_set_##name##_add\
  5615. }
  5616. #define PT ITSTRUCT(end) /* stores the previous transform */
  5617. /* To save code: */
  5618. extern void image_transform_default_ini(const image_transform *this,
  5619. transform_display *that); /* silence GCC warnings */
  5620. void /* private, but almost always needed */
  5621. image_transform_default_ini(const image_transform *this,
  5622. transform_display *that)
  5623. {
  5624. this->next->ini(this->next, that);
  5625. }
  5626. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  5627. static int
  5628. image_transform_default_add(image_transform *this,
  5629. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5630. {
  5631. UNUSED(colour_type)
  5632. UNUSED(bit_depth)
  5633. this->next = *that;
  5634. *that = this;
  5635. return 1;
  5636. }
  5637. #endif
  5638. #ifdef PNG_READ_EXPAND_SUPPORTED
  5639. /* png_set_palette_to_rgb */
  5640. static void
  5641. image_transform_png_set_palette_to_rgb_set(const image_transform *this,
  5642. transform_display *that, png_structp pp, png_infop pi)
  5643. {
  5644. png_set_palette_to_rgb(pp);
  5645. this->next->set(this->next, that, pp, pi);
  5646. }
  5647. static void
  5648. image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
  5649. image_pixel *that, png_const_structp pp,
  5650. const transform_display *display)
  5651. {
  5652. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5653. image_pixel_convert_PLTE(that);
  5654. this->next->mod(this->next, that, pp, display);
  5655. }
  5656. static int
  5657. image_transform_png_set_palette_to_rgb_add(image_transform *this,
  5658. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5659. {
  5660. UNUSED(bit_depth)
  5661. this->next = *that;
  5662. *that = this;
  5663. return colour_type == PNG_COLOR_TYPE_PALETTE;
  5664. }
  5665. IT(palette_to_rgb);
  5666. #undef PT
  5667. #define PT ITSTRUCT(palette_to_rgb)
  5668. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5669. #ifdef PNG_READ_EXPAND_SUPPORTED
  5670. /* png_set_tRNS_to_alpha */
  5671. static void
  5672. image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
  5673. transform_display *that, png_structp pp, png_infop pi)
  5674. {
  5675. png_set_tRNS_to_alpha(pp);
  5676. /* If there was a tRNS chunk that would get expanded and add an alpha
  5677. * channel is_transparent must be updated:
  5678. */
  5679. if (that->this.has_tRNS)
  5680. that->this.is_transparent = 1;
  5681. this->next->set(this->next, that, pp, pi);
  5682. }
  5683. static void
  5684. image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
  5685. image_pixel *that, png_const_structp pp,
  5686. const transform_display *display)
  5687. {
  5688. #if PNG_LIBPNG_VER < 10700
  5689. /* LIBPNG BUG: this always forces palette images to RGB. */
  5690. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5691. image_pixel_convert_PLTE(that);
  5692. #endif
  5693. /* This effectively does an 'expand' only if there is some transparency to
  5694. * convert to an alpha channel.
  5695. */
  5696. if (that->have_tRNS)
  5697. # if PNG_LIBPNG_VER >= 10700
  5698. if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
  5699. (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
  5700. # endif
  5701. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  5702. #if PNG_LIBPNG_VER < 10700
  5703. /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
  5704. else
  5705. {
  5706. if (that->bit_depth < 8)
  5707. that->bit_depth =8;
  5708. if (that->sample_depth < 8)
  5709. that->sample_depth = 8;
  5710. }
  5711. #endif
  5712. this->next->mod(this->next, that, pp, display);
  5713. }
  5714. static int
  5715. image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
  5716. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5717. {
  5718. UNUSED(bit_depth)
  5719. this->next = *that;
  5720. *that = this;
  5721. /* We don't know yet whether there will be a tRNS chunk, but we know that
  5722. * this transformation should do nothing if there already is an alpha
  5723. * channel. In addition, after the bug fix in 1.7.0, there is no longer
  5724. * any action on a palette image.
  5725. */
  5726. return
  5727. # if PNG_LIBPNG_VER >= 10700
  5728. colour_type != PNG_COLOR_TYPE_PALETTE &&
  5729. # endif
  5730. (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  5731. }
  5732. IT(tRNS_to_alpha);
  5733. #undef PT
  5734. #define PT ITSTRUCT(tRNS_to_alpha)
  5735. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5736. #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
  5737. /* png_set_gray_to_rgb */
  5738. static void
  5739. image_transform_png_set_gray_to_rgb_set(const image_transform *this,
  5740. transform_display *that, png_structp pp, png_infop pi)
  5741. {
  5742. png_set_gray_to_rgb(pp);
  5743. /* NOTE: this doesn't result in tRNS expansion. */
  5744. this->next->set(this->next, that, pp, pi);
  5745. }
  5746. static void
  5747. image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
  5748. image_pixel *that, png_const_structp pp,
  5749. const transform_display *display)
  5750. {
  5751. /* NOTE: we can actually pend the tRNS processing at this point because we
  5752. * can correctly recognize the original pixel value even though we have
  5753. * mapped the one gray channel to the three RGB ones, but in fact libpng
  5754. * doesn't do this, so we don't either.
  5755. */
  5756. if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
  5757. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  5758. /* Simply expand the bit depth and alter the colour type as required. */
  5759. if (that->colour_type == PNG_COLOR_TYPE_GRAY)
  5760. {
  5761. /* RGB images have a bit depth at least equal to '8' */
  5762. if (that->bit_depth < 8)
  5763. that->sample_depth = that->bit_depth = 8;
  5764. /* And just changing the colour type works here because the green and blue
  5765. * channels are being maintained in lock-step with the red/gray:
  5766. */
  5767. that->colour_type = PNG_COLOR_TYPE_RGB;
  5768. }
  5769. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  5770. that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  5771. this->next->mod(this->next, that, pp, display);
  5772. }
  5773. static int
  5774. image_transform_png_set_gray_to_rgb_add(image_transform *this,
  5775. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5776. {
  5777. UNUSED(bit_depth)
  5778. this->next = *that;
  5779. *that = this;
  5780. return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
  5781. }
  5782. IT(gray_to_rgb);
  5783. #undef PT
  5784. #define PT ITSTRUCT(gray_to_rgb)
  5785. #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
  5786. #ifdef PNG_READ_EXPAND_SUPPORTED
  5787. /* png_set_expand */
  5788. static void
  5789. image_transform_png_set_expand_set(const image_transform *this,
  5790. transform_display *that, png_structp pp, png_infop pi)
  5791. {
  5792. png_set_expand(pp);
  5793. if (that->this.has_tRNS)
  5794. that->this.is_transparent = 1;
  5795. this->next->set(this->next, that, pp, pi);
  5796. }
  5797. static void
  5798. image_transform_png_set_expand_mod(const image_transform *this,
  5799. image_pixel *that, png_const_structp pp,
  5800. const transform_display *display)
  5801. {
  5802. /* The general expand case depends on what the colour type is: */
  5803. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5804. image_pixel_convert_PLTE(that);
  5805. else if (that->bit_depth < 8) /* grayscale */
  5806. that->sample_depth = that->bit_depth = 8;
  5807. if (that->have_tRNS)
  5808. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  5809. this->next->mod(this->next, that, pp, display);
  5810. }
  5811. static int
  5812. image_transform_png_set_expand_add(image_transform *this,
  5813. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5814. {
  5815. UNUSED(bit_depth)
  5816. this->next = *that;
  5817. *that = this;
  5818. /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
  5819. * depth is at least 8 already.
  5820. */
  5821. return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  5822. }
  5823. IT(expand);
  5824. #undef PT
  5825. #define PT ITSTRUCT(expand)
  5826. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5827. #ifdef PNG_READ_EXPAND_SUPPORTED
  5828. /* png_set_expand_gray_1_2_4_to_8
  5829. * Pre 1.7.0 LIBPNG BUG: this just does an 'expand'
  5830. */
  5831. static void
  5832. image_transform_png_set_expand_gray_1_2_4_to_8_set(
  5833. const image_transform *this, transform_display *that, png_structp pp,
  5834. png_infop pi)
  5835. {
  5836. png_set_expand_gray_1_2_4_to_8(pp);
  5837. /* NOTE: don't expect this to expand tRNS */
  5838. this->next->set(this->next, that, pp, pi);
  5839. }
  5840. static void
  5841. image_transform_png_set_expand_gray_1_2_4_to_8_mod(
  5842. const image_transform *this, image_pixel *that, png_const_structp pp,
  5843. const transform_display *display)
  5844. {
  5845. #if PNG_LIBPNG_VER < 10700
  5846. image_transform_png_set_expand_mod(this, that, pp, display);
  5847. #else
  5848. /* Only expand grayscale of bit depth less than 8: */
  5849. if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
  5850. that->bit_depth < 8)
  5851. that->sample_depth = that->bit_depth = 8;
  5852. this->next->mod(this->next, that, pp, display);
  5853. #endif /* 1.7 or later */
  5854. }
  5855. static int
  5856. image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
  5857. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5858. {
  5859. #if PNG_LIBPNG_VER < 10700
  5860. return image_transform_png_set_expand_add(this, that, colour_type,
  5861. bit_depth);
  5862. #else
  5863. UNUSED(bit_depth)
  5864. this->next = *that;
  5865. *that = this;
  5866. /* This should do nothing unless the color type is gray and the bit depth is
  5867. * less than 8:
  5868. */
  5869. return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
  5870. #endif /* 1.7 or later */
  5871. }
  5872. IT(expand_gray_1_2_4_to_8);
  5873. #undef PT
  5874. #define PT ITSTRUCT(expand_gray_1_2_4_to_8)
  5875. #endif /* PNG_READ_EXPAND_SUPPORTED */
  5876. #ifdef PNG_READ_EXPAND_16_SUPPORTED
  5877. /* png_set_expand_16 */
  5878. static void
  5879. image_transform_png_set_expand_16_set(const image_transform *this,
  5880. transform_display *that, png_structp pp, png_infop pi)
  5881. {
  5882. png_set_expand_16(pp);
  5883. /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
  5884. # if PNG_LIBPNG_VER < 10700
  5885. if (that->this.has_tRNS)
  5886. that->this.is_transparent = 1;
  5887. # endif
  5888. this->next->set(this->next, that, pp, pi);
  5889. }
  5890. static void
  5891. image_transform_png_set_expand_16_mod(const image_transform *this,
  5892. image_pixel *that, png_const_structp pp,
  5893. const transform_display *display)
  5894. {
  5895. /* Expect expand_16 to expand everything to 16 bits as a result of also
  5896. * causing 'expand' to happen.
  5897. */
  5898. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5899. image_pixel_convert_PLTE(that);
  5900. if (that->have_tRNS)
  5901. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  5902. if (that->bit_depth < 16)
  5903. that->sample_depth = that->bit_depth = 16;
  5904. this->next->mod(this->next, that, pp, display);
  5905. }
  5906. static int
  5907. image_transform_png_set_expand_16_add(image_transform *this,
  5908. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5909. {
  5910. UNUSED(colour_type)
  5911. this->next = *that;
  5912. *that = this;
  5913. /* expand_16 does something unless the bit depth is already 16. */
  5914. return bit_depth < 16;
  5915. }
  5916. IT(expand_16);
  5917. #undef PT
  5918. #define PT ITSTRUCT(expand_16)
  5919. #endif /* PNG_READ_EXPAND_16_SUPPORTED */
  5920. #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */
  5921. /* png_set_scale_16 */
  5922. static void
  5923. image_transform_png_set_scale_16_set(const image_transform *this,
  5924. transform_display *that, png_structp pp, png_infop pi)
  5925. {
  5926. png_set_scale_16(pp);
  5927. # if PNG_LIBPNG_VER < 10700
  5928. /* libpng will limit the gamma table size: */
  5929. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  5930. # endif
  5931. this->next->set(this->next, that, pp, pi);
  5932. }
  5933. static void
  5934. image_transform_png_set_scale_16_mod(const image_transform *this,
  5935. image_pixel *that, png_const_structp pp,
  5936. const transform_display *display)
  5937. {
  5938. if (that->bit_depth == 16)
  5939. {
  5940. that->sample_depth = that->bit_depth = 8;
  5941. if (that->red_sBIT > 8) that->red_sBIT = 8;
  5942. if (that->green_sBIT > 8) that->green_sBIT = 8;
  5943. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  5944. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  5945. }
  5946. this->next->mod(this->next, that, pp, display);
  5947. }
  5948. static int
  5949. image_transform_png_set_scale_16_add(image_transform *this,
  5950. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  5951. {
  5952. UNUSED(colour_type)
  5953. this->next = *that;
  5954. *that = this;
  5955. return bit_depth > 8;
  5956. }
  5957. IT(scale_16);
  5958. #undef PT
  5959. #define PT ITSTRUCT(scale_16)
  5960. #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
  5961. #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
  5962. /* png_set_strip_16 */
  5963. static void
  5964. image_transform_png_set_strip_16_set(const image_transform *this,
  5965. transform_display *that, png_structp pp, png_infop pi)
  5966. {
  5967. png_set_strip_16(pp);
  5968. # if PNG_LIBPNG_VER < 10700
  5969. /* libpng will limit the gamma table size: */
  5970. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  5971. # endif
  5972. this->next->set(this->next, that, pp, pi);
  5973. }
  5974. static void
  5975. image_transform_png_set_strip_16_mod(const image_transform *this,
  5976. image_pixel *that, png_const_structp pp,
  5977. const transform_display *display)
  5978. {
  5979. if (that->bit_depth == 16)
  5980. {
  5981. that->sample_depth = that->bit_depth = 8;
  5982. if (that->red_sBIT > 8) that->red_sBIT = 8;
  5983. if (that->green_sBIT > 8) that->green_sBIT = 8;
  5984. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  5985. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  5986. /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
  5987. * configuration option is set. From 1.5.4 the flag is never set and the
  5988. * 'scale' API (above) must be used.
  5989. */
  5990. # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
  5991. # if PNG_LIBPNG_VER >= 10504
  5992. # error PNG_READ_ACCURATE_SCALE should not be set
  5993. # endif
  5994. /* The strip 16 algorithm drops the low 8 bits rather than calculating
  5995. * 1/257, so we need to adjust the permitted errors appropriately:
  5996. * Notice that this is only relevant prior to the addition of the
  5997. * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
  5998. */
  5999. {
  6000. const double d = (255-128.5)/65535;
  6001. that->rede += d;
  6002. that->greene += d;
  6003. that->bluee += d;
  6004. that->alphae += d;
  6005. }
  6006. # endif
  6007. }
  6008. this->next->mod(this->next, that, pp, display);
  6009. }
  6010. static int
  6011. image_transform_png_set_strip_16_add(image_transform *this,
  6012. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6013. {
  6014. UNUSED(colour_type)
  6015. this->next = *that;
  6016. *that = this;
  6017. return bit_depth > 8;
  6018. }
  6019. IT(strip_16);
  6020. #undef PT
  6021. #define PT ITSTRUCT(strip_16)
  6022. #endif /* PNG_READ_16_TO_8_SUPPORTED */
  6023. #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
  6024. /* png_set_strip_alpha */
  6025. static void
  6026. image_transform_png_set_strip_alpha_set(const image_transform *this,
  6027. transform_display *that, png_structp pp, png_infop pi)
  6028. {
  6029. png_set_strip_alpha(pp);
  6030. this->next->set(this->next, that, pp, pi);
  6031. }
  6032. static void
  6033. image_transform_png_set_strip_alpha_mod(const image_transform *this,
  6034. image_pixel *that, png_const_structp pp,
  6035. const transform_display *display)
  6036. {
  6037. if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  6038. that->colour_type = PNG_COLOR_TYPE_GRAY;
  6039. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  6040. that->colour_type = PNG_COLOR_TYPE_RGB;
  6041. that->have_tRNS = 0;
  6042. that->alphaf = 1;
  6043. this->next->mod(this->next, that, pp, display);
  6044. }
  6045. static int
  6046. image_transform_png_set_strip_alpha_add(image_transform *this,
  6047. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6048. {
  6049. UNUSED(bit_depth)
  6050. this->next = *that;
  6051. *that = this;
  6052. return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
  6053. }
  6054. IT(strip_alpha);
  6055. #undef PT
  6056. #define PT ITSTRUCT(strip_alpha)
  6057. #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
  6058. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  6059. /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
  6060. * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
  6061. * png_fixed_point green)
  6062. * png_get_rgb_to_gray_status
  6063. *
  6064. * The 'default' test here uses values known to be used inside libpng prior to
  6065. * 1.7.0:
  6066. *
  6067. * red: 6968
  6068. * green: 23434
  6069. * blue: 2366
  6070. *
  6071. * These values are being retained for compatibility, along with the somewhat
  6072. * broken truncation calculation in the fast-and-inaccurate code path. Older
  6073. * versions of libpng will fail the accuracy tests below because they use the
  6074. * truncation algorithm everywhere.
  6075. */
  6076. #define data ITDATA(rgb_to_gray)
  6077. static struct
  6078. {
  6079. double gamma; /* File gamma to use in processing */
  6080. /* The following are the parameters for png_set_rgb_to_gray: */
  6081. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6082. double red_to_set;
  6083. double green_to_set;
  6084. # else
  6085. png_fixed_point red_to_set;
  6086. png_fixed_point green_to_set;
  6087. # endif
  6088. /* The actual coefficients: */
  6089. double red_coefficient;
  6090. double green_coefficient;
  6091. double blue_coefficient;
  6092. /* Set if the coeefficients have been overridden. */
  6093. int coefficients_overridden;
  6094. } data;
  6095. #undef image_transform_ini
  6096. #define image_transform_ini image_transform_png_set_rgb_to_gray_ini
  6097. static void
  6098. image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
  6099. transform_display *that)
  6100. {
  6101. png_modifier *pm = that->pm;
  6102. const color_encoding *e = pm->current_encoding;
  6103. UNUSED(this)
  6104. /* Since we check the encoding this flag must be set: */
  6105. pm->test_uses_encoding = 1;
  6106. /* If 'e' is not NULL chromaticity information is present and either a cHRM
  6107. * or an sRGB chunk will be inserted.
  6108. */
  6109. if (e != 0)
  6110. {
  6111. /* Coefficients come from the encoding, but may need to be normalized to a
  6112. * white point Y of 1.0
  6113. */
  6114. const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
  6115. data.red_coefficient = e->red.Y;
  6116. data.green_coefficient = e->green.Y;
  6117. data.blue_coefficient = e->blue.Y;
  6118. if (whiteY != 1)
  6119. {
  6120. data.red_coefficient /= whiteY;
  6121. data.green_coefficient /= whiteY;
  6122. data.blue_coefficient /= whiteY;
  6123. }
  6124. }
  6125. else
  6126. {
  6127. /* The default (built in) coeffcients, as above: */
  6128. # if PNG_LIBPNG_VER < 10700
  6129. data.red_coefficient = 6968 / 32768.;
  6130. data.green_coefficient = 23434 / 32768.;
  6131. data.blue_coefficient = 2366 / 32768.;
  6132. # else
  6133. data.red_coefficient = .2126;
  6134. data.green_coefficient = .7152;
  6135. data.blue_coefficient = .0722;
  6136. # endif
  6137. }
  6138. data.gamma = pm->current_gamma;
  6139. /* If not set then the calculations assume linear encoding (implicitly): */
  6140. if (data.gamma == 0)
  6141. data.gamma = 1;
  6142. /* The arguments to png_set_rgb_to_gray can override the coefficients implied
  6143. * by the color space encoding. If doing exhaustive checks do the override
  6144. * in each case, otherwise do it randomly.
  6145. */
  6146. if (pm->test_exhaustive)
  6147. {
  6148. /* First time in coefficients_overridden is 0, the following sets it to 1,
  6149. * so repeat if it is set. If a test fails this may mean we subsequently
  6150. * skip a non-override test, ignore that.
  6151. */
  6152. data.coefficients_overridden = !data.coefficients_overridden;
  6153. pm->repeat = data.coefficients_overridden != 0;
  6154. }
  6155. else
  6156. data.coefficients_overridden = random_choice();
  6157. if (data.coefficients_overridden)
  6158. {
  6159. /* These values override the color encoding defaults, simply use random
  6160. * numbers.
  6161. */
  6162. png_uint_32 ru;
  6163. double total;
  6164. RANDOMIZE(ru);
  6165. data.green_coefficient = total = (ru & 0xffff) / 65535.;
  6166. ru >>= 16;
  6167. data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
  6168. total += data.red_coefficient;
  6169. data.blue_coefficient = 1 - total;
  6170. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6171. data.red_to_set = data.red_coefficient;
  6172. data.green_to_set = data.green_coefficient;
  6173. # else
  6174. data.red_to_set = fix(data.red_coefficient);
  6175. data.green_to_set = fix(data.green_coefficient);
  6176. # endif
  6177. /* The following just changes the error messages: */
  6178. pm->encoding_ignored = 1;
  6179. }
  6180. else
  6181. {
  6182. data.red_to_set = -1;
  6183. data.green_to_set = -1;
  6184. }
  6185. /* Adjust the error limit in the png_modifier because of the larger errors
  6186. * produced in the digitization during the gamma handling.
  6187. */
  6188. if (data.gamma != 1) /* Use gamma tables */
  6189. {
  6190. if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
  6191. {
  6192. /* The computations have the form:
  6193. *
  6194. * r * rc + g * gc + b * bc
  6195. *
  6196. * Each component of which is +/-1/65535 from the gamma_to_1 table
  6197. * lookup, resulting in a base error of +/-6. The gamma_from_1
  6198. * conversion adds another +/-2 in the 16-bit case and
  6199. * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
  6200. */
  6201. # if PNG_LIBPNG_VER < 10700
  6202. if (that->this.bit_depth < 16)
  6203. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  6204. # endif
  6205. that->pm->limit += pow(
  6206. (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
  6207. 8. :
  6208. 6. + (1<<(15-that->max_gamma_8))
  6209. )/65535, data.gamma);
  6210. }
  6211. else
  6212. {
  6213. /* Rounding to 8 bits in the linear space causes massive errors which
  6214. * will trigger the error check in transform_range_check. Fix that
  6215. * here by taking the gamma encoding into account.
  6216. *
  6217. * When DIGITIZE is set because a pre-1.7 version of libpng is being
  6218. * tested allow a bigger slack.
  6219. *
  6220. * NOTE: this magic number was determined by experiment to be about
  6221. * 1.263. There's no great merit to the value below, however it only
  6222. * affects the limit used for checking for internal calculation errors,
  6223. * not the actual limit imposed by pngvalid on the output errors.
  6224. */
  6225. that->pm->limit += pow(
  6226. # if DIGITIZE
  6227. 1.3
  6228. # else
  6229. 1.0
  6230. # endif
  6231. /255, data.gamma);
  6232. }
  6233. }
  6234. else
  6235. {
  6236. /* With no gamma correction a large error comes from the truncation of the
  6237. * calculation in the 8 bit case, allow for that here.
  6238. */
  6239. if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
  6240. that->pm->limit += 4E-3;
  6241. }
  6242. }
  6243. static void
  6244. image_transform_png_set_rgb_to_gray_set(const image_transform *this,
  6245. transform_display *that, png_structp pp, png_infop pi)
  6246. {
  6247. const int error_action = 1; /* no error, no defines in png.h */
  6248. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6249. png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
  6250. # else
  6251. png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
  6252. data.green_to_set);
  6253. # endif
  6254. # ifdef PNG_READ_cHRM_SUPPORTED
  6255. if (that->pm->current_encoding != 0)
  6256. {
  6257. /* We have an encoding so a cHRM chunk may have been set; if so then
  6258. * check that the libpng APIs give the correct (X,Y,Z) values within
  6259. * some margin of error for the round trip through the chromaticity
  6260. * form.
  6261. */
  6262. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6263. # define API_function png_get_cHRM_XYZ
  6264. # define API_form "FP"
  6265. # define API_type double
  6266. # define API_cvt(x) (x)
  6267. # else
  6268. # define API_function png_get_cHRM_XYZ_fixed
  6269. # define API_form "fixed"
  6270. # define API_type png_fixed_point
  6271. # define API_cvt(x) ((double)(x)/PNG_FP_1)
  6272. # endif
  6273. API_type rX, gX, bX;
  6274. API_type rY, gY, bY;
  6275. API_type rZ, gZ, bZ;
  6276. if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
  6277. & PNG_INFO_cHRM) != 0)
  6278. {
  6279. double maxe;
  6280. const char *el;
  6281. color_encoding e, o;
  6282. /* Expect libpng to return a normalized result, but the original
  6283. * color space encoding may not be normalized.
  6284. */
  6285. modifier_current_encoding(that->pm, &o);
  6286. normalize_color_encoding(&o);
  6287. /* Sanity check the pngvalid code - the coefficients should match
  6288. * the normalized Y values of the encoding unless they were
  6289. * overridden.
  6290. */
  6291. if (data.red_to_set == -1 && data.green_to_set == -1 &&
  6292. (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
  6293. fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
  6294. fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
  6295. png_error(pp, "internal pngvalid cHRM coefficient error");
  6296. /* Generate a colour space encoding. */
  6297. e.gamma = o.gamma; /* not used */
  6298. e.red.X = API_cvt(rX);
  6299. e.red.Y = API_cvt(rY);
  6300. e.red.Z = API_cvt(rZ);
  6301. e.green.X = API_cvt(gX);
  6302. e.green.Y = API_cvt(gY);
  6303. e.green.Z = API_cvt(gZ);
  6304. e.blue.X = API_cvt(bX);
  6305. e.blue.Y = API_cvt(bY);
  6306. e.blue.Z = API_cvt(bZ);
  6307. /* This should match the original one from the png_modifier, within
  6308. * the range permitted by the libpng fixed point representation.
  6309. */
  6310. maxe = 0;
  6311. el = "-"; /* Set to element name with error */
  6312. # define CHECK(col,x)\
  6313. {\
  6314. double err = fabs(o.col.x - e.col.x);\
  6315. if (err > maxe)\
  6316. {\
  6317. maxe = err;\
  6318. el = #col "(" #x ")";\
  6319. }\
  6320. }
  6321. CHECK(red,X)
  6322. CHECK(red,Y)
  6323. CHECK(red,Z)
  6324. CHECK(green,X)
  6325. CHECK(green,Y)
  6326. CHECK(green,Z)
  6327. CHECK(blue,X)
  6328. CHECK(blue,Y)
  6329. CHECK(blue,Z)
  6330. /* Here in both fixed and floating cases to check the values read
  6331. * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
  6332. * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
  6333. */
  6334. if (maxe >= 1E-5)
  6335. {
  6336. size_t pos = 0;
  6337. char buffer[256];
  6338. pos = safecat(buffer, sizeof buffer, pos, API_form);
  6339. pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
  6340. pos = safecat(buffer, sizeof buffer, pos, el);
  6341. pos = safecat(buffer, sizeof buffer, pos, " error: ");
  6342. pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
  6343. pos = safecat(buffer, sizeof buffer, pos, " ");
  6344. /* Print the color space without the gamma value: */
  6345. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
  6346. pos = safecat(buffer, sizeof buffer, pos, " -> ");
  6347. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
  6348. png_error(pp, buffer);
  6349. }
  6350. }
  6351. }
  6352. # endif /* READ_cHRM */
  6353. this->next->set(this->next, that, pp, pi);
  6354. }
  6355. static void
  6356. image_transform_png_set_rgb_to_gray_mod(const image_transform *this,
  6357. image_pixel *that, png_const_structp pp,
  6358. const transform_display *display)
  6359. {
  6360. if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
  6361. {
  6362. double gray, err;
  6363. # if PNG_LIBPNG_VER < 10700
  6364. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6365. image_pixel_convert_PLTE(that);
  6366. # endif
  6367. /* Image now has RGB channels... */
  6368. # if DIGITIZE
  6369. {
  6370. const png_modifier *pm = display->pm;
  6371. const unsigned int sample_depth = that->sample_depth;
  6372. const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
  6373. sample_depth);
  6374. const unsigned int gamma_depth =
  6375. (sample_depth == 16 ?
  6376. display->max_gamma_8 :
  6377. (pm->assume_16_bit_calculations ?
  6378. display->max_gamma_8 :
  6379. sample_depth));
  6380. int isgray;
  6381. double r, g, b;
  6382. double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
  6383. /* Do this using interval arithmetic, otherwise it is too difficult to
  6384. * handle the errors correctly.
  6385. *
  6386. * To handle the gamma correction work out the upper and lower bounds
  6387. * of the digitized value. Assume rounding here - normally the values
  6388. * will be identical after this operation if there is only one
  6389. * transform, feel free to delete the png_error checks on this below in
  6390. * the future (this is just me trying to ensure it works!)
  6391. *
  6392. * Interval arithmetic is exact, but to implement it it must be
  6393. * possible to control the floating point implementation rounding mode.
  6394. * This cannot be done in ANSI-C, so instead I reduce the 'lo' values
  6395. * by DBL_EPSILON and increase the 'hi' values by the same.
  6396. */
  6397. # define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON))
  6398. # define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON))
  6399. r = rlo = rhi = that->redf;
  6400. rlo -= that->rede;
  6401. rlo = DD(rlo, calc_depth, 1/*round*/);
  6402. rhi += that->rede;
  6403. rhi = DU(rhi, calc_depth, 1/*round*/);
  6404. g = glo = ghi = that->greenf;
  6405. glo -= that->greene;
  6406. glo = DD(glo, calc_depth, 1/*round*/);
  6407. ghi += that->greene;
  6408. ghi = DU(ghi, calc_depth, 1/*round*/);
  6409. b = blo = bhi = that->bluef;
  6410. blo -= that->bluee;
  6411. blo = DD(blo, calc_depth, 1/*round*/);
  6412. bhi += that->bluee;
  6413. bhi = DU(bhi, calc_depth, 1/*round*/);
  6414. isgray = r==g && g==b;
  6415. if (data.gamma != 1)
  6416. {
  6417. const double power = 1/data.gamma;
  6418. const double abse = .5/(sample_depth == 16 ? 65535 : 255);
  6419. /* If a gamma calculation is done it is done using lookup tables of
  6420. * precision gamma_depth, so the already digitized value above may
  6421. * need to be further digitized here.
  6422. */
  6423. if (gamma_depth != calc_depth)
  6424. {
  6425. rlo = DD(rlo, gamma_depth, 0/*truncate*/);
  6426. rhi = DU(rhi, gamma_depth, 0/*truncate*/);
  6427. glo = DD(glo, gamma_depth, 0/*truncate*/);
  6428. ghi = DU(ghi, gamma_depth, 0/*truncate*/);
  6429. blo = DD(blo, gamma_depth, 0/*truncate*/);
  6430. bhi = DU(bhi, gamma_depth, 0/*truncate*/);
  6431. }
  6432. /* 'abse' is the error in the gamma table calculation itself. */
  6433. r = pow(r, power);
  6434. rlo = DD(pow(rlo, power)-abse, calc_depth, 1);
  6435. rhi = DU(pow(rhi, power)+abse, calc_depth, 1);
  6436. g = pow(g, power);
  6437. glo = DD(pow(glo, power)-abse, calc_depth, 1);
  6438. ghi = DU(pow(ghi, power)+abse, calc_depth, 1);
  6439. b = pow(b, power);
  6440. blo = DD(pow(blo, power)-abse, calc_depth, 1);
  6441. bhi = DU(pow(bhi, power)+abse, calc_depth, 1);
  6442. }
  6443. /* Now calculate the actual gray values. Although the error in the
  6444. * coefficients depends on whether they were specified on the command
  6445. * line (in which case truncation to 15 bits happened) or not (rounding
  6446. * was used) the maxium error in an individual coefficient is always
  6447. * 2/32768, because even in the rounding case the requirement that
  6448. * coefficients add up to 32768 can cause a larger rounding error.
  6449. *
  6450. * The only time when rounding doesn't occur in 1.5.5 and later is when
  6451. * the non-gamma code path is used for less than 16 bit data.
  6452. */
  6453. gray = r * data.red_coefficient + g * data.green_coefficient +
  6454. b * data.blue_coefficient;
  6455. {
  6456. const int do_round = data.gamma != 1 || calc_depth == 16;
  6457. const double ce = 2. / 32768;
  6458. graylo = DD(rlo * (data.red_coefficient-ce) +
  6459. glo * (data.green_coefficient-ce) +
  6460. blo * (data.blue_coefficient-ce), calc_depth, do_round);
  6461. if (graylo > gray) /* always accept the right answer */
  6462. graylo = gray;
  6463. grayhi = DU(rhi * (data.red_coefficient+ce) +
  6464. ghi * (data.green_coefficient+ce) +
  6465. bhi * (data.blue_coefficient+ce), calc_depth, do_round);
  6466. if (grayhi < gray)
  6467. grayhi = gray;
  6468. }
  6469. /* And invert the gamma. */
  6470. if (data.gamma != 1)
  6471. {
  6472. const double power = data.gamma;
  6473. /* And this happens yet again, shifting the values once more. */
  6474. if (gamma_depth != sample_depth)
  6475. {
  6476. rlo = DD(rlo, gamma_depth, 0/*truncate*/);
  6477. rhi = DU(rhi, gamma_depth, 0/*truncate*/);
  6478. glo = DD(glo, gamma_depth, 0/*truncate*/);
  6479. ghi = DU(ghi, gamma_depth, 0/*truncate*/);
  6480. blo = DD(blo, gamma_depth, 0/*truncate*/);
  6481. bhi = DU(bhi, gamma_depth, 0/*truncate*/);
  6482. }
  6483. gray = pow(gray, power);
  6484. graylo = DD(pow(graylo, power), sample_depth, 1);
  6485. grayhi = DU(pow(grayhi, power), sample_depth, 1);
  6486. }
  6487. # undef DD
  6488. # undef DU
  6489. /* Now the error can be calculated.
  6490. *
  6491. * If r==g==b because there is no overall gamma correction libpng
  6492. * currently preserves the original value.
  6493. */
  6494. if (isgray)
  6495. err = (that->rede + that->greene + that->bluee)/3;
  6496. else
  6497. {
  6498. err = fabs(grayhi-gray);
  6499. if (fabs(gray - graylo) > err)
  6500. err = fabs(graylo-gray);
  6501. /* Check that this worked: */
  6502. if (err > pm->limit)
  6503. {
  6504. size_t pos = 0;
  6505. char buffer[128];
  6506. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  6507. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  6508. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  6509. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  6510. png_error(pp, buffer);
  6511. }
  6512. }
  6513. }
  6514. # else /* DIGITIZE */
  6515. {
  6516. double r = that->redf;
  6517. double re = that->rede;
  6518. double g = that->greenf;
  6519. double ge = that->greene;
  6520. double b = that->bluef;
  6521. double be = that->bluee;
  6522. # if PNG_LIBPNG_VER < 10700
  6523. /* The true gray case involves no math in earlier versions (not
  6524. * true, there was some if gamma correction was happening too.)
  6525. */
  6526. if (r == g && r == b)
  6527. {
  6528. gray = r;
  6529. err = re;
  6530. if (err < ge) err = ge;
  6531. if (err < be) err = be;
  6532. }
  6533. else
  6534. # endif /* before 1.7 */
  6535. if (data.gamma == 1)
  6536. {
  6537. /* There is no need to do the conversions to and from linear space,
  6538. * so the calculation should be a lot more accurate. There is a
  6539. * built in error in the coefficients because they only have 15 bits
  6540. * and are adjusted to make sure they add up to 32768. This
  6541. * involves a integer calculation with truncation of the form:
  6542. *
  6543. * ((int)(coefficient * 100000) * 32768)/100000
  6544. *
  6545. * This is done to the red and green coefficients (the ones
  6546. * provided to the API) then blue is calculated from them so the
  6547. * result adds up to 32768. In the worst case this can result in
  6548. * a -1 error in red and green and a +2 error in blue. Consequently
  6549. * the worst case in the calculation below is 2/32768 error.
  6550. *
  6551. * TODO: consider fixing this in libpng by rounding the calculation
  6552. * limiting the error to 1/32768.
  6553. *
  6554. * Handling this by adding 2/32768 here avoids needing to increase
  6555. * the global error limits to take this into account.)
  6556. */
  6557. gray = r * data.red_coefficient + g * data.green_coefficient +
  6558. b * data.blue_coefficient;
  6559. err = re * data.red_coefficient + ge * data.green_coefficient +
  6560. be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON;
  6561. }
  6562. else
  6563. {
  6564. /* The calculation happens in linear space, and this produces much
  6565. * wider errors in the encoded space. These are handled here by
  6566. * factoring the errors in to the calculation. There are two table
  6567. * lookups in the calculation and each introduces a quantization
  6568. * error defined by the table size.
  6569. */
  6570. const png_modifier *pm = display->pm;
  6571. double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
  6572. double out_qe = (that->sample_depth > 8 ? .5/65535 :
  6573. (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) :
  6574. .5/255));
  6575. double rhi, ghi, bhi, grayhi;
  6576. double g1 = 1/data.gamma;
  6577. rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
  6578. r -= re + in_qe; if (r < 0) r = 0;
  6579. ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
  6580. g -= ge + in_qe; if (g < 0) g = 0;
  6581. bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
  6582. b -= be + in_qe; if (b < 0) b = 0;
  6583. r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
  6584. g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
  6585. b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
  6586. /* Work out the lower and upper bounds for the gray value in the
  6587. * encoded space, then work out an average and error. Remove the
  6588. * previously added input quantization error at this point.
  6589. */
  6590. gray = r * data.red_coefficient + g * data.green_coefficient +
  6591. b * data.blue_coefficient - 2./32768 - out_qe;
  6592. if (gray <= 0)
  6593. gray = 0;
  6594. else
  6595. {
  6596. gray *= (1 - 6 * DBL_EPSILON);
  6597. gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
  6598. }
  6599. grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
  6600. bhi * data.blue_coefficient + 2./32768 + out_qe;
  6601. grayhi *= (1 + 6 * DBL_EPSILON);
  6602. if (grayhi >= 1)
  6603. grayhi = 1;
  6604. else
  6605. grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
  6606. err = (grayhi - gray) / 2;
  6607. gray = (grayhi + gray) / 2;
  6608. if (err <= in_qe)
  6609. err = gray * DBL_EPSILON;
  6610. else
  6611. err -= in_qe;
  6612. /* Validate that the error is within limits (this has caused
  6613. * problems before, it's much easier to detect them here.)
  6614. */
  6615. if (err > pm->limit)
  6616. {
  6617. size_t pos = 0;
  6618. char buffer[128];
  6619. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  6620. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  6621. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  6622. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  6623. png_error(pp, buffer);
  6624. }
  6625. }
  6626. }
  6627. # endif /* !DIGITIZE */
  6628. that->bluef = that->greenf = that->redf = gray;
  6629. that->bluee = that->greene = that->rede = err;
  6630. /* The sBIT is the minium of the three colour channel sBITs. */
  6631. if (that->red_sBIT > that->green_sBIT)
  6632. that->red_sBIT = that->green_sBIT;
  6633. if (that->red_sBIT > that->blue_sBIT)
  6634. that->red_sBIT = that->blue_sBIT;
  6635. that->blue_sBIT = that->green_sBIT = that->red_sBIT;
  6636. /* And remove the colour bit in the type: */
  6637. if (that->colour_type == PNG_COLOR_TYPE_RGB)
  6638. that->colour_type = PNG_COLOR_TYPE_GRAY;
  6639. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  6640. that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  6641. }
  6642. this->next->mod(this->next, that, pp, display);
  6643. }
  6644. static int
  6645. image_transform_png_set_rgb_to_gray_add(image_transform *this,
  6646. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6647. {
  6648. UNUSED(bit_depth)
  6649. this->next = *that;
  6650. *that = this;
  6651. return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
  6652. }
  6653. #undef data
  6654. IT(rgb_to_gray);
  6655. #undef PT
  6656. #define PT ITSTRUCT(rgb_to_gray)
  6657. #undef image_transform_ini
  6658. #define image_transform_ini image_transform_default_ini
  6659. #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
  6660. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  6661. /* png_set_background(png_structp, png_const_color_16p background_color,
  6662. * int background_gamma_code, int need_expand, double background_gamma)
  6663. * png_set_background_fixed(png_structp, png_const_color_16p background_color,
  6664. * int background_gamma_code, int need_expand,
  6665. * png_fixed_point background_gamma)
  6666. *
  6667. * This ignores the gamma (at present.)
  6668. */
  6669. #define data ITDATA(background)
  6670. static image_pixel data;
  6671. static void
  6672. image_transform_png_set_background_set(const image_transform *this,
  6673. transform_display *that, png_structp pp, png_infop pi)
  6674. {
  6675. png_byte colour_type, bit_depth;
  6676. png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
  6677. int expand;
  6678. png_color_16 back;
  6679. /* We need a background colour, because we don't know exactly what transforms
  6680. * have been set we have to supply the colour in the original file format and
  6681. * so we need to know what that is! The background colour is stored in the
  6682. * transform_display.
  6683. */
  6684. RANDOMIZE(random_bytes);
  6685. /* Read the random value, for colour type 3 the background colour is actually
  6686. * expressed as a 24bit rgb, not an index.
  6687. */
  6688. colour_type = that->this.colour_type;
  6689. if (colour_type == 3)
  6690. {
  6691. colour_type = PNG_COLOR_TYPE_RGB;
  6692. bit_depth = 8;
  6693. expand = 0; /* passing in an RGB not a pixel index */
  6694. }
  6695. else
  6696. {
  6697. if (that->this.has_tRNS)
  6698. that->this.is_transparent = 1;
  6699. bit_depth = that->this.bit_depth;
  6700. expand = 1;
  6701. }
  6702. image_pixel_init(&data, random_bytes, colour_type,
  6703. bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
  6704. /* Extract the background colour from this image_pixel, but make sure the
  6705. * unused fields of 'back' are garbage.
  6706. */
  6707. RANDOMIZE(back);
  6708. if (colour_type & PNG_COLOR_MASK_COLOR)
  6709. {
  6710. back.red = (png_uint_16)data.red;
  6711. back.green = (png_uint_16)data.green;
  6712. back.blue = (png_uint_16)data.blue;
  6713. }
  6714. else
  6715. back.gray = (png_uint_16)data.red;
  6716. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6717. png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  6718. # else
  6719. png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  6720. # endif
  6721. this->next->set(this->next, that, pp, pi);
  6722. }
  6723. static void
  6724. image_transform_png_set_background_mod(const image_transform *this,
  6725. image_pixel *that, png_const_structp pp,
  6726. const transform_display *display)
  6727. {
  6728. /* Check for tRNS first: */
  6729. if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
  6730. image_pixel_add_alpha(that, &display->this, 1/*for background*/);
  6731. /* This is only necessary if the alpha value is less than 1. */
  6732. if (that->alphaf < 1)
  6733. {
  6734. /* Now we do the background calculation without any gamma correction. */
  6735. if (that->alphaf <= 0)
  6736. {
  6737. that->redf = data.redf;
  6738. that->greenf = data.greenf;
  6739. that->bluef = data.bluef;
  6740. that->rede = data.rede;
  6741. that->greene = data.greene;
  6742. that->bluee = data.bluee;
  6743. that->red_sBIT= data.red_sBIT;
  6744. that->green_sBIT= data.green_sBIT;
  6745. that->blue_sBIT= data.blue_sBIT;
  6746. }
  6747. else /* 0 < alpha < 1 */
  6748. {
  6749. double alf = 1 - that->alphaf;
  6750. that->redf = that->redf * that->alphaf + data.redf * alf;
  6751. that->rede = that->rede * that->alphaf + data.rede * alf +
  6752. DBL_EPSILON;
  6753. that->greenf = that->greenf * that->alphaf + data.greenf * alf;
  6754. that->greene = that->greene * that->alphaf + data.greene * alf +
  6755. DBL_EPSILON;
  6756. that->bluef = that->bluef * that->alphaf + data.bluef * alf;
  6757. that->bluee = that->bluee * that->alphaf + data.bluee * alf +
  6758. DBL_EPSILON;
  6759. }
  6760. /* Remove the alpha type and set the alpha (not in that order.) */
  6761. that->alphaf = 1;
  6762. that->alphae = 0;
  6763. }
  6764. if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  6765. that->colour_type = PNG_COLOR_TYPE_RGB;
  6766. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  6767. that->colour_type = PNG_COLOR_TYPE_GRAY;
  6768. /* PNG_COLOR_TYPE_PALETTE is not changed */
  6769. this->next->mod(this->next, that, pp, display);
  6770. }
  6771. #define image_transform_png_set_background_add image_transform_default_add
  6772. #undef data
  6773. IT(background);
  6774. #undef PT
  6775. #define PT ITSTRUCT(background)
  6776. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  6777. /* png_set_quantize(png_structp, png_colorp palette, int num_palette,
  6778. * int maximum_colors, png_const_uint_16p histogram, int full_quantize)
  6779. *
  6780. * Very difficult to validate this!
  6781. */
  6782. /*NOTE: TBD NYI */
  6783. /* The data layout transforms are handled by swapping our own channel data,
  6784. * necessarily these need to happen at the end of the transform list because the
  6785. * semantic of the channels changes after these are executed. Some of these,
  6786. * like set_shift and set_packing, can't be done at present because they change
  6787. * the layout of the data at the sub-sample level so sample() won't get the
  6788. * right answer.
  6789. */
  6790. /* png_set_invert_alpha */
  6791. #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
  6792. /* Invert the alpha channel
  6793. *
  6794. * png_set_invert_alpha(png_structrp png_ptr)
  6795. */
  6796. static void
  6797. image_transform_png_set_invert_alpha_set(const image_transform *this,
  6798. transform_display *that, png_structp pp, png_infop pi)
  6799. {
  6800. png_set_invert_alpha(pp);
  6801. this->next->set(this->next, that, pp, pi);
  6802. }
  6803. static void
  6804. image_transform_png_set_invert_alpha_mod(const image_transform *this,
  6805. image_pixel *that, png_const_structp pp,
  6806. const transform_display *display)
  6807. {
  6808. if (that->colour_type & 4)
  6809. that->alpha_inverted = 1;
  6810. this->next->mod(this->next, that, pp, display);
  6811. }
  6812. static int
  6813. image_transform_png_set_invert_alpha_add(image_transform *this,
  6814. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6815. {
  6816. UNUSED(bit_depth)
  6817. this->next = *that;
  6818. *that = this;
  6819. /* Only has an effect on pixels with alpha: */
  6820. return (colour_type & 4) != 0;
  6821. }
  6822. IT(invert_alpha);
  6823. #undef PT
  6824. #define PT ITSTRUCT(invert_alpha)
  6825. #endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
  6826. /* png_set_bgr */
  6827. #ifdef PNG_READ_BGR_SUPPORTED
  6828. /* Swap R,G,B channels to order B,G,R.
  6829. *
  6830. * png_set_bgr(png_structrp png_ptr)
  6831. *
  6832. * This only has an effect on RGB and RGBA pixels.
  6833. */
  6834. static void
  6835. image_transform_png_set_bgr_set(const image_transform *this,
  6836. transform_display *that, png_structp pp, png_infop pi)
  6837. {
  6838. png_set_bgr(pp);
  6839. this->next->set(this->next, that, pp, pi);
  6840. }
  6841. static void
  6842. image_transform_png_set_bgr_mod(const image_transform *this,
  6843. image_pixel *that, png_const_structp pp,
  6844. const transform_display *display)
  6845. {
  6846. if (that->colour_type == PNG_COLOR_TYPE_RGB ||
  6847. that->colour_type == PNG_COLOR_TYPE_RGBA)
  6848. that->swap_rgb = 1;
  6849. this->next->mod(this->next, that, pp, display);
  6850. }
  6851. static int
  6852. image_transform_png_set_bgr_add(image_transform *this,
  6853. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6854. {
  6855. UNUSED(bit_depth)
  6856. this->next = *that;
  6857. *that = this;
  6858. return colour_type == PNG_COLOR_TYPE_RGB ||
  6859. colour_type == PNG_COLOR_TYPE_RGBA;
  6860. }
  6861. IT(bgr);
  6862. #undef PT
  6863. #define PT ITSTRUCT(bgr)
  6864. #endif /* PNG_READ_BGR_SUPPORTED */
  6865. /* png_set_swap_alpha */
  6866. #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
  6867. /* Put the alpha channel first.
  6868. *
  6869. * png_set_swap_alpha(png_structrp png_ptr)
  6870. *
  6871. * This only has an effect on GA and RGBA pixels.
  6872. */
  6873. static void
  6874. image_transform_png_set_swap_alpha_set(const image_transform *this,
  6875. transform_display *that, png_structp pp, png_infop pi)
  6876. {
  6877. png_set_swap_alpha(pp);
  6878. this->next->set(this->next, that, pp, pi);
  6879. }
  6880. static void
  6881. image_transform_png_set_swap_alpha_mod(const image_transform *this,
  6882. image_pixel *that, png_const_structp pp,
  6883. const transform_display *display)
  6884. {
  6885. if (that->colour_type == PNG_COLOR_TYPE_GA ||
  6886. that->colour_type == PNG_COLOR_TYPE_RGBA)
  6887. that->alpha_first = 1;
  6888. this->next->mod(this->next, that, pp, display);
  6889. }
  6890. static int
  6891. image_transform_png_set_swap_alpha_add(image_transform *this,
  6892. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6893. {
  6894. UNUSED(bit_depth)
  6895. this->next = *that;
  6896. *that = this;
  6897. return colour_type == PNG_COLOR_TYPE_GA ||
  6898. colour_type == PNG_COLOR_TYPE_RGBA;
  6899. }
  6900. IT(swap_alpha);
  6901. #undef PT
  6902. #define PT ITSTRUCT(swap_alpha)
  6903. #endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
  6904. /* png_set_swap */
  6905. #ifdef PNG_READ_SWAP_SUPPORTED
  6906. /* Byte swap 16-bit components.
  6907. *
  6908. * png_set_swap(png_structrp png_ptr)
  6909. */
  6910. static void
  6911. image_transform_png_set_swap_set(const image_transform *this,
  6912. transform_display *that, png_structp pp, png_infop pi)
  6913. {
  6914. png_set_swap(pp);
  6915. this->next->set(this->next, that, pp, pi);
  6916. }
  6917. static void
  6918. image_transform_png_set_swap_mod(const image_transform *this,
  6919. image_pixel *that, png_const_structp pp,
  6920. const transform_display *display)
  6921. {
  6922. if (that->bit_depth == 16)
  6923. that->swap16 = 1;
  6924. this->next->mod(this->next, that, pp, display);
  6925. }
  6926. static int
  6927. image_transform_png_set_swap_add(image_transform *this,
  6928. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6929. {
  6930. UNUSED(colour_type)
  6931. this->next = *that;
  6932. *that = this;
  6933. return bit_depth == 16;
  6934. }
  6935. IT(swap);
  6936. #undef PT
  6937. #define PT ITSTRUCT(swap)
  6938. #endif /* PNG_READ_SWAP_SUPPORTED */
  6939. #ifdef PNG_READ_FILLER_SUPPORTED
  6940. /* Add a filler byte to 8-bit Gray or 24-bit RGB images.
  6941. *
  6942. * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
  6943. *
  6944. * Flags:
  6945. *
  6946. * PNG_FILLER_BEFORE
  6947. * PNG_FILLER_AFTER
  6948. */
  6949. #define data ITDATA(filler)
  6950. static struct
  6951. {
  6952. png_uint_32 filler;
  6953. int flags;
  6954. } data;
  6955. static void
  6956. image_transform_png_set_filler_set(const image_transform *this,
  6957. transform_display *that, png_structp pp, png_infop pi)
  6958. {
  6959. /* Need a random choice for 'before' and 'after' as well as for the
  6960. * filler. The 'filler' value has all 32 bits set, but only bit_depth
  6961. * will be used. At this point we don't know bit_depth.
  6962. */
  6963. RANDOMIZE(data.filler);
  6964. data.flags = random_choice();
  6965. png_set_filler(pp, data.filler, data.flags);
  6966. /* The standard display handling stuff also needs to know that
  6967. * there is a filler, so set that here.
  6968. */
  6969. that->this.filler = 1;
  6970. this->next->set(this->next, that, pp, pi);
  6971. }
  6972. static void
  6973. image_transform_png_set_filler_mod(const image_transform *this,
  6974. image_pixel *that, png_const_structp pp,
  6975. const transform_display *display)
  6976. {
  6977. if (that->bit_depth >= 8 &&
  6978. (that->colour_type == PNG_COLOR_TYPE_RGB ||
  6979. that->colour_type == PNG_COLOR_TYPE_GRAY))
  6980. {
  6981. const unsigned int max = (1U << that->bit_depth)-1;
  6982. that->alpha = data.filler & max;
  6983. that->alphaf = ((double)that->alpha) / max;
  6984. that->alphae = 0;
  6985. /* The filler has been stored in the alpha channel, we must record
  6986. * that this has been done for the checking later on, the color
  6987. * type is faked to have an alpha channel, but libpng won't report
  6988. * this; the app has to know the extra channel is there and this
  6989. * was recording in standard_display::filler above.
  6990. */
  6991. that->colour_type |= 4; /* alpha added */
  6992. that->alpha_first = data.flags == PNG_FILLER_BEFORE;
  6993. }
  6994. this->next->mod(this->next, that, pp, display);
  6995. }
  6996. static int
  6997. image_transform_png_set_filler_add(image_transform *this,
  6998. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6999. {
  7000. this->next = *that;
  7001. *that = this;
  7002. return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
  7003. colour_type == PNG_COLOR_TYPE_GRAY);
  7004. }
  7005. #undef data
  7006. IT(filler);
  7007. #undef PT
  7008. #define PT ITSTRUCT(filler)
  7009. /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
  7010. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  7011. #define data ITDATA(add_alpha)
  7012. static struct
  7013. {
  7014. png_uint_32 filler;
  7015. int flags;
  7016. } data;
  7017. static void
  7018. image_transform_png_set_add_alpha_set(const image_transform *this,
  7019. transform_display *that, png_structp pp, png_infop pi)
  7020. {
  7021. /* Need a random choice for 'before' and 'after' as well as for the
  7022. * filler. The 'filler' value has all 32 bits set, but only bit_depth
  7023. * will be used. At this point we don't know bit_depth.
  7024. */
  7025. RANDOMIZE(data.filler);
  7026. data.flags = random_choice();
  7027. png_set_add_alpha(pp, data.filler, data.flags);
  7028. this->next->set(this->next, that, pp, pi);
  7029. }
  7030. static void
  7031. image_transform_png_set_add_alpha_mod(const image_transform *this,
  7032. image_pixel *that, png_const_structp pp,
  7033. const transform_display *display)
  7034. {
  7035. if (that->bit_depth >= 8 &&
  7036. (that->colour_type == PNG_COLOR_TYPE_RGB ||
  7037. that->colour_type == PNG_COLOR_TYPE_GRAY))
  7038. {
  7039. const unsigned int max = (1U << that->bit_depth)-1;
  7040. that->alpha = data.filler & max;
  7041. that->alphaf = ((double)that->alpha) / max;
  7042. that->alphae = 0;
  7043. that->colour_type |= 4; /* alpha added */
  7044. that->alpha_first = data.flags == PNG_FILLER_BEFORE;
  7045. }
  7046. this->next->mod(this->next, that, pp, display);
  7047. }
  7048. static int
  7049. image_transform_png_set_add_alpha_add(image_transform *this,
  7050. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7051. {
  7052. this->next = *that;
  7053. *that = this;
  7054. return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
  7055. colour_type == PNG_COLOR_TYPE_GRAY);
  7056. }
  7057. #undef data
  7058. IT(add_alpha);
  7059. #undef PT
  7060. #define PT ITSTRUCT(add_alpha)
  7061. #endif /* PNG_READ_FILLER_SUPPORTED */
  7062. /* png_set_packing */
  7063. #ifdef PNG_READ_PACK_SUPPORTED
  7064. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
  7065. *
  7066. * png_set_packing(png_structrp png_ptr)
  7067. *
  7068. * This should only affect grayscale and palette images with less than 8 bits
  7069. * per pixel.
  7070. */
  7071. static void
  7072. image_transform_png_set_packing_set(const image_transform *this,
  7073. transform_display *that, png_structp pp, png_infop pi)
  7074. {
  7075. png_set_packing(pp);
  7076. that->unpacked = 1;
  7077. this->next->set(this->next, that, pp, pi);
  7078. }
  7079. static void
  7080. image_transform_png_set_packing_mod(const image_transform *this,
  7081. image_pixel *that, png_const_structp pp,
  7082. const transform_display *display)
  7083. {
  7084. /* The general expand case depends on what the colour type is,
  7085. * low bit-depth pixel values are unpacked into bytes without
  7086. * scaling, so sample_depth is not changed.
  7087. */
  7088. if (that->bit_depth < 8) /* grayscale or palette */
  7089. that->bit_depth = 8;
  7090. this->next->mod(this->next, that, pp, display);
  7091. }
  7092. static int
  7093. image_transform_png_set_packing_add(image_transform *this,
  7094. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7095. {
  7096. UNUSED(colour_type)
  7097. this->next = *that;
  7098. *that = this;
  7099. /* Nothing should happen unless the bit depth is less than 8: */
  7100. return bit_depth < 8;
  7101. }
  7102. IT(packing);
  7103. #undef PT
  7104. #define PT ITSTRUCT(packing)
  7105. #endif /* PNG_READ_PACK_SUPPORTED */
  7106. /* png_set_packswap */
  7107. #ifdef PNG_READ_PACKSWAP_SUPPORTED
  7108. /* Swap pixels packed into bytes; reverses the order on screen so that
  7109. * the high order bits correspond to the rightmost pixels.
  7110. *
  7111. * png_set_packswap(png_structrp png_ptr)
  7112. */
  7113. static void
  7114. image_transform_png_set_packswap_set(const image_transform *this,
  7115. transform_display *that, png_structp pp, png_infop pi)
  7116. {
  7117. png_set_packswap(pp);
  7118. that->this.littleendian = 1;
  7119. this->next->set(this->next, that, pp, pi);
  7120. }
  7121. static void
  7122. image_transform_png_set_packswap_mod(const image_transform *this,
  7123. image_pixel *that, png_const_structp pp,
  7124. const transform_display *display)
  7125. {
  7126. if (that->bit_depth < 8)
  7127. that->littleendian = 1;
  7128. this->next->mod(this->next, that, pp, display);
  7129. }
  7130. static int
  7131. image_transform_png_set_packswap_add(image_transform *this,
  7132. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7133. {
  7134. UNUSED(colour_type)
  7135. this->next = *that;
  7136. *that = this;
  7137. return bit_depth < 8;
  7138. }
  7139. IT(packswap);
  7140. #undef PT
  7141. #define PT ITSTRUCT(packswap)
  7142. #endif /* PNG_READ_PACKSWAP_SUPPORTED */
  7143. /* png_set_invert_mono */
  7144. #ifdef PNG_READ_INVERT_MONO_SUPPORTED
  7145. /* Invert the gray channel
  7146. *
  7147. * png_set_invert_mono(png_structrp png_ptr)
  7148. */
  7149. static void
  7150. image_transform_png_set_invert_mono_set(const image_transform *this,
  7151. transform_display *that, png_structp pp, png_infop pi)
  7152. {
  7153. png_set_invert_mono(pp);
  7154. this->next->set(this->next, that, pp, pi);
  7155. }
  7156. static void
  7157. image_transform_png_set_invert_mono_mod(const image_transform *this,
  7158. image_pixel *that, png_const_structp pp,
  7159. const transform_display *display)
  7160. {
  7161. if (that->colour_type & 4)
  7162. that->mono_inverted = 1;
  7163. this->next->mod(this->next, that, pp, display);
  7164. }
  7165. static int
  7166. image_transform_png_set_invert_mono_add(image_transform *this,
  7167. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7168. {
  7169. UNUSED(bit_depth)
  7170. this->next = *that;
  7171. *that = this;
  7172. /* Only has an effect on pixels with no colour: */
  7173. return (colour_type & 2) == 0;
  7174. }
  7175. IT(invert_mono);
  7176. #undef PT
  7177. #define PT ITSTRUCT(invert_mono)
  7178. #endif /* PNG_READ_INVERT_MONO_SUPPORTED */
  7179. #ifdef PNG_READ_SHIFT_SUPPORTED
  7180. /* png_set_shift(png_structp, png_const_color_8p true_bits)
  7181. *
  7182. * The output pixels will be shifted by the given true_bits
  7183. * values.
  7184. */
  7185. #define data ITDATA(shift)
  7186. static png_color_8 data;
  7187. static void
  7188. image_transform_png_set_shift_set(const image_transform *this,
  7189. transform_display *that, png_structp pp, png_infop pi)
  7190. {
  7191. /* Get a random set of shifts. The shifts need to do something
  7192. * to test the transform, so they are limited to the bit depth
  7193. * of the input image. Notice that in the following the 'gray'
  7194. * field is randomized independently. This acts as a check that
  7195. * libpng does use the correct field.
  7196. */
  7197. const unsigned int depth = that->this.bit_depth;
  7198. data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7199. data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7200. data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7201. data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7202. data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7203. png_set_shift(pp, &data);
  7204. this->next->set(this->next, that, pp, pi);
  7205. }
  7206. static void
  7207. image_transform_png_set_shift_mod(const image_transform *this,
  7208. image_pixel *that, png_const_structp pp,
  7209. const transform_display *display)
  7210. {
  7211. /* Copy the correct values into the sBIT fields, libpng does not do
  7212. * anything to palette data:
  7213. */
  7214. if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
  7215. {
  7216. that->sig_bits = 1;
  7217. /* The sBIT fields are reset to the values previously sent to
  7218. * png_set_shift according to the colour type.
  7219. * does.
  7220. */
  7221. if (that->colour_type & 2) /* RGB channels */
  7222. {
  7223. that->red_sBIT = data.red;
  7224. that->green_sBIT = data.green;
  7225. that->blue_sBIT = data.blue;
  7226. }
  7227. else /* One grey channel */
  7228. that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
  7229. that->alpha_sBIT = data.alpha;
  7230. }
  7231. this->next->mod(this->next, that, pp, display);
  7232. }
  7233. static int
  7234. image_transform_png_set_shift_add(image_transform *this,
  7235. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7236. {
  7237. UNUSED(bit_depth)
  7238. this->next = *that;
  7239. *that = this;
  7240. return colour_type != PNG_COLOR_TYPE_PALETTE;
  7241. }
  7242. IT(shift);
  7243. #undef PT
  7244. #define PT ITSTRUCT(shift)
  7245. #endif /* PNG_READ_SHIFT_SUPPORTED */
  7246. #ifdef THIS_IS_THE_PROFORMA
  7247. static void
  7248. image_transform_png_set_@_set(const image_transform *this,
  7249. transform_display *that, png_structp pp, png_infop pi)
  7250. {
  7251. png_set_@(pp);
  7252. this->next->set(this->next, that, pp, pi);
  7253. }
  7254. static void
  7255. image_transform_png_set_@_mod(const image_transform *this,
  7256. image_pixel *that, png_const_structp pp,
  7257. const transform_display *display)
  7258. {
  7259. this->next->mod(this->next, that, pp, display);
  7260. }
  7261. static int
  7262. image_transform_png_set_@_add(image_transform *this,
  7263. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7264. {
  7265. this->next = *that;
  7266. *that = this;
  7267. return 1;
  7268. }
  7269. IT(@);
  7270. #endif
  7271. /* This may just be 'end' if all the transforms are disabled! */
  7272. static image_transform *const image_transform_first = &PT;
  7273. static void
  7274. transform_enable(const char *name)
  7275. {
  7276. /* Everything starts out enabled, so if we see an 'enable' disabled
  7277. * everything else the first time round.
  7278. */
  7279. static int all_disabled = 0;
  7280. int found_it = 0;
  7281. image_transform *list = image_transform_first;
  7282. while (list != &image_transform_end)
  7283. {
  7284. if (strcmp(list->name, name) == 0)
  7285. {
  7286. list->enable = 1;
  7287. found_it = 1;
  7288. }
  7289. else if (!all_disabled)
  7290. list->enable = 0;
  7291. list = list->list;
  7292. }
  7293. all_disabled = 1;
  7294. if (!found_it)
  7295. {
  7296. fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
  7297. name);
  7298. exit(99);
  7299. }
  7300. }
  7301. static void
  7302. transform_disable(const char *name)
  7303. {
  7304. image_transform *list = image_transform_first;
  7305. while (list != &image_transform_end)
  7306. {
  7307. if (strcmp(list->name, name) == 0)
  7308. {
  7309. list->enable = 0;
  7310. return;
  7311. }
  7312. list = list->list;
  7313. }
  7314. fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
  7315. name);
  7316. exit(99);
  7317. }
  7318. static void
  7319. image_transform_reset_count(void)
  7320. {
  7321. image_transform *next = image_transform_first;
  7322. int count = 0;
  7323. while (next != &image_transform_end)
  7324. {
  7325. next->local_use = 0;
  7326. next->next = 0;
  7327. next = next->list;
  7328. ++count;
  7329. }
  7330. /* This can only happen if we every have more than 32 transforms (excluding
  7331. * the end) in the list.
  7332. */
  7333. if (count > 32) abort();
  7334. }
  7335. static int
  7336. image_transform_test_counter(png_uint_32 counter, unsigned int max)
  7337. {
  7338. /* Test the list to see if there is any point contining, given a current
  7339. * counter and a 'max' value.
  7340. */
  7341. image_transform *next = image_transform_first;
  7342. while (next != &image_transform_end)
  7343. {
  7344. /* For max 0 or 1 continue until the counter overflows: */
  7345. counter >>= 1;
  7346. /* Continue if any entry hasn't reacked the max. */
  7347. if (max > 1 && next->local_use < max)
  7348. return 1;
  7349. next = next->list;
  7350. }
  7351. return max <= 1 && counter == 0;
  7352. }
  7353. static png_uint_32
  7354. image_transform_add(const image_transform **this, unsigned int max,
  7355. png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
  7356. png_byte colour_type, png_byte bit_depth)
  7357. {
  7358. for (;;) /* until we manage to add something */
  7359. {
  7360. png_uint_32 mask;
  7361. image_transform *list;
  7362. /* Find the next counter value, if the counter is zero this is the start
  7363. * of the list. This routine always returns the current counter (not the
  7364. * next) so it returns 0 at the end and expects 0 at the beginning.
  7365. */
  7366. if (counter == 0) /* first time */
  7367. {
  7368. image_transform_reset_count();
  7369. if (max <= 1)
  7370. counter = 1;
  7371. else
  7372. counter = random_32();
  7373. }
  7374. else /* advance the counter */
  7375. {
  7376. switch (max)
  7377. {
  7378. case 0: ++counter; break;
  7379. case 1: counter <<= 1; break;
  7380. default: counter = random_32(); break;
  7381. }
  7382. }
  7383. /* Now add all these items, if possible */
  7384. *this = &image_transform_end;
  7385. list = image_transform_first;
  7386. mask = 1;
  7387. /* Go through the whole list adding anything that the counter selects: */
  7388. while (list != &image_transform_end)
  7389. {
  7390. if ((counter & mask) != 0 && list->enable &&
  7391. (max == 0 || list->local_use < max))
  7392. {
  7393. /* Candidate to add: */
  7394. if (list->add(list, this, colour_type, bit_depth) || max == 0)
  7395. {
  7396. /* Added, so add to the name too. */
  7397. *pos = safecat(name, sizeof_name, *pos, " +");
  7398. *pos = safecat(name, sizeof_name, *pos, list->name);
  7399. }
  7400. else
  7401. {
  7402. /* Not useful and max>0, so remove it from *this: */
  7403. *this = list->next;
  7404. list->next = 0;
  7405. /* And, since we know it isn't useful, stop it being added again
  7406. * in this run:
  7407. */
  7408. list->local_use = max;
  7409. }
  7410. }
  7411. mask <<= 1;
  7412. list = list->list;
  7413. }
  7414. /* Now if anything was added we have something to do. */
  7415. if (*this != &image_transform_end)
  7416. return counter;
  7417. /* Nothing added, but was there anything in there to add? */
  7418. if (!image_transform_test_counter(counter, max))
  7419. return 0;
  7420. }
  7421. }
  7422. static void
  7423. perform_transform_test(png_modifier *pm)
  7424. {
  7425. png_byte colour_type = 0;
  7426. png_byte bit_depth = 0;
  7427. unsigned int palette_number = 0;
  7428. while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
  7429. pm->test_tRNS))
  7430. {
  7431. png_uint_32 counter = 0;
  7432. size_t base_pos;
  7433. char name[64];
  7434. base_pos = safecat(name, sizeof name, 0, "transform:");
  7435. for (;;)
  7436. {
  7437. size_t pos = base_pos;
  7438. const image_transform *list = 0;
  7439. /* 'max' is currently hardwired to '1'; this should be settable on the
  7440. * command line.
  7441. */
  7442. counter = image_transform_add(&list, 1/*max*/, counter,
  7443. name, sizeof name, &pos, colour_type, bit_depth);
  7444. if (counter == 0)
  7445. break;
  7446. /* The command line can change this to checking interlaced images. */
  7447. do
  7448. {
  7449. pm->repeat = 0;
  7450. transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
  7451. pm->interlace_type, 0, 0, 0), list, name);
  7452. if (fail(pm))
  7453. return;
  7454. }
  7455. while (pm->repeat);
  7456. }
  7457. }
  7458. }
  7459. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  7460. /********************************* GAMMA TESTS ********************************/
  7461. #ifdef PNG_READ_GAMMA_SUPPORTED
  7462. /* Reader callbacks and implementations, where they differ from the standard
  7463. * ones.
  7464. */
  7465. typedef struct gamma_display
  7466. {
  7467. standard_display this;
  7468. /* Parameters */
  7469. png_modifier* pm;
  7470. double file_gamma;
  7471. double screen_gamma;
  7472. double background_gamma;
  7473. png_byte sbit;
  7474. int threshold_test;
  7475. int use_input_precision;
  7476. int scale16;
  7477. int expand16;
  7478. int do_background;
  7479. png_color_16 background_color;
  7480. /* Local variables */
  7481. double maxerrout;
  7482. double maxerrpc;
  7483. double maxerrabs;
  7484. } gamma_display;
  7485. #define ALPHA_MODE_OFFSET 4
  7486. static void
  7487. gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
  7488. double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
  7489. int use_input_precision, int scale16, int expand16,
  7490. int do_background, const png_color_16 *pointer_to_the_background_color,
  7491. double background_gamma)
  7492. {
  7493. /* Standard fields */
  7494. standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
  7495. pm->use_update_info);
  7496. /* Parameter fields */
  7497. dp->pm = pm;
  7498. dp->file_gamma = file_gamma;
  7499. dp->screen_gamma = screen_gamma;
  7500. dp->background_gamma = background_gamma;
  7501. dp->sbit = sbit;
  7502. dp->threshold_test = threshold_test;
  7503. dp->use_input_precision = use_input_precision;
  7504. dp->scale16 = scale16;
  7505. dp->expand16 = expand16;
  7506. dp->do_background = do_background;
  7507. if (do_background && pointer_to_the_background_color != 0)
  7508. dp->background_color = *pointer_to_the_background_color;
  7509. else
  7510. memset(&dp->background_color, 0, sizeof dp->background_color);
  7511. /* Local variable fields */
  7512. dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
  7513. }
  7514. static void
  7515. gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
  7516. {
  7517. /* Reuse the standard stuff as appropriate. */
  7518. standard_info_part1(&dp->this, pp, pi);
  7519. /* If requested strip 16 to 8 bits - this is handled automagically below
  7520. * because the output bit depth is read from the library. Note that there
  7521. * are interactions with sBIT but, internally, libpng makes sbit at most
  7522. * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
  7523. */
  7524. if (dp->scale16)
  7525. # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
  7526. png_set_scale_16(pp);
  7527. # else
  7528. /* The following works both in 1.5.4 and earlier versions: */
  7529. # ifdef PNG_READ_16_TO_8_SUPPORTED
  7530. png_set_strip_16(pp);
  7531. # else
  7532. png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
  7533. # endif
  7534. # endif
  7535. if (dp->expand16)
  7536. # ifdef PNG_READ_EXPAND_16_SUPPORTED
  7537. png_set_expand_16(pp);
  7538. # else
  7539. png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
  7540. # endif
  7541. if (dp->do_background >= ALPHA_MODE_OFFSET)
  7542. {
  7543. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7544. {
  7545. /* This tests the alpha mode handling, if supported. */
  7546. int mode = dp->do_background - ALPHA_MODE_OFFSET;
  7547. /* The gamma value is the output gamma, and is in the standard,
  7548. * non-inverted, represenation. It provides a default for the PNG file
  7549. * gamma, but since the file has a gAMA chunk this does not matter.
  7550. */
  7551. const double sg = dp->screen_gamma;
  7552. # ifndef PNG_FLOATING_POINT_SUPPORTED
  7553. const png_fixed_point g = fix(sg);
  7554. # endif
  7555. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7556. png_set_alpha_mode(pp, mode, sg);
  7557. # else
  7558. png_set_alpha_mode_fixed(pp, mode, g);
  7559. # endif
  7560. /* However, for the standard Porter-Duff algorithm the output defaults
  7561. * to be linear, so if the test requires non-linear output it must be
  7562. * corrected here.
  7563. */
  7564. if (mode == PNG_ALPHA_STANDARD && sg != 1)
  7565. {
  7566. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7567. png_set_gamma(pp, sg, dp->file_gamma);
  7568. # else
  7569. png_fixed_point f = fix(dp->file_gamma);
  7570. png_set_gamma_fixed(pp, g, f);
  7571. # endif
  7572. }
  7573. }
  7574. # else
  7575. png_error(pp, "alpha mode handling not supported");
  7576. # endif
  7577. }
  7578. else
  7579. {
  7580. /* Set up gamma processing. */
  7581. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7582. png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
  7583. # else
  7584. {
  7585. png_fixed_point s = fix(dp->screen_gamma);
  7586. png_fixed_point f = fix(dp->file_gamma);
  7587. png_set_gamma_fixed(pp, s, f);
  7588. }
  7589. # endif
  7590. if (dp->do_background)
  7591. {
  7592. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  7593. /* NOTE: this assumes the caller provided the correct background gamma!
  7594. */
  7595. const double bg = dp->background_gamma;
  7596. # ifndef PNG_FLOATING_POINT_SUPPORTED
  7597. const png_fixed_point g = fix(bg);
  7598. # endif
  7599. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7600. png_set_background(pp, &dp->background_color, dp->do_background,
  7601. 0/*need_expand*/, bg);
  7602. # else
  7603. png_set_background_fixed(pp, &dp->background_color,
  7604. dp->do_background, 0/*need_expand*/, g);
  7605. # endif
  7606. # else
  7607. png_error(pp, "png_set_background not supported");
  7608. # endif
  7609. }
  7610. }
  7611. {
  7612. int i = dp->this.use_update_info;
  7613. /* Always do one call, even if use_update_info is 0. */
  7614. do
  7615. png_read_update_info(pp, pi);
  7616. while (--i > 0);
  7617. }
  7618. /* Now we may get a different cbRow: */
  7619. standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
  7620. }
  7621. static void PNGCBAPI
  7622. gamma_info(png_structp pp, png_infop pi)
  7623. {
  7624. gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
  7625. pi);
  7626. }
  7627. /* Validate a single component value - the routine gets the input and output
  7628. * sample values as unscaled PNG component values along with a cache of all the
  7629. * information required to validate the values.
  7630. */
  7631. typedef struct validate_info
  7632. {
  7633. png_const_structp pp;
  7634. gamma_display *dp;
  7635. png_byte sbit;
  7636. int use_input_precision;
  7637. int do_background;
  7638. int scale16;
  7639. unsigned int sbit_max;
  7640. unsigned int isbit_shift;
  7641. unsigned int outmax;
  7642. double gamma_correction; /* Overall correction required. */
  7643. double file_inverse; /* Inverse of file gamma. */
  7644. double screen_gamma;
  7645. double screen_inverse; /* Inverse of screen gamma. */
  7646. double background_red; /* Linear background value, red or gray. */
  7647. double background_green;
  7648. double background_blue;
  7649. double maxabs;
  7650. double maxpc;
  7651. double maxcalc;
  7652. double maxout;
  7653. double maxout_total; /* Total including quantization error */
  7654. double outlog;
  7655. int outquant;
  7656. }
  7657. validate_info;
  7658. static void
  7659. init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
  7660. int in_depth, int out_depth)
  7661. {
  7662. const unsigned int outmax = (1U<<out_depth)-1;
  7663. vi->pp = pp;
  7664. vi->dp = dp;
  7665. if (dp->sbit > 0 && dp->sbit < in_depth)
  7666. {
  7667. vi->sbit = dp->sbit;
  7668. vi->isbit_shift = in_depth - dp->sbit;
  7669. }
  7670. else
  7671. {
  7672. vi->sbit = (png_byte)in_depth;
  7673. vi->isbit_shift = 0;
  7674. }
  7675. vi->sbit_max = (1U << vi->sbit)-1;
  7676. /* This mimics the libpng threshold test, '0' is used to prevent gamma
  7677. * correction in the validation test.
  7678. */
  7679. vi->screen_gamma = dp->screen_gamma;
  7680. if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
  7681. vi->screen_gamma = vi->screen_inverse = 0;
  7682. else
  7683. vi->screen_inverse = 1/vi->screen_gamma;
  7684. vi->use_input_precision = dp->use_input_precision;
  7685. vi->outmax = outmax;
  7686. vi->maxabs = abserr(dp->pm, in_depth, out_depth);
  7687. vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
  7688. vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
  7689. vi->maxout = outerr(dp->pm, in_depth, out_depth);
  7690. vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
  7691. vi->maxout_total = vi->maxout + vi->outquant * .5;
  7692. vi->outlog = outlog(dp->pm, in_depth, out_depth);
  7693. if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
  7694. (dp->this.colour_type == 3 && dp->this.is_transparent) ||
  7695. ((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
  7696. dp->this.has_tRNS))
  7697. {
  7698. vi->do_background = dp->do_background;
  7699. if (vi->do_background != 0)
  7700. {
  7701. const double bg_inverse = 1/dp->background_gamma;
  7702. double r, g, b;
  7703. /* Caller must at least put the gray value into the red channel */
  7704. r = dp->background_color.red; r /= outmax;
  7705. g = dp->background_color.green; g /= outmax;
  7706. b = dp->background_color.blue; b /= outmax;
  7707. # if 0
  7708. /* libpng doesn't do this optimization, if we do pngvalid will fail.
  7709. */
  7710. if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
  7711. # endif
  7712. {
  7713. r = pow(r, bg_inverse);
  7714. g = pow(g, bg_inverse);
  7715. b = pow(b, bg_inverse);
  7716. }
  7717. vi->background_red = r;
  7718. vi->background_green = g;
  7719. vi->background_blue = b;
  7720. }
  7721. }
  7722. else /* Do not expect any background processing */
  7723. vi->do_background = 0;
  7724. if (vi->do_background == 0)
  7725. vi->background_red = vi->background_green = vi->background_blue = 0;
  7726. vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
  7727. if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
  7728. vi->gamma_correction = 0;
  7729. vi->file_inverse = 1/dp->file_gamma;
  7730. if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
  7731. vi->file_inverse = 0;
  7732. vi->scale16 = dp->scale16;
  7733. }
  7734. /* This function handles composition of a single non-alpha component. The
  7735. * argument is the input sample value, in the range 0..1, and the alpha value.
  7736. * The result is the composed, linear, input sample. If alpha is less than zero
  7737. * this is the alpha component and the function should not be called!
  7738. */
  7739. static double
  7740. gamma_component_compose(int do_background, double input_sample, double alpha,
  7741. double background, int *compose)
  7742. {
  7743. switch (do_background)
  7744. {
  7745. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  7746. case PNG_BACKGROUND_GAMMA_SCREEN:
  7747. case PNG_BACKGROUND_GAMMA_FILE:
  7748. case PNG_BACKGROUND_GAMMA_UNIQUE:
  7749. /* Standard PNG background processing. */
  7750. if (alpha < 1)
  7751. {
  7752. if (alpha > 0)
  7753. {
  7754. input_sample = input_sample * alpha + background * (1-alpha);
  7755. if (compose != NULL)
  7756. *compose = 1;
  7757. }
  7758. else
  7759. input_sample = background;
  7760. }
  7761. break;
  7762. #endif
  7763. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7764. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  7765. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  7766. /* The components are premultiplied in either case and the output is
  7767. * gamma encoded (to get standard Porter-Duff we expect the output
  7768. * gamma to be set to 1.0!)
  7769. */
  7770. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  7771. /* The optimization is that the partial-alpha entries are linear
  7772. * while the opaque pixels are gamma encoded, but this only affects the
  7773. * output encoding.
  7774. */
  7775. if (alpha < 1)
  7776. {
  7777. if (alpha > 0)
  7778. {
  7779. input_sample *= alpha;
  7780. if (compose != NULL)
  7781. *compose = 1;
  7782. }
  7783. else
  7784. input_sample = 0;
  7785. }
  7786. break;
  7787. #endif
  7788. default:
  7789. /* Standard cases where no compositing is done (so the component
  7790. * value is already correct.)
  7791. */
  7792. UNUSED(alpha)
  7793. UNUSED(background)
  7794. UNUSED(compose)
  7795. break;
  7796. }
  7797. return input_sample;
  7798. }
  7799. /* This API returns the encoded *input* component, in the range 0..1 */
  7800. static double
  7801. gamma_component_validate(const char *name, const validate_info *vi,
  7802. const unsigned int id, const unsigned int od,
  7803. const double alpha /* <0 for the alpha channel itself */,
  7804. const double background /* component background value */)
  7805. {
  7806. const unsigned int isbit = id >> vi->isbit_shift;
  7807. const unsigned int sbit_max = vi->sbit_max;
  7808. const unsigned int outmax = vi->outmax;
  7809. const int do_background = vi->do_background;
  7810. double i;
  7811. /* First check on the 'perfect' result obtained from the digitized input
  7812. * value, id, and compare this against the actual digitized result, 'od'.
  7813. * 'i' is the input result in the range 0..1:
  7814. */
  7815. i = isbit; i /= sbit_max;
  7816. /* Check for the fast route: if we don't do any background composition or if
  7817. * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
  7818. * just use the gamma_correction field to correct to the final output gamma.
  7819. */
  7820. if (alpha == 1 /* opaque pixel component */ || !do_background
  7821. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7822. || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
  7823. #endif
  7824. || (alpha < 0 /* alpha channel */
  7825. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7826. && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
  7827. #endif
  7828. ))
  7829. {
  7830. /* Then get the gamma corrected version of 'i' and compare to 'od', any
  7831. * error less than .5 is insignificant - just quantization of the output
  7832. * value to the nearest digital value (nevertheless the error is still
  7833. * recorded - it's interesting ;-)
  7834. */
  7835. double encoded_sample = i;
  7836. double encoded_error;
  7837. /* alpha less than 0 indicates the alpha channel, which is always linear
  7838. */
  7839. if (alpha >= 0 && vi->gamma_correction > 0)
  7840. encoded_sample = pow(encoded_sample, vi->gamma_correction);
  7841. encoded_sample *= outmax;
  7842. encoded_error = fabs(od-encoded_sample);
  7843. if (encoded_error > vi->dp->maxerrout)
  7844. vi->dp->maxerrout = encoded_error;
  7845. if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
  7846. return i;
  7847. }
  7848. /* The slow route - attempt to do linear calculations. */
  7849. /* There may be an error, or background processing is required, so calculate
  7850. * the actual sample values - unencoded light intensity values. Note that in
  7851. * practice these are not completely unencoded because they include a
  7852. * 'viewing correction' to decrease or (normally) increase the perceptual
  7853. * contrast of the image. There's nothing we can do about this - we don't
  7854. * know what it is - so assume the unencoded value is perceptually linear.
  7855. */
  7856. {
  7857. double input_sample = i; /* In range 0..1 */
  7858. double output, error, encoded_sample, encoded_error;
  7859. double es_lo, es_hi;
  7860. int compose = 0; /* Set to one if composition done */
  7861. int output_is_encoded; /* Set if encoded to screen gamma */
  7862. int log_max_error = 1; /* Check maximum error values */
  7863. png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */
  7864. /* Convert to linear light (with the above caveat.) The alpha channel is
  7865. * already linear.
  7866. */
  7867. if (alpha >= 0)
  7868. {
  7869. int tcompose;
  7870. if (vi->file_inverse > 0)
  7871. input_sample = pow(input_sample, vi->file_inverse);
  7872. /* Handle the compose processing: */
  7873. tcompose = 0;
  7874. input_sample = gamma_component_compose(do_background, input_sample,
  7875. alpha, background, &tcompose);
  7876. if (tcompose)
  7877. compose = 1;
  7878. }
  7879. /* And similarly for the output value, but we need to check the background
  7880. * handling to linearize it correctly.
  7881. */
  7882. output = od;
  7883. output /= outmax;
  7884. output_is_encoded = vi->screen_gamma > 0;
  7885. if (alpha < 0) /* The alpha channel */
  7886. {
  7887. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7888. if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
  7889. #endif
  7890. {
  7891. /* In all other cases the output alpha channel is linear already,
  7892. * don't log errors here, they are much larger in linear data.
  7893. */
  7894. output_is_encoded = 0;
  7895. log_max_error = 0;
  7896. }
  7897. }
  7898. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7899. else /* A component */
  7900. {
  7901. if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
  7902. alpha < 1) /* the optimized case - linear output */
  7903. {
  7904. if (alpha > 0) log_max_error = 0;
  7905. output_is_encoded = 0;
  7906. }
  7907. }
  7908. #endif
  7909. if (output_is_encoded)
  7910. output = pow(output, vi->screen_gamma);
  7911. /* Calculate (or recalculate) the encoded_sample value and repeat the
  7912. * check above (unnecessary if we took the fast route, but harmless.)
  7913. */
  7914. encoded_sample = input_sample;
  7915. if (output_is_encoded)
  7916. encoded_sample = pow(encoded_sample, vi->screen_inverse);
  7917. encoded_sample *= outmax;
  7918. encoded_error = fabs(od-encoded_sample);
  7919. /* Don't log errors in the alpha channel, or the 'optimized' case,
  7920. * neither are significant to the overall perception.
  7921. */
  7922. if (log_max_error && encoded_error > vi->dp->maxerrout)
  7923. vi->dp->maxerrout = encoded_error;
  7924. if (encoded_error < vi->maxout_total)
  7925. {
  7926. if (encoded_error < vi->outlog)
  7927. return i;
  7928. /* Test passed but error is bigger than the log limit, record why the
  7929. * test passed:
  7930. */
  7931. pass = "less than maxout:\n";
  7932. }
  7933. /* i: the original input value in the range 0..1
  7934. *
  7935. * pngvalid calculations:
  7936. * input_sample: linear result; i linearized and composed, range 0..1
  7937. * encoded_sample: encoded result; input_sample scaled to ouput bit depth
  7938. *
  7939. * libpng calculations:
  7940. * output: linear result; od scaled to 0..1 and linearized
  7941. * od: encoded result from libpng
  7942. */
  7943. /* Now we have the numbers for real errors, both absolute values as as a
  7944. * percentage of the correct value (output):
  7945. */
  7946. error = fabs(input_sample-output);
  7947. if (log_max_error && error > vi->dp->maxerrabs)
  7948. vi->dp->maxerrabs = error;
  7949. /* The following is an attempt to ignore the tendency of quantization to
  7950. * dominate the percentage errors for lower result values:
  7951. */
  7952. if (log_max_error && input_sample > .5)
  7953. {
  7954. double percentage_error = error/input_sample;
  7955. if (percentage_error > vi->dp->maxerrpc)
  7956. vi->dp->maxerrpc = percentage_error;
  7957. }
  7958. /* Now calculate the digitization limits for 'encoded_sample' using the
  7959. * 'max' values. Note that maxout is in the encoded space but maxpc and
  7960. * maxabs are in linear light space.
  7961. *
  7962. * First find the maximum error in linear light space, range 0..1:
  7963. */
  7964. {
  7965. double tmp = input_sample * vi->maxpc;
  7966. if (tmp < vi->maxabs) tmp = vi->maxabs;
  7967. /* If 'compose' is true the composition was done in linear space using
  7968. * integer arithmetic. This introduces an extra error of +/- 0.5 (at
  7969. * least) in the integer space used. 'maxcalc' records this, taking
  7970. * into account the possibility that even for 16 bit output 8 bit space
  7971. * may have been used.
  7972. */
  7973. if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
  7974. /* The 'maxout' value refers to the encoded result, to compare with
  7975. * this encode input_sample adjusted by the maximum error (tmp) above.
  7976. */
  7977. es_lo = encoded_sample - vi->maxout;
  7978. if (es_lo > 0 && input_sample-tmp > 0)
  7979. {
  7980. double low_value = input_sample-tmp;
  7981. if (output_is_encoded)
  7982. low_value = pow(low_value, vi->screen_inverse);
  7983. low_value *= outmax;
  7984. if (low_value < es_lo) es_lo = low_value;
  7985. /* Quantize this appropriately: */
  7986. es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
  7987. }
  7988. else
  7989. es_lo = 0;
  7990. es_hi = encoded_sample + vi->maxout;
  7991. if (es_hi < outmax && input_sample+tmp < 1)
  7992. {
  7993. double high_value = input_sample+tmp;
  7994. if (output_is_encoded)
  7995. high_value = pow(high_value, vi->screen_inverse);
  7996. high_value *= outmax;
  7997. if (high_value > es_hi) es_hi = high_value;
  7998. es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
  7999. }
  8000. else
  8001. es_hi = outmax;
  8002. }
  8003. /* The primary test is that the final encoded value returned by the
  8004. * library should be between the two limits (inclusive) that were
  8005. * calculated above.
  8006. */
  8007. if (od >= es_lo && od <= es_hi)
  8008. {
  8009. /* The value passes, but we may need to log the information anyway. */
  8010. if (encoded_error < vi->outlog)
  8011. return i;
  8012. if (pass == 0)
  8013. pass = "within digitization limits:\n";
  8014. }
  8015. {
  8016. /* There has been an error in processing, or we need to log this
  8017. * value.
  8018. */
  8019. double is_lo, is_hi;
  8020. /* pass is set at this point if either of the tests above would have
  8021. * passed. Don't do these additional tests here - just log the
  8022. * original [es_lo..es_hi] values.
  8023. */
  8024. if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
  8025. {
  8026. /* Ok, something is wrong - this actually happens in current libpng
  8027. * 16-to-8 processing. Assume that the input value (id, adjusted
  8028. * for sbit) can be anywhere between value-.5 and value+.5 - quite a
  8029. * large range if sbit is low.
  8030. *
  8031. * NOTE: at present because the libpng gamma table stuff has been
  8032. * changed to use a rounding algorithm to correct errors in 8-bit
  8033. * calculations the precise sbit calculation (a shift) has been
  8034. * lost. This can result in up to a +/-1 error in the presence of
  8035. * an sbit less than the bit depth.
  8036. */
  8037. # if PNG_LIBPNG_VER < 10700
  8038. # define SBIT_ERROR .5
  8039. # else
  8040. # define SBIT_ERROR 1.
  8041. # endif
  8042. double tmp = (isbit - SBIT_ERROR)/sbit_max;
  8043. if (tmp <= 0)
  8044. tmp = 0;
  8045. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  8046. tmp = pow(tmp, vi->file_inverse);
  8047. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  8048. NULL);
  8049. if (output_is_encoded && tmp > 0 && tmp < 1)
  8050. tmp = pow(tmp, vi->screen_inverse);
  8051. is_lo = ceil(outmax * tmp - vi->maxout_total);
  8052. if (is_lo < 0)
  8053. is_lo = 0;
  8054. tmp = (isbit + SBIT_ERROR)/sbit_max;
  8055. if (tmp >= 1)
  8056. tmp = 1;
  8057. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  8058. tmp = pow(tmp, vi->file_inverse);
  8059. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  8060. NULL);
  8061. if (output_is_encoded && tmp > 0 && tmp < 1)
  8062. tmp = pow(tmp, vi->screen_inverse);
  8063. is_hi = floor(outmax * tmp + vi->maxout_total);
  8064. if (is_hi > outmax)
  8065. is_hi = outmax;
  8066. if (!(od < is_lo || od > is_hi))
  8067. {
  8068. if (encoded_error < vi->outlog)
  8069. return i;
  8070. pass = "within input precision limits:\n";
  8071. }
  8072. /* One last chance. If this is an alpha channel and the 16to8
  8073. * option has been used and 'inaccurate' scaling is used then the
  8074. * bit reduction is obtained by simply using the top 8 bits of the
  8075. * value.
  8076. *
  8077. * This is only done for older libpng versions when the 'inaccurate'
  8078. * (chop) method of scaling was used.
  8079. */
  8080. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  8081. # if PNG_LIBPNG_VER < 10504
  8082. /* This may be required for other components in the future,
  8083. * but at present the presence of gamma correction effectively
  8084. * prevents the errors in the component scaling (I don't quite
  8085. * understand why, but since it's better this way I care not
  8086. * to ask, JB 20110419.)
  8087. */
  8088. if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
  8089. vi->sbit + vi->isbit_shift == 16)
  8090. {
  8091. tmp = ((id >> 8) - .5)/255;
  8092. if (tmp > 0)
  8093. {
  8094. is_lo = ceil(outmax * tmp - vi->maxout_total);
  8095. if (is_lo < 0) is_lo = 0;
  8096. }
  8097. else
  8098. is_lo = 0;
  8099. tmp = ((id >> 8) + .5)/255;
  8100. if (tmp < 1)
  8101. {
  8102. is_hi = floor(outmax * tmp + vi->maxout_total);
  8103. if (is_hi > outmax) is_hi = outmax;
  8104. }
  8105. else
  8106. is_hi = outmax;
  8107. if (!(od < is_lo || od > is_hi))
  8108. {
  8109. if (encoded_error < vi->outlog)
  8110. return i;
  8111. pass = "within 8 bit limits:\n";
  8112. }
  8113. }
  8114. # endif
  8115. # endif
  8116. }
  8117. else /* !use_input_precision */
  8118. is_lo = es_lo, is_hi = es_hi;
  8119. /* Attempt to output a meaningful error/warning message: the message
  8120. * output depends on the background/composite operation being performed
  8121. * because this changes what parameters were actually used above.
  8122. */
  8123. {
  8124. size_t pos = 0;
  8125. /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
  8126. * places. Just use outmax to work out which.
  8127. */
  8128. int precision = (outmax >= 1000 ? 6 : 3);
  8129. int use_input=1, use_background=0, do_compose=0;
  8130. char msg[256];
  8131. if (pass != 0)
  8132. pos = safecat(msg, sizeof msg, pos, "\n\t");
  8133. /* Set up the various flags, the output_is_encoded flag above
  8134. * is also used below. do_compose is just a double check.
  8135. */
  8136. switch (do_background)
  8137. {
  8138. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  8139. case PNG_BACKGROUND_GAMMA_SCREEN:
  8140. case PNG_BACKGROUND_GAMMA_FILE:
  8141. case PNG_BACKGROUND_GAMMA_UNIQUE:
  8142. use_background = (alpha >= 0 && alpha < 1);
  8143. /*FALL THROUGH*/
  8144. # endif
  8145. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8146. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  8147. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  8148. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  8149. # endif /* ALPHA_MODE_SUPPORTED */
  8150. do_compose = (alpha > 0 && alpha < 1);
  8151. use_input = (alpha != 0);
  8152. break;
  8153. default:
  8154. break;
  8155. }
  8156. /* Check the 'compose' flag */
  8157. if (compose != do_compose)
  8158. png_error(vi->pp, "internal error (compose)");
  8159. /* 'name' is the component name */
  8160. pos = safecat(msg, sizeof msg, pos, name);
  8161. pos = safecat(msg, sizeof msg, pos, "(");
  8162. pos = safecatn(msg, sizeof msg, pos, id);
  8163. if (use_input || pass != 0/*logging*/)
  8164. {
  8165. if (isbit != id)
  8166. {
  8167. /* sBIT has reduced the precision of the input: */
  8168. pos = safecat(msg, sizeof msg, pos, ", sbit(");
  8169. pos = safecatn(msg, sizeof msg, pos, vi->sbit);
  8170. pos = safecat(msg, sizeof msg, pos, "): ");
  8171. pos = safecatn(msg, sizeof msg, pos, isbit);
  8172. }
  8173. pos = safecat(msg, sizeof msg, pos, "/");
  8174. /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
  8175. pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
  8176. }
  8177. pos = safecat(msg, sizeof msg, pos, ")");
  8178. /* A component may have been multiplied (in linear space) by the
  8179. * alpha value, 'compose' says whether this is relevant.
  8180. */
  8181. if (compose || pass != 0)
  8182. {
  8183. /* If any form of composition is being done report our
  8184. * calculated linear value here (the code above doesn't record
  8185. * the input value before composition is performed, so what
  8186. * gets reported is the value after composition.)
  8187. */
  8188. if (use_input || pass != 0)
  8189. {
  8190. if (vi->file_inverse > 0)
  8191. {
  8192. pos = safecat(msg, sizeof msg, pos, "^");
  8193. pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
  8194. }
  8195. else
  8196. pos = safecat(msg, sizeof msg, pos, "[linear]");
  8197. pos = safecat(msg, sizeof msg, pos, "*(alpha)");
  8198. pos = safecatd(msg, sizeof msg, pos, alpha, precision);
  8199. }
  8200. /* Now record the *linear* background value if it was used
  8201. * (this function is not passed the original, non-linear,
  8202. * value but it is contained in the test name.)
  8203. */
  8204. if (use_background)
  8205. {
  8206. pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
  8207. pos = safecat(msg, sizeof msg, pos, "(background)");
  8208. pos = safecatd(msg, sizeof msg, pos, background, precision);
  8209. pos = safecat(msg, sizeof msg, pos, "*");
  8210. pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
  8211. }
  8212. }
  8213. /* Report the calculated value (input_sample) and the linearized
  8214. * libpng value (output) unless this is just a component gamma
  8215. * correction.
  8216. */
  8217. if (compose || alpha < 0 || pass != 0)
  8218. {
  8219. pos = safecat(msg, sizeof msg, pos,
  8220. pass != 0 ? " =\n\t" : " = ");
  8221. pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
  8222. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  8223. pos = safecatd(msg, sizeof msg, pos, output, precision);
  8224. pos = safecat(msg, sizeof msg, pos, ")");
  8225. /* Finally report the output gamma encoding, if any. */
  8226. if (output_is_encoded)
  8227. {
  8228. pos = safecat(msg, sizeof msg, pos, " ^");
  8229. pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
  8230. pos = safecat(msg, sizeof msg, pos, "(to screen) =");
  8231. }
  8232. else
  8233. pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
  8234. }
  8235. if ((!compose && alpha >= 0) || pass != 0)
  8236. {
  8237. if (pass != 0) /* logging */
  8238. pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
  8239. /* This is the non-composition case, the internal linear
  8240. * values are irrelevant (though the log below will reveal
  8241. * them.) Output a much shorter warning/error message and report
  8242. * the overall gamma correction.
  8243. */
  8244. if (vi->gamma_correction > 0)
  8245. {
  8246. pos = safecat(msg, sizeof msg, pos, " ^");
  8247. pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
  8248. pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
  8249. }
  8250. else
  8251. pos = safecat(msg, sizeof msg, pos,
  8252. " [no gamma correction] =");
  8253. if (pass != 0)
  8254. pos = safecat(msg, sizeof msg, pos, "]");
  8255. }
  8256. /* This is our calculated encoded_sample which should (but does
  8257. * not) match od:
  8258. */
  8259. pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
  8260. pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
  8261. pos = safecat(msg, sizeof msg, pos, " < ");
  8262. pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
  8263. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  8264. pos = safecatn(msg, sizeof msg, pos, od);
  8265. pos = safecat(msg, sizeof msg, pos, ")");
  8266. pos = safecat(msg, sizeof msg, pos, "/");
  8267. pos = safecatn(msg, sizeof msg, pos, outmax);
  8268. pos = safecat(msg, sizeof msg, pos, " < ");
  8269. pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
  8270. if (pass == 0) /* The error condition */
  8271. {
  8272. # ifdef PNG_WARNINGS_SUPPORTED
  8273. png_warning(vi->pp, msg);
  8274. # else
  8275. store_warning(vi->pp, msg);
  8276. # endif
  8277. }
  8278. else /* logging this value */
  8279. store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
  8280. }
  8281. }
  8282. }
  8283. return i;
  8284. }
  8285. static void
  8286. gamma_image_validate(gamma_display *dp, png_const_structp pp,
  8287. png_infop pi)
  8288. {
  8289. /* Get some constants derived from the input and output file formats: */
  8290. const png_store* const ps = dp->this.ps;
  8291. const png_byte in_ct = dp->this.colour_type;
  8292. const png_byte in_bd = dp->this.bit_depth;
  8293. const png_uint_32 w = dp->this.w;
  8294. const png_uint_32 h = dp->this.h;
  8295. const size_t cbRow = dp->this.cbRow;
  8296. const png_byte out_ct = png_get_color_type(pp, pi);
  8297. const png_byte out_bd = png_get_bit_depth(pp, pi);
  8298. /* There are three sources of error, firstly the quantization in the
  8299. * file encoding, determined by sbit and/or the file depth, secondly
  8300. * the output (screen) gamma and thirdly the output file encoding.
  8301. *
  8302. * Since this API receives the screen and file gamma in double
  8303. * precision it is possible to calculate an exact answer given an input
  8304. * pixel value. Therefore we assume that the *input* value is exact -
  8305. * sample/maxsample - calculate the corresponding gamma corrected
  8306. * output to the limits of double precision arithmetic and compare with
  8307. * what libpng returns.
  8308. *
  8309. * Since the library must quantize the output to 8 or 16 bits there is
  8310. * a fundamental limit on the accuracy of the output of +/-.5 - this
  8311. * quantization limit is included in addition to the other limits
  8312. * specified by the paramaters to the API. (Effectively, add .5
  8313. * everywhere.)
  8314. *
  8315. * The behavior of the 'sbit' paramter is defined by section 12.5
  8316. * (sample depth scaling) of the PNG spec. That section forces the
  8317. * decoder to assume that the PNG values have been scaled if sBIT is
  8318. * present:
  8319. *
  8320. * png-sample = floor( input-sample * (max-out/max-in) + .5);
  8321. *
  8322. * This means that only a subset of the possible PNG values should
  8323. * appear in the input. However, the spec allows the encoder to use a
  8324. * variety of approximations to the above and doesn't require any
  8325. * restriction of the values produced.
  8326. *
  8327. * Nevertheless the spec requires that the upper 'sBIT' bits of the
  8328. * value stored in a PNG file be the original sample bits.
  8329. * Consequently the code below simply scales the top sbit bits by
  8330. * (1<<sbit)-1 to obtain an original sample value.
  8331. *
  8332. * Because there is limited precision in the input it is arguable that
  8333. * an acceptable result is any valid result from input-.5 to input+.5.
  8334. * The basic tests below do not do this, however if 'use_input_precision'
  8335. * is set a subsequent test is performed above.
  8336. */
  8337. const unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
  8338. int processing;
  8339. png_uint_32 y;
  8340. const store_palette_entry *in_palette = dp->this.palette;
  8341. const int in_is_transparent = dp->this.is_transparent;
  8342. int process_tRNS;
  8343. int out_npalette = -1;
  8344. int out_is_transparent = 0; /* Just refers to the palette case */
  8345. store_palette out_palette;
  8346. validate_info vi;
  8347. /* Check for row overwrite errors */
  8348. store_image_check(dp->this.ps, pp, 0);
  8349. /* Supply the input and output sample depths here - 8 for an indexed image,
  8350. * otherwise the bit depth.
  8351. */
  8352. init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
  8353. processing = (vi.gamma_correction > 0 && !dp->threshold_test)
  8354. || in_bd != out_bd || in_ct != out_ct || vi.do_background;
  8355. process_tRNS = dp->this.has_tRNS && vi.do_background;
  8356. /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
  8357. * the palette there is no way of finding out, because libpng fails to
  8358. * update the palette on png_read_update_info. Indeed, libpng doesn't
  8359. * even do the required work until much later, when it doesn't have any
  8360. * info pointer. Oops. For the moment 'processing' is turned off if
  8361. * out_ct is palette.
  8362. */
  8363. if (in_ct == 3 && out_ct == 3)
  8364. processing = 0;
  8365. if (processing && out_ct == 3)
  8366. out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
  8367. for (y=0; y<h; ++y)
  8368. {
  8369. png_const_bytep pRow = store_image_row(ps, pp, 0, y);
  8370. png_byte std[STANDARD_ROWMAX];
  8371. transform_row(pp, std, in_ct, in_bd, y);
  8372. if (processing)
  8373. {
  8374. unsigned int x;
  8375. for (x=0; x<w; ++x)
  8376. {
  8377. double alpha = 1; /* serves as a flag value */
  8378. /* Record the palette index for index images. */
  8379. const unsigned int in_index =
  8380. in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256;
  8381. const unsigned int out_index =
  8382. out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256;
  8383. /* Handle input alpha - png_set_background will cause the output
  8384. * alpha to disappear so there is nothing to check.
  8385. */
  8386. if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 ||
  8387. (in_ct == 3 && in_is_transparent))
  8388. {
  8389. const unsigned int input_alpha = in_ct == 3 ?
  8390. dp->this.palette[in_index].alpha :
  8391. sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0);
  8392. unsigned int output_alpha = 65536 /* as a flag value */;
  8393. if (out_ct == 3)
  8394. {
  8395. if (out_is_transparent)
  8396. output_alpha = out_palette[out_index].alpha;
  8397. }
  8398. else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
  8399. output_alpha = sample(pRow, out_ct, out_bd, x,
  8400. samples_per_pixel, 0, 0);
  8401. if (output_alpha != 65536)
  8402. alpha = gamma_component_validate("alpha", &vi, input_alpha,
  8403. output_alpha, -1/*alpha*/, 0/*background*/);
  8404. else /* no alpha in output */
  8405. {
  8406. /* This is a copy of the calculation of 'i' above in order to
  8407. * have the alpha value to use in the background calculation.
  8408. */
  8409. alpha = input_alpha >> vi.isbit_shift;
  8410. alpha /= vi.sbit_max;
  8411. }
  8412. }
  8413. else if (process_tRNS)
  8414. {
  8415. /* alpha needs to be set appropriately for this pixel, it is
  8416. * currently 1 and needs to be 0 for an input pixel which matches
  8417. * the values in tRNS.
  8418. */
  8419. switch (in_ct)
  8420. {
  8421. case 0: /* gray */
  8422. if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
  8423. dp->this.transparent.red)
  8424. alpha = 0;
  8425. break;
  8426. case 2: /* RGB */
  8427. if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
  8428. dp->this.transparent.red &&
  8429. sample(std, in_ct, in_bd, x, 1, 0, 0) ==
  8430. dp->this.transparent.green &&
  8431. sample(std, in_ct, in_bd, x, 2, 0, 0) ==
  8432. dp->this.transparent.blue)
  8433. alpha = 0;
  8434. break;
  8435. default:
  8436. break;
  8437. }
  8438. }
  8439. /* Handle grayscale or RGB components. */
  8440. if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
  8441. (void)gamma_component_validate("gray", &vi,
  8442. sample(std, in_ct, in_bd, x, 0, 0, 0),
  8443. sample(pRow, out_ct, out_bd, x, 0, 0, 0),
  8444. alpha/*component*/, vi.background_red);
  8445. else /* RGB or palette */
  8446. {
  8447. (void)gamma_component_validate("red", &vi,
  8448. in_ct == 3 ? in_palette[in_index].red :
  8449. sample(std, in_ct, in_bd, x, 0, 0, 0),
  8450. out_ct == 3 ? out_palette[out_index].red :
  8451. sample(pRow, out_ct, out_bd, x, 0, 0, 0),
  8452. alpha/*component*/, vi.background_red);
  8453. (void)gamma_component_validate("green", &vi,
  8454. in_ct == 3 ? in_palette[in_index].green :
  8455. sample(std, in_ct, in_bd, x, 1, 0, 0),
  8456. out_ct == 3 ? out_palette[out_index].green :
  8457. sample(pRow, out_ct, out_bd, x, 1, 0, 0),
  8458. alpha/*component*/, vi.background_green);
  8459. (void)gamma_component_validate("blue", &vi,
  8460. in_ct == 3 ? in_palette[in_index].blue :
  8461. sample(std, in_ct, in_bd, x, 2, 0, 0),
  8462. out_ct == 3 ? out_palette[out_index].blue :
  8463. sample(pRow, out_ct, out_bd, x, 2, 0, 0),
  8464. alpha/*component*/, vi.background_blue);
  8465. }
  8466. }
  8467. }
  8468. else if (memcmp(std, pRow, cbRow) != 0)
  8469. {
  8470. char msg[64];
  8471. /* No transform is expected on the threshold tests. */
  8472. sprintf(msg, "gamma: below threshold row %lu changed",
  8473. (unsigned long)y);
  8474. png_error(pp, msg);
  8475. }
  8476. } /* row (y) loop */
  8477. dp->this.ps->validated = 1;
  8478. }
  8479. static void PNGCBAPI
  8480. gamma_end(png_structp ppIn, png_infop pi)
  8481. {
  8482. png_const_structp pp = ppIn;
  8483. gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
  8484. if (!dp->this.speed)
  8485. gamma_image_validate(dp, pp, pi);
  8486. else
  8487. dp->this.ps->validated = 1;
  8488. }
  8489. /* A single test run checking a gamma transformation.
  8490. *
  8491. * maxabs: maximum absolute error as a fraction
  8492. * maxout: maximum output error in the output units
  8493. * maxpc: maximum percentage error (as a percentage)
  8494. */
  8495. static void
  8496. gamma_test(png_modifier *pmIn, const png_byte colour_typeIn,
  8497. const png_byte bit_depthIn, const int palette_numberIn,
  8498. const int interlace_typeIn,
  8499. const double file_gammaIn, const double screen_gammaIn,
  8500. const png_byte sbitIn, const int threshold_testIn,
  8501. const char *name,
  8502. const int use_input_precisionIn, const int scale16In,
  8503. const int expand16In, const int do_backgroundIn,
  8504. const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
  8505. {
  8506. gamma_display d;
  8507. context(&pmIn->this, fault);
  8508. gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
  8509. palette_numberIn, interlace_typeIn, 0, 0, 0),
  8510. file_gammaIn, screen_gammaIn, sbitIn,
  8511. threshold_testIn, use_input_precisionIn, scale16In,
  8512. expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
  8513. Try
  8514. {
  8515. png_structp pp;
  8516. png_infop pi;
  8517. gama_modification gama_mod;
  8518. srgb_modification srgb_mod;
  8519. sbit_modification sbit_mod;
  8520. /* For the moment don't use the png_modifier support here. */
  8521. d.pm->encoding_counter = 0;
  8522. modifier_set_encoding(d.pm); /* Just resets everything */
  8523. d.pm->current_gamma = d.file_gamma;
  8524. /* Make an appropriate modifier to set the PNG file gamma to the
  8525. * given gamma value and the sBIT chunk to the given precision.
  8526. */
  8527. d.pm->modifications = NULL;
  8528. gama_modification_init(&gama_mod, d.pm, d.file_gamma);
  8529. srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
  8530. if (d.sbit > 0)
  8531. sbit_modification_init(&sbit_mod, d.pm, d.sbit);
  8532. modification_reset(d.pm->modifications);
  8533. /* Get a png_struct for reading the image. */
  8534. pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
  8535. standard_palette_init(&d.this);
  8536. /* Introduce the correct read function. */
  8537. if (d.pm->this.progressive)
  8538. {
  8539. /* Share the row function with the standard implementation. */
  8540. png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
  8541. gamma_end);
  8542. /* Now feed data into the reader until we reach the end: */
  8543. modifier_progressive_read(d.pm, pp, pi);
  8544. }
  8545. else
  8546. {
  8547. /* modifier_read expects a png_modifier* */
  8548. png_set_read_fn(pp, d.pm, modifier_read);
  8549. /* Check the header values: */
  8550. png_read_info(pp, pi);
  8551. /* Process the 'info' requirements. Only one image is generated */
  8552. gamma_info_imp(&d, pp, pi);
  8553. sequential_row(&d.this, pp, pi, -1, 0);
  8554. if (!d.this.speed)
  8555. gamma_image_validate(&d, pp, pi);
  8556. else
  8557. d.this.ps->validated = 1;
  8558. }
  8559. modifier_reset(d.pm);
  8560. if (d.pm->log && !d.threshold_test && !d.this.speed)
  8561. fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
  8562. d.this.bit_depth, colour_types[d.this.colour_type], name,
  8563. d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
  8564. /* Log the summary values too. */
  8565. if (d.this.colour_type == 0 || d.this.colour_type == 4)
  8566. {
  8567. switch (d.this.bit_depth)
  8568. {
  8569. case 1:
  8570. break;
  8571. case 2:
  8572. if (d.maxerrout > d.pm->error_gray_2)
  8573. d.pm->error_gray_2 = d.maxerrout;
  8574. break;
  8575. case 4:
  8576. if (d.maxerrout > d.pm->error_gray_4)
  8577. d.pm->error_gray_4 = d.maxerrout;
  8578. break;
  8579. case 8:
  8580. if (d.maxerrout > d.pm->error_gray_8)
  8581. d.pm->error_gray_8 = d.maxerrout;
  8582. break;
  8583. case 16:
  8584. if (d.maxerrout > d.pm->error_gray_16)
  8585. d.pm->error_gray_16 = d.maxerrout;
  8586. break;
  8587. default:
  8588. png_error(pp, "bad bit depth (internal: 1)");
  8589. }
  8590. }
  8591. else if (d.this.colour_type == 2 || d.this.colour_type == 6)
  8592. {
  8593. switch (d.this.bit_depth)
  8594. {
  8595. case 8:
  8596. if (d.maxerrout > d.pm->error_color_8)
  8597. d.pm->error_color_8 = d.maxerrout;
  8598. break;
  8599. case 16:
  8600. if (d.maxerrout > d.pm->error_color_16)
  8601. d.pm->error_color_16 = d.maxerrout;
  8602. break;
  8603. default:
  8604. png_error(pp, "bad bit depth (internal: 2)");
  8605. }
  8606. }
  8607. else if (d.this.colour_type == 3)
  8608. {
  8609. if (d.maxerrout > d.pm->error_indexed)
  8610. d.pm->error_indexed = d.maxerrout;
  8611. }
  8612. }
  8613. Catch(fault)
  8614. modifier_reset(voidcast(png_modifier*,(void*)fault));
  8615. }
  8616. static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
  8617. png_byte bit_depth, int interlace_type, double file_gamma,
  8618. double screen_gamma)
  8619. {
  8620. size_t pos = 0;
  8621. char name[64];
  8622. pos = safecat(name, sizeof name, pos, "threshold ");
  8623. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  8624. pos = safecat(name, sizeof name, pos, "/");
  8625. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  8626. (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
  8627. file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
  8628. 0 /*no input precision*/,
  8629. 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
  8630. 0 /*no background gamma*/);
  8631. }
  8632. static void
  8633. perform_gamma_threshold_tests(png_modifier *pm)
  8634. {
  8635. png_byte colour_type = 0;
  8636. png_byte bit_depth = 0;
  8637. unsigned int palette_number = 0;
  8638. /* Don't test more than one instance of each palette - it's pointless, in
  8639. * fact this test is somewhat excessive since libpng doesn't make this
  8640. * decision based on colour type or bit depth!
  8641. *
  8642. * CHANGED: now test two palettes and, as a side effect, images with and
  8643. * without tRNS.
  8644. */
  8645. while (next_format(&colour_type, &bit_depth, &palette_number,
  8646. pm->test_lbg_gamma_threshold, pm->test_tRNS))
  8647. if (palette_number < 2)
  8648. {
  8649. double test_gamma = 1.0;
  8650. while (test_gamma >= .4)
  8651. {
  8652. /* There's little point testing the interlacing vs non-interlacing,
  8653. * but this can be set from the command line.
  8654. */
  8655. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  8656. test_gamma, 1/test_gamma);
  8657. test_gamma *= .95;
  8658. }
  8659. /* And a special test for sRGB */
  8660. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  8661. .45455, 2.2);
  8662. if (fail(pm))
  8663. return;
  8664. }
  8665. }
  8666. static void gamma_transform_test(png_modifier *pm,
  8667. const png_byte colour_type, const png_byte bit_depth,
  8668. const int palette_number,
  8669. const int interlace_type, const double file_gamma,
  8670. const double screen_gamma, const png_byte sbit,
  8671. const int use_input_precision, const int scale16)
  8672. {
  8673. size_t pos = 0;
  8674. char name[64];
  8675. if (sbit != bit_depth && sbit != 0)
  8676. {
  8677. pos = safecat(name, sizeof name, pos, "sbit(");
  8678. pos = safecatn(name, sizeof name, pos, sbit);
  8679. pos = safecat(name, sizeof name, pos, ") ");
  8680. }
  8681. else
  8682. pos = safecat(name, sizeof name, pos, "gamma ");
  8683. if (scale16)
  8684. pos = safecat(name, sizeof name, pos, "16to8 ");
  8685. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  8686. pos = safecat(name, sizeof name, pos, "->");
  8687. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  8688. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  8689. file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
  8690. scale16, pm->test_gamma_expand16, 0 , 0, 0);
  8691. }
  8692. static void perform_gamma_transform_tests(png_modifier *pm)
  8693. {
  8694. png_byte colour_type = 0;
  8695. png_byte bit_depth = 0;
  8696. unsigned int palette_number = 0;
  8697. while (next_format(&colour_type, &bit_depth, &palette_number,
  8698. pm->test_lbg_gamma_transform, pm->test_tRNS))
  8699. {
  8700. unsigned int i, j;
  8701. for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
  8702. if (i != j)
  8703. {
  8704. gamma_transform_test(pm, colour_type, bit_depth, palette_number,
  8705. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
  8706. pm->use_input_precision, 0 /*do not scale16*/);
  8707. if (fail(pm))
  8708. return;
  8709. }
  8710. }
  8711. }
  8712. static void perform_gamma_sbit_tests(png_modifier *pm)
  8713. {
  8714. png_byte sbit;
  8715. /* The only interesting cases are colour and grayscale, alpha is ignored here
  8716. * for overall speed. Only bit depths where sbit is less than the bit depth
  8717. * are tested.
  8718. */
  8719. for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
  8720. {
  8721. png_byte colour_type = 0, bit_depth = 0;
  8722. unsigned int npalette = 0;
  8723. while (next_format(&colour_type, &bit_depth, &npalette,
  8724. pm->test_lbg_gamma_sbit, pm->test_tRNS))
  8725. if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
  8726. ((colour_type == 3 && sbit < 8) ||
  8727. (colour_type != 3 && sbit < bit_depth)))
  8728. {
  8729. unsigned int i;
  8730. for (i=0; i<pm->ngamma_tests; ++i)
  8731. {
  8732. unsigned int j;
  8733. for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
  8734. {
  8735. gamma_transform_test(pm, colour_type, bit_depth, npalette,
  8736. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  8737. sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
  8738. if (fail(pm))
  8739. return;
  8740. }
  8741. }
  8742. }
  8743. }
  8744. }
  8745. /* Note that this requires a 16 bit source image but produces 8 bit output, so
  8746. * we only need the 16bit write support, but the 16 bit images are only
  8747. * generated if DO_16BIT is defined.
  8748. */
  8749. #ifdef DO_16BIT
  8750. static void perform_gamma_scale16_tests(png_modifier *pm)
  8751. {
  8752. # ifndef PNG_MAX_GAMMA_8
  8753. # define PNG_MAX_GAMMA_8 11
  8754. # endif
  8755. # if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700
  8756. # define SBIT_16_TO_8 PNG_MAX_GAMMA_8
  8757. # else
  8758. # define SBIT_16_TO_8 16
  8759. # endif
  8760. /* Include the alpha cases here. Note that sbit matches the internal value
  8761. * used by the library - otherwise we will get spurious errors from the
  8762. * internal sbit style approximation.
  8763. *
  8764. * The threshold test is here because otherwise the 16 to 8 conversion will
  8765. * proceed *without* gamma correction, and the tests above will fail (but not
  8766. * by much) - this could be fixed, it only appears with the -g option.
  8767. */
  8768. unsigned int i, j;
  8769. for (i=0; i<pm->ngamma_tests; ++i)
  8770. {
  8771. for (j=0; j<pm->ngamma_tests; ++j)
  8772. {
  8773. if (i != j &&
  8774. fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
  8775. {
  8776. gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
  8777. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  8778. pm->use_input_precision_16to8, 1 /*scale16*/);
  8779. if (fail(pm))
  8780. return;
  8781. gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
  8782. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  8783. pm->use_input_precision_16to8, 1 /*scale16*/);
  8784. if (fail(pm))
  8785. return;
  8786. gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
  8787. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  8788. pm->use_input_precision_16to8, 1 /*scale16*/);
  8789. if (fail(pm))
  8790. return;
  8791. gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
  8792. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  8793. pm->use_input_precision_16to8, 1 /*scale16*/);
  8794. if (fail(pm))
  8795. return;
  8796. }
  8797. }
  8798. }
  8799. }
  8800. #endif /* 16 to 8 bit conversion */
  8801. #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
  8802. defined(PNG_READ_ALPHA_MODE_SUPPORTED)
  8803. static void gamma_composition_test(png_modifier *pm,
  8804. const png_byte colour_type, const png_byte bit_depth,
  8805. const int palette_number,
  8806. const int interlace_type, const double file_gamma,
  8807. const double screen_gamma,
  8808. const int use_input_precision, const int do_background,
  8809. const int expand_16)
  8810. {
  8811. size_t pos = 0;
  8812. png_const_charp base;
  8813. double bg;
  8814. char name[128];
  8815. png_color_16 background;
  8816. /* Make up a name and get an appropriate background gamma value. */
  8817. switch (do_background)
  8818. {
  8819. default:
  8820. base = "";
  8821. bg = 4; /* should not be used */
  8822. break;
  8823. case PNG_BACKGROUND_GAMMA_SCREEN:
  8824. base = " bckg(Screen):";
  8825. bg = 1/screen_gamma;
  8826. break;
  8827. case PNG_BACKGROUND_GAMMA_FILE:
  8828. base = " bckg(File):";
  8829. bg = file_gamma;
  8830. break;
  8831. case PNG_BACKGROUND_GAMMA_UNIQUE:
  8832. base = " bckg(Unique):";
  8833. /* This tests the handling of a unique value, the math is such that the
  8834. * value tends to be <1, but is neither screen nor file (even if they
  8835. * match!)
  8836. */
  8837. bg = (file_gamma + screen_gamma) / 3;
  8838. break;
  8839. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8840. case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
  8841. base = " alpha(PNG)";
  8842. bg = 4; /* should not be used */
  8843. break;
  8844. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  8845. base = " alpha(Porter-Duff)";
  8846. bg = 4; /* should not be used */
  8847. break;
  8848. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  8849. base = " alpha(Optimized)";
  8850. bg = 4; /* should not be used */
  8851. break;
  8852. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  8853. base = " alpha(Broken)";
  8854. bg = 4; /* should not be used */
  8855. break;
  8856. #endif
  8857. }
  8858. /* Use random background values - the background is always presented in the
  8859. * output space (8 or 16 bit components).
  8860. */
  8861. if (expand_16 || bit_depth == 16)
  8862. {
  8863. png_uint_32 r = random_32();
  8864. background.red = (png_uint_16)r;
  8865. background.green = (png_uint_16)(r >> 16);
  8866. r = random_32();
  8867. background.blue = (png_uint_16)r;
  8868. background.gray = (png_uint_16)(r >> 16);
  8869. /* In earlier libpng versions, those where DIGITIZE is set, any background
  8870. * gamma correction in the expand16 case was done using 8-bit gamma
  8871. * correction tables, resulting in larger errors. To cope with those
  8872. * cases use a 16-bit background value which will handle this gamma
  8873. * correction.
  8874. */
  8875. # if DIGITIZE
  8876. if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
  8877. do_background == PNG_BACKGROUND_GAMMA_FILE) &&
  8878. fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
  8879. {
  8880. /* The background values will be looked up in an 8-bit table to do
  8881. * the gamma correction, so only select values which are an exact
  8882. * match for the 8-bit table entries:
  8883. */
  8884. background.red = (png_uint_16)((background.red >> 8) * 257);
  8885. background.green = (png_uint_16)((background.green >> 8) * 257);
  8886. background.blue = (png_uint_16)((background.blue >> 8) * 257);
  8887. background.gray = (png_uint_16)((background.gray >> 8) * 257);
  8888. }
  8889. # endif
  8890. }
  8891. else /* 8 bit colors */
  8892. {
  8893. png_uint_32 r = random_32();
  8894. background.red = (png_byte)r;
  8895. background.green = (png_byte)(r >> 8);
  8896. background.blue = (png_byte)(r >> 16);
  8897. background.gray = (png_byte)(r >> 24);
  8898. }
  8899. background.index = 193; /* rgb(193,193,193) to detect errors */
  8900. if (!(colour_type & PNG_COLOR_MASK_COLOR))
  8901. {
  8902. /* Because, currently, png_set_background is always called with
  8903. * 'need_expand' false in this case and because the gamma test itself
  8904. * doesn't cause an expand to 8-bit for lower bit depths the colour must
  8905. * be reduced to the correct range.
  8906. */
  8907. if (bit_depth < 8)
  8908. background.gray &= (png_uint_16)((1U << bit_depth)-1);
  8909. /* Grayscale input, we do not convert to RGB (TBD), so we must set the
  8910. * background to gray - else libpng seems to fail.
  8911. */
  8912. background.red = background.green = background.blue = background.gray;
  8913. }
  8914. pos = safecat(name, sizeof name, pos, "gamma ");
  8915. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  8916. pos = safecat(name, sizeof name, pos, "->");
  8917. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  8918. pos = safecat(name, sizeof name, pos, base);
  8919. if (do_background < ALPHA_MODE_OFFSET)
  8920. {
  8921. /* Include the background color and gamma in the name: */
  8922. pos = safecat(name, sizeof name, pos, "(");
  8923. /* This assumes no expand gray->rgb - the current code won't handle that!
  8924. */
  8925. if (colour_type & PNG_COLOR_MASK_COLOR)
  8926. {
  8927. pos = safecatn(name, sizeof name, pos, background.red);
  8928. pos = safecat(name, sizeof name, pos, ",");
  8929. pos = safecatn(name, sizeof name, pos, background.green);
  8930. pos = safecat(name, sizeof name, pos, ",");
  8931. pos = safecatn(name, sizeof name, pos, background.blue);
  8932. }
  8933. else
  8934. pos = safecatn(name, sizeof name, pos, background.gray);
  8935. pos = safecat(name, sizeof name, pos, ")^");
  8936. pos = safecatd(name, sizeof name, pos, bg, 3);
  8937. }
  8938. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  8939. file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
  8940. 0/*strip 16*/, expand_16, do_background, &background, bg);
  8941. }
  8942. static void
  8943. perform_gamma_composition_tests(png_modifier *pm, int do_background,
  8944. int expand_16)
  8945. {
  8946. png_byte colour_type = 0;
  8947. png_byte bit_depth = 0;
  8948. unsigned int palette_number = 0;
  8949. /* Skip the non-alpha cases - there is no setting of a transparency colour at
  8950. * present.
  8951. *
  8952. * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
  8953. * however the palette case fails miserably so is commented out below.
  8954. */
  8955. while (next_format(&colour_type, &bit_depth, &palette_number,
  8956. pm->test_lbg_gamma_composition, pm->test_tRNS))
  8957. if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
  8958. #if 0 /* TODO: FIXME */
  8959. /*TODO: FIXME: this should work */
  8960. || colour_type == 3
  8961. #endif
  8962. || (colour_type != 3 && palette_number != 0))
  8963. {
  8964. unsigned int i, j;
  8965. /* Don't skip the i==j case here - it's relevant. */
  8966. for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
  8967. {
  8968. gamma_composition_test(pm, colour_type, bit_depth, palette_number,
  8969. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  8970. pm->use_input_precision, do_background, expand_16);
  8971. if (fail(pm))
  8972. return;
  8973. }
  8974. }
  8975. }
  8976. #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
  8977. static void
  8978. init_gamma_errors(png_modifier *pm)
  8979. {
  8980. /* Use -1 to catch tests that were not actually run */
  8981. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
  8982. pm->error_color_8 = -1.;
  8983. pm->error_indexed = -1.;
  8984. pm->error_gray_16 = pm->error_color_16 = -1.;
  8985. }
  8986. static void
  8987. print_one(const char *leader, double err)
  8988. {
  8989. if (err != -1.)
  8990. printf(" %s %.5f\n", leader, err);
  8991. }
  8992. static void
  8993. summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
  8994. int indexed)
  8995. {
  8996. fflush(stderr);
  8997. if (who)
  8998. printf("\nGamma correction with %s:\n", who);
  8999. else
  9000. printf("\nBasic gamma correction:\n");
  9001. if (low_bit_depth)
  9002. {
  9003. print_one(" 2 bit gray: ", pm->error_gray_2);
  9004. print_one(" 4 bit gray: ", pm->error_gray_4);
  9005. print_one(" 8 bit gray: ", pm->error_gray_8);
  9006. print_one(" 8 bit color:", pm->error_color_8);
  9007. if (indexed)
  9008. print_one(" indexed: ", pm->error_indexed);
  9009. }
  9010. print_one("16 bit gray: ", pm->error_gray_16);
  9011. print_one("16 bit color:", pm->error_color_16);
  9012. fflush(stdout);
  9013. }
  9014. static void
  9015. perform_gamma_test(png_modifier *pm, int summary)
  9016. {
  9017. /*TODO: remove this*/
  9018. /* Save certain values for the temporary overrides below. */
  9019. unsigned int calculations_use_input_precision =
  9020. pm->calculations_use_input_precision;
  9021. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  9022. double maxout8 = pm->maxout8;
  9023. # endif
  9024. /* First some arbitrary no-transform tests: */
  9025. if (!pm->this.speed && pm->test_gamma_threshold)
  9026. {
  9027. perform_gamma_threshold_tests(pm);
  9028. if (fail(pm))
  9029. return;
  9030. }
  9031. /* Now some real transforms. */
  9032. if (pm->test_gamma_transform)
  9033. {
  9034. if (summary)
  9035. {
  9036. fflush(stderr);
  9037. printf("Gamma correction error summary\n\n");
  9038. printf("The printed value is the maximum error in the pixel values\n");
  9039. printf("calculated by the libpng gamma correction code. The error\n");
  9040. printf("is calculated as the difference between the output pixel\n");
  9041. printf("value (always an integer) and the ideal value from the\n");
  9042. printf("libpng specification (typically not an integer).\n\n");
  9043. printf("Expect this value to be less than .5 for 8 bit formats,\n");
  9044. printf("less than 1 for formats with fewer than 8 bits and a small\n");
  9045. printf("number (typically less than 5) for the 16 bit formats.\n");
  9046. printf("For performance reasons the value for 16 bit formats\n");
  9047. printf("increases when the image file includes an sBIT chunk.\n");
  9048. fflush(stdout);
  9049. }
  9050. init_gamma_errors(pm);
  9051. /*TODO: remove this. Necessary because the current libpng
  9052. * implementation works in 8 bits:
  9053. */
  9054. if (pm->test_gamma_expand16)
  9055. pm->calculations_use_input_precision = 1;
  9056. perform_gamma_transform_tests(pm);
  9057. if (!calculations_use_input_precision)
  9058. pm->calculations_use_input_precision = 0;
  9059. if (summary)
  9060. summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/);
  9061. if (fail(pm))
  9062. return;
  9063. }
  9064. /* The sbit tests produce much larger errors: */
  9065. if (pm->test_gamma_sbit)
  9066. {
  9067. init_gamma_errors(pm);
  9068. perform_gamma_sbit_tests(pm);
  9069. if (summary)
  9070. summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
  9071. if (fail(pm))
  9072. return;
  9073. }
  9074. #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
  9075. if (pm->test_gamma_scale16)
  9076. {
  9077. /* The 16 to 8 bit strip operations: */
  9078. init_gamma_errors(pm);
  9079. perform_gamma_scale16_tests(pm);
  9080. if (summary)
  9081. {
  9082. fflush(stderr);
  9083. printf("\nGamma correction with 16 to 8 bit reduction:\n");
  9084. printf(" 16 bit gray: %.5f\n", pm->error_gray_16);
  9085. printf(" 16 bit color: %.5f\n", pm->error_color_16);
  9086. fflush(stdout);
  9087. }
  9088. if (fail(pm))
  9089. return;
  9090. }
  9091. #endif
  9092. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  9093. if (pm->test_gamma_background)
  9094. {
  9095. init_gamma_errors(pm);
  9096. /*TODO: remove this. Necessary because the current libpng
  9097. * implementation works in 8 bits:
  9098. */
  9099. if (pm->test_gamma_expand16)
  9100. {
  9101. pm->calculations_use_input_precision = 1;
  9102. pm->maxout8 = .499; /* because the 16 bit background is smashed */
  9103. }
  9104. perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
  9105. pm->test_gamma_expand16);
  9106. if (!calculations_use_input_precision)
  9107. pm->calculations_use_input_precision = 0;
  9108. pm->maxout8 = maxout8;
  9109. if (summary)
  9110. summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
  9111. if (fail(pm))
  9112. return;
  9113. }
  9114. #endif
  9115. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  9116. if (pm->test_gamma_alpha_mode)
  9117. {
  9118. int do_background;
  9119. init_gamma_errors(pm);
  9120. /*TODO: remove this. Necessary because the current libpng
  9121. * implementation works in 8 bits:
  9122. */
  9123. if (pm->test_gamma_expand16)
  9124. pm->calculations_use_input_precision = 1;
  9125. for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
  9126. do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
  9127. ++do_background)
  9128. perform_gamma_composition_tests(pm, do_background,
  9129. pm->test_gamma_expand16);
  9130. if (!calculations_use_input_precision)
  9131. pm->calculations_use_input_precision = 0;
  9132. if (summary)
  9133. summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
  9134. if (fail(pm))
  9135. return;
  9136. }
  9137. #endif
  9138. }
  9139. #endif /* PNG_READ_GAMMA_SUPPORTED */
  9140. #endif /* PNG_READ_SUPPORTED */
  9141. /* INTERLACE MACRO VALIDATION */
  9142. /* This is copied verbatim from the specification, it is simply the pass
  9143. * number in which each pixel in each 8x8 tile appears. The array must
  9144. * be indexed adam7[y][x] and notice that the pass numbers are based at
  9145. * 1, not 0 - the base libpng uses.
  9146. */
  9147. static const
  9148. png_byte adam7[8][8] =
  9149. {
  9150. { 1,6,4,6,2,6,4,6 },
  9151. { 7,7,7,7,7,7,7,7 },
  9152. { 5,6,5,6,5,6,5,6 },
  9153. { 7,7,7,7,7,7,7,7 },
  9154. { 3,6,4,6,3,6,4,6 },
  9155. { 7,7,7,7,7,7,7,7 },
  9156. { 5,6,5,6,5,6,5,6 },
  9157. { 7,7,7,7,7,7,7,7 }
  9158. };
  9159. /* This routine validates all the interlace support macros in png.h for
  9160. * a variety of valid PNG widths and heights. It uses a number of similarly
  9161. * named internal routines that feed off the above array.
  9162. */
  9163. static png_uint_32
  9164. png_pass_start_row(int pass)
  9165. {
  9166. int x, y;
  9167. ++pass;
  9168. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9169. return y;
  9170. return 0xf;
  9171. }
  9172. static png_uint_32
  9173. png_pass_start_col(int pass)
  9174. {
  9175. int x, y;
  9176. ++pass;
  9177. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9178. return x;
  9179. return 0xf;
  9180. }
  9181. static int
  9182. png_pass_row_shift(int pass)
  9183. {
  9184. int x, y, base=(-1), inc=8;
  9185. ++pass;
  9186. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9187. {
  9188. if (base == (-1))
  9189. base = y;
  9190. else if (base == y)
  9191. {}
  9192. else if (inc == y-base)
  9193. base=y;
  9194. else if (inc == 8)
  9195. inc = y-base, base=y;
  9196. else if (inc != y-base)
  9197. return 0xff; /* error - more than one 'inc' value! */
  9198. }
  9199. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  9200. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  9201. switch (inc)
  9202. {
  9203. case 2: return 1;
  9204. case 4: return 2;
  9205. case 8: return 3;
  9206. default: break;
  9207. }
  9208. /* error - unrecognized 'inc' */
  9209. return (inc << 8) + 0xfd;
  9210. }
  9211. static int
  9212. png_pass_col_shift(int pass)
  9213. {
  9214. int x, y, base=(-1), inc=8;
  9215. ++pass;
  9216. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9217. {
  9218. if (base == (-1))
  9219. base = x;
  9220. else if (base == x)
  9221. {}
  9222. else if (inc == x-base)
  9223. base=x;
  9224. else if (inc == 8)
  9225. inc = x-base, base=x;
  9226. else if (inc != x-base)
  9227. return 0xff; /* error - more than one 'inc' value! */
  9228. }
  9229. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  9230. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  9231. switch (inc)
  9232. {
  9233. case 1: return 0; /* pass 7 has all the columns */
  9234. case 2: return 1;
  9235. case 4: return 2;
  9236. case 8: return 3;
  9237. default: break;
  9238. }
  9239. /* error - unrecognized 'inc' */
  9240. return (inc << 8) + 0xfd;
  9241. }
  9242. static png_uint_32
  9243. png_row_from_pass_row(png_uint_32 yIn, int pass)
  9244. {
  9245. /* By examination of the array: */
  9246. switch (pass)
  9247. {
  9248. case 0: return yIn * 8;
  9249. case 1: return yIn * 8;
  9250. case 2: return yIn * 8 + 4;
  9251. case 3: return yIn * 4;
  9252. case 4: return yIn * 4 + 2;
  9253. case 5: return yIn * 2;
  9254. case 6: return yIn * 2 + 1;
  9255. default: break;
  9256. }
  9257. return 0xff; /* bad pass number */
  9258. }
  9259. static png_uint_32
  9260. png_col_from_pass_col(png_uint_32 xIn, int pass)
  9261. {
  9262. /* By examination of the array: */
  9263. switch (pass)
  9264. {
  9265. case 0: return xIn * 8;
  9266. case 1: return xIn * 8 + 4;
  9267. case 2: return xIn * 4;
  9268. case 3: return xIn * 4 + 2;
  9269. case 4: return xIn * 2;
  9270. case 5: return xIn * 2 + 1;
  9271. case 6: return xIn;
  9272. default: break;
  9273. }
  9274. return 0xff; /* bad pass number */
  9275. }
  9276. static int
  9277. png_row_in_interlace_pass(png_uint_32 y, int pass)
  9278. {
  9279. /* Is row 'y' in pass 'pass'? */
  9280. int x;
  9281. y &= 7;
  9282. ++pass;
  9283. for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9284. return 1;
  9285. return 0;
  9286. }
  9287. static int
  9288. png_col_in_interlace_pass(png_uint_32 x, int pass)
  9289. {
  9290. /* Is column 'x' in pass 'pass'? */
  9291. int y;
  9292. x &= 7;
  9293. ++pass;
  9294. for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9295. return 1;
  9296. return 0;
  9297. }
  9298. static png_uint_32
  9299. png_pass_rows(png_uint_32 height, int pass)
  9300. {
  9301. png_uint_32 tiles = height>>3;
  9302. png_uint_32 rows = 0;
  9303. unsigned int x, y;
  9304. height &= 7;
  9305. ++pass;
  9306. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9307. {
  9308. rows += tiles;
  9309. if (y < height) ++rows;
  9310. break; /* i.e. break the 'x', column, loop. */
  9311. }
  9312. return rows;
  9313. }
  9314. static png_uint_32
  9315. png_pass_cols(png_uint_32 width, int pass)
  9316. {
  9317. png_uint_32 tiles = width>>3;
  9318. png_uint_32 cols = 0;
  9319. unsigned int x, y;
  9320. width &= 7;
  9321. ++pass;
  9322. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9323. {
  9324. cols += tiles;
  9325. if (x < width) ++cols;
  9326. break; /* i.e. break the 'y', row, loop. */
  9327. }
  9328. return cols;
  9329. }
  9330. static void
  9331. perform_interlace_macro_validation(void)
  9332. {
  9333. /* The macros to validate, first those that depend only on pass:
  9334. *
  9335. * PNG_PASS_START_ROW(pass)
  9336. * PNG_PASS_START_COL(pass)
  9337. * PNG_PASS_ROW_SHIFT(pass)
  9338. * PNG_PASS_COL_SHIFT(pass)
  9339. */
  9340. int pass;
  9341. for (pass=0; pass<7; ++pass)
  9342. {
  9343. png_uint_32 m, f, v;
  9344. m = PNG_PASS_START_ROW(pass);
  9345. f = png_pass_start_row(pass);
  9346. if (m != f)
  9347. {
  9348. fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
  9349. exit(99);
  9350. }
  9351. m = PNG_PASS_START_COL(pass);
  9352. f = png_pass_start_col(pass);
  9353. if (m != f)
  9354. {
  9355. fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
  9356. exit(99);
  9357. }
  9358. m = PNG_PASS_ROW_SHIFT(pass);
  9359. f = png_pass_row_shift(pass);
  9360. if (m != f)
  9361. {
  9362. fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
  9363. exit(99);
  9364. }
  9365. m = PNG_PASS_COL_SHIFT(pass);
  9366. f = png_pass_col_shift(pass);
  9367. if (m != f)
  9368. {
  9369. fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
  9370. exit(99);
  9371. }
  9372. /* Macros that depend on the image or sub-image height too:
  9373. *
  9374. * PNG_PASS_ROWS(height, pass)
  9375. * PNG_PASS_COLS(width, pass)
  9376. * PNG_ROW_FROM_PASS_ROW(yIn, pass)
  9377. * PNG_COL_FROM_PASS_COL(xIn, pass)
  9378. * PNG_ROW_IN_INTERLACE_PASS(y, pass)
  9379. * PNG_COL_IN_INTERLACE_PASS(x, pass)
  9380. */
  9381. for (v=0;;)
  9382. {
  9383. /* First the base 0 stuff: */
  9384. m = PNG_ROW_FROM_PASS_ROW(v, pass);
  9385. f = png_row_from_pass_row(v, pass);
  9386. if (m != f)
  9387. {
  9388. fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
  9389. v, pass, m, f);
  9390. exit(99);
  9391. }
  9392. m = PNG_COL_FROM_PASS_COL(v, pass);
  9393. f = png_col_from_pass_col(v, pass);
  9394. if (m != f)
  9395. {
  9396. fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
  9397. v, pass, m, f);
  9398. exit(99);
  9399. }
  9400. m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
  9401. f = png_row_in_interlace_pass(v, pass);
  9402. if (m != f)
  9403. {
  9404. fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  9405. v, pass, m, f);
  9406. exit(99);
  9407. }
  9408. m = PNG_COL_IN_INTERLACE_PASS(v, pass);
  9409. f = png_col_in_interlace_pass(v, pass);
  9410. if (m != f)
  9411. {
  9412. fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  9413. v, pass, m, f);
  9414. exit(99);
  9415. }
  9416. /* Then the base 1 stuff: */
  9417. ++v;
  9418. m = PNG_PASS_ROWS(v, pass);
  9419. f = png_pass_rows(v, pass);
  9420. if (m != f)
  9421. {
  9422. fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
  9423. v, pass, m, f);
  9424. exit(99);
  9425. }
  9426. m = PNG_PASS_COLS(v, pass);
  9427. f = png_pass_cols(v, pass);
  9428. if (m != f)
  9429. {
  9430. fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
  9431. v, pass, m, f);
  9432. exit(99);
  9433. }
  9434. /* Move to the next v - the stepping algorithm starts skipping
  9435. * values above 1024.
  9436. */
  9437. if (v > 1024)
  9438. {
  9439. if (v == PNG_UINT_31_MAX)
  9440. break;
  9441. v = (v << 1) ^ v;
  9442. if (v >= PNG_UINT_31_MAX)
  9443. v = PNG_UINT_31_MAX-1;
  9444. }
  9445. }
  9446. }
  9447. }
  9448. /* Test color encodings. These values are back-calculated from the published
  9449. * chromaticities. The values are accurate to about 14 decimal places; 15 are
  9450. * given. These values are much more accurate than the ones given in the spec,
  9451. * which typically don't exceed 4 decimal places. This allows testing of the
  9452. * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid
  9453. * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
  9454. * more.)
  9455. *
  9456. * The png_modifier code assumes that encodings[0] is sRGB and treats it
  9457. * specially: do not change the first entry in this list!
  9458. */
  9459. static const color_encoding test_encodings[] =
  9460. {
  9461. /* sRGB: must be first in this list! */
  9462. /*gamma:*/ { 1/2.2,
  9463. /*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
  9464. /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
  9465. /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
  9466. /* Kodak ProPhoto (wide gamut) */
  9467. /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
  9468. /*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
  9469. /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
  9470. /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
  9471. /* Adobe RGB (1998) */
  9472. /*gamma:*/ { 1/(2+51./256),
  9473. /*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
  9474. /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
  9475. /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
  9476. /* Adobe Wide Gamut RGB */
  9477. /*gamma:*/ { 1/(2+51./256),
  9478. /*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
  9479. /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
  9480. /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
  9481. /* Fake encoding which selects just the green channel */
  9482. /*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */
  9483. /*red: */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 },
  9484. /*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 },
  9485. /*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} },
  9486. };
  9487. /* signal handler
  9488. *
  9489. * This attempts to trap signals and escape without crashing. It needs a
  9490. * context pointer so that it can throw an exception (call longjmp) to recover
  9491. * from the condition; this is handled by making the png_modifier used by 'main'
  9492. * into a global variable.
  9493. */
  9494. static png_modifier pm;
  9495. static void signal_handler(int signum)
  9496. {
  9497. size_t pos = 0;
  9498. char msg[64];
  9499. pos = safecat(msg, sizeof msg, pos, "caught signal: ");
  9500. switch (signum)
  9501. {
  9502. case SIGABRT:
  9503. pos = safecat(msg, sizeof msg, pos, "abort");
  9504. break;
  9505. case SIGFPE:
  9506. pos = safecat(msg, sizeof msg, pos, "floating point exception");
  9507. break;
  9508. case SIGILL:
  9509. pos = safecat(msg, sizeof msg, pos, "illegal instruction");
  9510. break;
  9511. case SIGINT:
  9512. pos = safecat(msg, sizeof msg, pos, "interrupt");
  9513. break;
  9514. case SIGSEGV:
  9515. pos = safecat(msg, sizeof msg, pos, "invalid memory access");
  9516. break;
  9517. case SIGTERM:
  9518. pos = safecat(msg, sizeof msg, pos, "termination request");
  9519. break;
  9520. default:
  9521. pos = safecat(msg, sizeof msg, pos, "unknown ");
  9522. pos = safecatn(msg, sizeof msg, pos, signum);
  9523. break;
  9524. }
  9525. store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
  9526. /* And finally throw an exception so we can keep going, unless this is
  9527. * SIGTERM in which case stop now.
  9528. */
  9529. if (signum != SIGTERM)
  9530. {
  9531. struct exception_context *the_exception_context =
  9532. &pm.this.exception_context;
  9533. Throw &pm.this;
  9534. }
  9535. else
  9536. exit(1);
  9537. }
  9538. /* main program */
  9539. int main(int argc, char **argv)
  9540. {
  9541. int summary = 1; /* Print the error summary at the end */
  9542. int memstats = 0; /* Print memory statistics at the end */
  9543. /* Create the given output file on success: */
  9544. const char *touch = NULL;
  9545. /* This is an array of standard gamma values (believe it or not I've seen
  9546. * every one of these mentioned somewhere.)
  9547. *
  9548. * In the following list the most useful values are first!
  9549. */
  9550. static double
  9551. gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
  9552. /* This records the command and arguments: */
  9553. size_t cp = 0;
  9554. char command[1024];
  9555. anon_context(&pm.this);
  9556. gnu_volatile(summary)
  9557. gnu_volatile(memstats)
  9558. gnu_volatile(touch)
  9559. /* Add appropriate signal handlers, just the ANSI specified ones: */
  9560. signal(SIGABRT, signal_handler);
  9561. signal(SIGFPE, signal_handler);
  9562. signal(SIGILL, signal_handler);
  9563. signal(SIGINT, signal_handler);
  9564. signal(SIGSEGV, signal_handler);
  9565. signal(SIGTERM, signal_handler);
  9566. #ifdef HAVE_FEENABLEEXCEPT
  9567. /* Only required to enable FP exceptions on platforms where they start off
  9568. * disabled; this is not necessary but if it is not done pngvalid will likely
  9569. * end up ignoring FP conditions that other platforms fault.
  9570. */
  9571. feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
  9572. #endif
  9573. modifier_init(&pm);
  9574. /* Preallocate the image buffer, because we know how big it needs to be,
  9575. * note that, for testing purposes, it is deliberately mis-aligned by tag
  9576. * bytes either side. All rows have an additional five bytes of padding for
  9577. * overwrite checking.
  9578. */
  9579. store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
  9580. /* Don't give argv[0], it's normally some horrible libtool string: */
  9581. cp = safecat(command, sizeof command, cp, "pngvalid");
  9582. /* Default to error on warning: */
  9583. pm.this.treat_warnings_as_errors = 1;
  9584. /* Default assume_16_bit_calculations appropriately; this tells the checking
  9585. * code that 16-bit arithmetic is used for 8-bit samples when it would make a
  9586. * difference.
  9587. */
  9588. pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
  9589. /* Currently 16 bit expansion happens at the end of the pipeline, so the
  9590. * calculations are done in the input bit depth not the output.
  9591. *
  9592. * TODO: fix this
  9593. */
  9594. pm.calculations_use_input_precision = 1U;
  9595. /* Store the test gammas */
  9596. pm.gammas = gammas;
  9597. pm.ngammas = ARRAY_SIZE(gammas);
  9598. pm.ngamma_tests = 0; /* default to off */
  9599. /* Low bit depth gray images don't do well in the gamma tests, until
  9600. * this is fixed turn them off for some gamma cases:
  9601. */
  9602. # ifdef PNG_WRITE_tRNS_SUPPORTED
  9603. pm.test_tRNS = 1;
  9604. # endif
  9605. pm.test_lbg = PNG_LIBPNG_VER >= 10600;
  9606. pm.test_lbg_gamma_threshold = 1;
  9607. pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
  9608. pm.test_lbg_gamma_sbit = 1;
  9609. pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700;
  9610. /* And the test encodings */
  9611. pm.encodings = test_encodings;
  9612. pm.nencodings = ARRAY_SIZE(test_encodings);
  9613. # if PNG_LIBPNG_VER < 10700
  9614. pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
  9615. # else
  9616. pm.sbitlow = 1U;
  9617. # endif
  9618. /* The following allows results to pass if they correspond to anything in the
  9619. * transformed range [input-.5,input+.5]; this is is required because of the
  9620. * way libpng treates the 16_TO_8 flag when building the gamma tables in
  9621. * releases up to 1.6.0.
  9622. *
  9623. * TODO: review this
  9624. */
  9625. pm.use_input_precision_16to8 = 1U;
  9626. pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
  9627. /* Some default values (set the behavior for 'make check' here).
  9628. * These values simply control the maximum error permitted in the gamma
  9629. * transformations. The practial limits for human perception are described
  9630. * below (the setting for maxpc16), however for 8 bit encodings it isn't
  9631. * possible to meet the accepted capabilities of human vision - i.e. 8 bit
  9632. * images can never be good enough, regardless of encoding.
  9633. */
  9634. pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
  9635. pm.maxabs8 = .00005; /* 1/20000 */
  9636. pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
  9637. pm.maxpc8 = .499; /* I.e., .499% fractional error */
  9638. pm.maxout16 = .499; /* Error in *encoded* value */
  9639. pm.maxabs16 = .00005;/* 1/20000 */
  9640. pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
  9641. # if PNG_LIBPNG_VER < 10700
  9642. pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
  9643. # else
  9644. pm.maxcalcG = 1./((1<<16)-1);
  9645. # endif
  9646. /* NOTE: this is a reasonable perceptual limit. We assume that humans can
  9647. * perceive light level differences of 1% over a 100:1 range, so we need to
  9648. * maintain 1 in 10000 accuracy (in linear light space), which is what the
  9649. * following guarantees. It also allows significantly higher errors at
  9650. * higher 16 bit values, which is important for performance. The actual
  9651. * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
  9652. * this is only allowed for values >38149 by the following:
  9653. */
  9654. pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
  9655. /* Now parse the command line options. */
  9656. while (--argc >= 1)
  9657. {
  9658. int catmore = 0; /* Set if the argument has an argument. */
  9659. /* Record each argument for posterity: */
  9660. cp = safecat(command, sizeof command, cp, " ");
  9661. cp = safecat(command, sizeof command, cp, *++argv);
  9662. if (strcmp(*argv, "-v") == 0)
  9663. pm.this.verbose = 1;
  9664. else if (strcmp(*argv, "-l") == 0)
  9665. pm.log = 1;
  9666. else if (strcmp(*argv, "-q") == 0)
  9667. summary = pm.this.verbose = pm.log = 0;
  9668. else if (strcmp(*argv, "-w") == 0 ||
  9669. strcmp(*argv, "--strict") == 0)
  9670. pm.this.treat_warnings_as_errors = 0;
  9671. else if (strcmp(*argv, "--speed") == 0)
  9672. pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
  9673. summary = 0;
  9674. else if (strcmp(*argv, "--memory") == 0)
  9675. memstats = 1;
  9676. else if (strcmp(*argv, "--size") == 0)
  9677. pm.test_size = 1;
  9678. else if (strcmp(*argv, "--nosize") == 0)
  9679. pm.test_size = 0;
  9680. else if (strcmp(*argv, "--standard") == 0)
  9681. pm.test_standard = 1;
  9682. else if (strcmp(*argv, "--nostandard") == 0)
  9683. pm.test_standard = 0;
  9684. else if (strcmp(*argv, "--transform") == 0)
  9685. pm.test_transform = 1;
  9686. else if (strcmp(*argv, "--notransform") == 0)
  9687. pm.test_transform = 0;
  9688. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  9689. else if (strncmp(*argv, "--transform-disable=",
  9690. sizeof "--transform-disable") == 0)
  9691. {
  9692. pm.test_transform = 1;
  9693. transform_disable(*argv + sizeof "--transform-disable");
  9694. }
  9695. else if (strncmp(*argv, "--transform-enable=",
  9696. sizeof "--transform-enable") == 0)
  9697. {
  9698. pm.test_transform = 1;
  9699. transform_enable(*argv + sizeof "--transform-enable");
  9700. }
  9701. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  9702. else if (strcmp(*argv, "--gamma") == 0)
  9703. {
  9704. /* Just do two gamma tests here (2.2 and linear) for speed: */
  9705. pm.ngamma_tests = 2U;
  9706. pm.test_gamma_threshold = 1;
  9707. pm.test_gamma_transform = 1;
  9708. pm.test_gamma_sbit = 1;
  9709. pm.test_gamma_scale16 = 1;
  9710. pm.test_gamma_background = 1; /* composition */
  9711. pm.test_gamma_alpha_mode = 1;
  9712. }
  9713. else if (strcmp(*argv, "--nogamma") == 0)
  9714. pm.ngamma_tests = 0;
  9715. else if (strcmp(*argv, "--gamma-threshold") == 0)
  9716. pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
  9717. else if (strcmp(*argv, "--nogamma-threshold") == 0)
  9718. pm.test_gamma_threshold = 0;
  9719. else if (strcmp(*argv, "--gamma-transform") == 0)
  9720. pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
  9721. else if (strcmp(*argv, "--nogamma-transform") == 0)
  9722. pm.test_gamma_transform = 0;
  9723. else if (strcmp(*argv, "--gamma-sbit") == 0)
  9724. pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
  9725. else if (strcmp(*argv, "--nogamma-sbit") == 0)
  9726. pm.test_gamma_sbit = 0;
  9727. else if (strcmp(*argv, "--gamma-16-to-8") == 0)
  9728. pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
  9729. else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
  9730. pm.test_gamma_scale16 = 0;
  9731. else if (strcmp(*argv, "--gamma-background") == 0)
  9732. pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
  9733. else if (strcmp(*argv, "--nogamma-background") == 0)
  9734. pm.test_gamma_background = 0;
  9735. else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
  9736. pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
  9737. else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
  9738. pm.test_gamma_alpha_mode = 0;
  9739. else if (strcmp(*argv, "--expand16") == 0)
  9740. pm.test_gamma_expand16 = 1;
  9741. else if (strcmp(*argv, "--noexpand16") == 0)
  9742. pm.test_gamma_expand16 = 0;
  9743. else if (strcmp(*argv, "--low-depth-gray") == 0)
  9744. pm.test_lbg = pm.test_lbg_gamma_threshold =
  9745. pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
  9746. pm.test_lbg_gamma_composition = 1;
  9747. else if (strcmp(*argv, "--nolow-depth-gray") == 0)
  9748. pm.test_lbg = pm.test_lbg_gamma_threshold =
  9749. pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
  9750. pm.test_lbg_gamma_composition = 0;
  9751. # ifdef PNG_WRITE_tRNS_SUPPORTED
  9752. else if (strcmp(*argv, "--tRNS") == 0)
  9753. pm.test_tRNS = 1;
  9754. # endif
  9755. else if (strcmp(*argv, "--notRNS") == 0)
  9756. pm.test_tRNS = 0;
  9757. else if (strcmp(*argv, "--more-gammas") == 0)
  9758. pm.ngamma_tests = 3U;
  9759. else if (strcmp(*argv, "--all-gammas") == 0)
  9760. pm.ngamma_tests = pm.ngammas;
  9761. else if (strcmp(*argv, "--progressive-read") == 0)
  9762. pm.this.progressive = 1;
  9763. else if (strcmp(*argv, "--use-update-info") == 0)
  9764. ++pm.use_update_info; /* Can call multiple times */
  9765. else if (strcmp(*argv, "--interlace") == 0)
  9766. {
  9767. # if CAN_WRITE_INTERLACE
  9768. pm.interlace_type = PNG_INTERLACE_ADAM7;
  9769. # else /* !CAN_WRITE_INTERLACE */
  9770. fprintf(stderr, "pngvalid: no write interlace support\n");
  9771. return SKIP;
  9772. # endif /* !CAN_WRITE_INTERLACE */
  9773. }
  9774. else if (strcmp(*argv, "--use-input-precision") == 0)
  9775. pm.use_input_precision = 1U;
  9776. else if (strcmp(*argv, "--use-calculation-precision") == 0)
  9777. pm.use_input_precision = 0;
  9778. else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
  9779. pm.calculations_use_input_precision = 1U;
  9780. else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
  9781. pm.assume_16_bit_calculations = 1U;
  9782. else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
  9783. pm.calculations_use_input_precision =
  9784. pm.assume_16_bit_calculations = 0;
  9785. else if (strcmp(*argv, "--exhaustive") == 0)
  9786. pm.test_exhaustive = 1;
  9787. else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
  9788. --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
  9789. else if (argc > 1 && strcmp(*argv, "--touch") == 0)
  9790. --argc, touch = *++argv, catmore = 1;
  9791. else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
  9792. {
  9793. --argc;
  9794. if (strcmp(5+*argv, "abs8") == 0)
  9795. pm.maxabs8 = atof(*++argv);
  9796. else if (strcmp(5+*argv, "abs16") == 0)
  9797. pm.maxabs16 = atof(*++argv);
  9798. else if (strcmp(5+*argv, "calc8") == 0)
  9799. pm.maxcalc8 = atof(*++argv);
  9800. else if (strcmp(5+*argv, "calc16") == 0)
  9801. pm.maxcalc16 = atof(*++argv);
  9802. else if (strcmp(5+*argv, "out8") == 0)
  9803. pm.maxout8 = atof(*++argv);
  9804. else if (strcmp(5+*argv, "out16") == 0)
  9805. pm.maxout16 = atof(*++argv);
  9806. else if (strcmp(5+*argv, "pc8") == 0)
  9807. pm.maxpc8 = atof(*++argv);
  9808. else if (strcmp(5+*argv, "pc16") == 0)
  9809. pm.maxpc16 = atof(*++argv);
  9810. else
  9811. {
  9812. fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
  9813. exit(99);
  9814. }
  9815. catmore = 1;
  9816. }
  9817. else if (strcmp(*argv, "--log8") == 0)
  9818. --argc, pm.log8 = atof(*++argv), catmore = 1;
  9819. else if (strcmp(*argv, "--log16") == 0)
  9820. --argc, pm.log16 = atof(*++argv), catmore = 1;
  9821. #ifdef PNG_SET_OPTION_SUPPORTED
  9822. else if (strncmp(*argv, "--option=", 9) == 0)
  9823. {
  9824. /* Syntax of the argument is <option>:{on|off} */
  9825. const char *arg = 9+*argv;
  9826. unsigned char option=0, setting=0;
  9827. #ifdef PNG_ARM_NEON
  9828. if (strncmp(arg, "arm-neon:", 9) == 0)
  9829. option = PNG_ARM_NEON, arg += 9;
  9830. else
  9831. #endif
  9832. #ifdef PNG_EXTENSIONS
  9833. if (strncmp(arg, "extensions:", 11) == 0)
  9834. option = PNG_EXTENSIONS, arg += 11;
  9835. else
  9836. #endif
  9837. #ifdef PNG_MAXIMUM_INFLATE_WINDOW
  9838. if (strncmp(arg, "max-inflate-window:", 19) == 0)
  9839. option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
  9840. else
  9841. #endif
  9842. {
  9843. fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
  9844. exit(99);
  9845. }
  9846. if (strcmp(arg, "off") == 0)
  9847. setting = PNG_OPTION_OFF;
  9848. else if (strcmp(arg, "on") == 0)
  9849. setting = PNG_OPTION_ON;
  9850. else
  9851. {
  9852. fprintf(stderr,
  9853. "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
  9854. *argv, arg);
  9855. exit(99);
  9856. }
  9857. pm.this.options[pm.this.noptions].option = option;
  9858. pm.this.options[pm.this.noptions++].setting = setting;
  9859. }
  9860. #endif /* PNG_SET_OPTION_SUPPORTED */
  9861. else
  9862. {
  9863. fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
  9864. exit(99);
  9865. }
  9866. if (catmore) /* consumed an extra *argv */
  9867. {
  9868. cp = safecat(command, sizeof command, cp, " ");
  9869. cp = safecat(command, sizeof command, cp, *argv);
  9870. }
  9871. }
  9872. /* If pngvalid is run with no arguments default to a reasonable set of the
  9873. * tests.
  9874. */
  9875. if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
  9876. pm.ngamma_tests == 0)
  9877. {
  9878. /* Make this do all the tests done in the test shell scripts with the same
  9879. * parameters, where possible. The limitation is that all the progressive
  9880. * read and interlace stuff has to be done in separate runs, so only the
  9881. * basic 'standard' and 'size' tests are done.
  9882. */
  9883. pm.test_standard = 1;
  9884. pm.test_size = 1;
  9885. pm.test_transform = 1;
  9886. pm.ngamma_tests = 2U;
  9887. }
  9888. if (pm.ngamma_tests > 0 &&
  9889. pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
  9890. pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
  9891. pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
  9892. {
  9893. pm.test_gamma_threshold = 1;
  9894. pm.test_gamma_transform = 1;
  9895. pm.test_gamma_sbit = 1;
  9896. pm.test_gamma_scale16 = 1;
  9897. pm.test_gamma_background = 1;
  9898. pm.test_gamma_alpha_mode = 1;
  9899. }
  9900. else if (pm.ngamma_tests == 0)
  9901. {
  9902. /* Nothing to test so turn everything off: */
  9903. pm.test_gamma_threshold = 0;
  9904. pm.test_gamma_transform = 0;
  9905. pm.test_gamma_sbit = 0;
  9906. pm.test_gamma_scale16 = 0;
  9907. pm.test_gamma_background = 0;
  9908. pm.test_gamma_alpha_mode = 0;
  9909. }
  9910. Try
  9911. {
  9912. /* Make useful base images */
  9913. make_transform_images(&pm);
  9914. /* Perform the standard and gamma tests. */
  9915. if (pm.test_standard)
  9916. {
  9917. perform_interlace_macro_validation();
  9918. perform_formatting_test(&pm.this);
  9919. # ifdef PNG_READ_SUPPORTED
  9920. perform_standard_test(&pm);
  9921. # endif
  9922. perform_error_test(&pm);
  9923. }
  9924. /* Various oddly sized images: */
  9925. if (pm.test_size)
  9926. {
  9927. make_size_images(&pm.this);
  9928. # ifdef PNG_READ_SUPPORTED
  9929. perform_size_test(&pm);
  9930. # endif
  9931. }
  9932. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  9933. /* Combinatorial transforms: */
  9934. if (pm.test_transform)
  9935. perform_transform_test(&pm);
  9936. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  9937. #ifdef PNG_READ_GAMMA_SUPPORTED
  9938. if (pm.ngamma_tests > 0)
  9939. perform_gamma_test(&pm, summary);
  9940. #endif
  9941. }
  9942. Catch_anonymous
  9943. {
  9944. fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
  9945. if (!pm.this.verbose)
  9946. {
  9947. if (pm.this.error[0] != 0)
  9948. fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
  9949. fprintf(stderr, "pngvalid: run with -v to see what happened\n");
  9950. }
  9951. exit(1);
  9952. }
  9953. if (summary)
  9954. {
  9955. printf("%s: %s (%s point arithmetic)\n",
  9956. (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  9957. pm.this.nwarnings)) ? "FAIL" : "PASS",
  9958. command,
  9959. #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
  9960. "floating"
  9961. #else
  9962. "fixed"
  9963. #endif
  9964. );
  9965. }
  9966. if (memstats)
  9967. {
  9968. printf("Allocated memory statistics (in bytes):\n"
  9969. "\tread %lu maximum single, %lu peak, %lu total\n"
  9970. "\twrite %lu maximum single, %lu peak, %lu total\n",
  9971. (unsigned long)pm.this.read_memory_pool.max_max,
  9972. (unsigned long)pm.this.read_memory_pool.max_limit,
  9973. (unsigned long)pm.this.read_memory_pool.max_total,
  9974. (unsigned long)pm.this.write_memory_pool.max_max,
  9975. (unsigned long)pm.this.write_memory_pool.max_limit,
  9976. (unsigned long)pm.this.write_memory_pool.max_total);
  9977. }
  9978. /* Do this here to provoke memory corruption errors in memory not directly
  9979. * allocated by libpng - not a complete test, but better than nothing.
  9980. */
  9981. store_delete(&pm.this);
  9982. /* Error exit if there are any errors, and maybe if there are any
  9983. * warnings.
  9984. */
  9985. if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  9986. pm.this.nwarnings))
  9987. {
  9988. if (!pm.this.verbose)
  9989. fprintf(stderr, "pngvalid: %s\n", pm.this.error);
  9990. fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
  9991. pm.this.nwarnings);
  9992. exit(1);
  9993. }
  9994. /* Success case. */
  9995. if (touch != NULL)
  9996. {
  9997. FILE *fsuccess = fopen(touch, "wt");
  9998. if (fsuccess != NULL)
  9999. {
  10000. int error = 0;
  10001. fprintf(fsuccess, "PNG validation succeeded\n");
  10002. fflush(fsuccess);
  10003. error = ferror(fsuccess);
  10004. if (fclose(fsuccess) || error)
  10005. {
  10006. fprintf(stderr, "%s: write failed\n", touch);
  10007. exit(1);
  10008. }
  10009. }
  10010. else
  10011. {
  10012. fprintf(stderr, "%s: open failed\n", touch);
  10013. exit(1);
  10014. }
  10015. }
  10016. /* This is required because some very minimal configurations do not use it:
  10017. */
  10018. UNUSED(fail)
  10019. return 0;
  10020. }
  10021. #else /* write or low level APIs not supported */
  10022. int main(void)
  10023. {
  10024. fprintf(stderr,
  10025. "pngvalid: no low level write support in libpng, all tests skipped\n");
  10026. /* So the test is skipped: */
  10027. return SKIP;
  10028. }
  10029. #endif