pngvalid.c 376 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230
  1. /* pngvalid.c - validate libpng by constructing then reading png files.
  2. *
  3. * Last changed in libpng 1.6.31 [July 27, 2017]
  4. * Copyright (c) 2014-2017 John Cunningham Bowler
  5. *
  6. * This code is released under the libpng license.
  7. * For conditions of distribution and use, see the disclaimer
  8. * and license in png.h
  9. *
  10. * NOTES:
  11. * This is a C program that is intended to be linked against libpng. It
  12. * generates bitmaps internally, stores them as PNG files (using the
  13. * sequential write code) then reads them back (using the sequential
  14. * read code) and validates that the result has the correct data.
  15. *
  16. * The program can be modified and extended to test the correctness of
  17. * transformations performed by libpng.
  18. */
  19. #define _POSIX_SOURCE 1
  20. #define _ISOC99_SOURCE 1 /* For floating point */
  21. #define _GNU_SOURCE 1 /* For the floating point exception extension */
  22. #define _BSD_SOURCE 1 /* For the floating point exception extension */
  23. #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 && defined(HAVE_CONFIG_H)
  57. # define SKIP 77
  58. #else
  59. # define SKIP 0
  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 after 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. #ifndef RELEASE_BUILD
  104. /* RELEASE_BUILD is true for releases and release candidates: */
  105. # define RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC)
  106. #endif
  107. #if RELEASE_BUILD
  108. # define debugonly(something)
  109. #else /* !RELEASE_BUILD */
  110. # define debugonly(something) something
  111. #endif /* !RELEASE_BUILD */
  112. #include <float.h> /* For floating point constants */
  113. #include <stdlib.h> /* For malloc */
  114. #include <string.h> /* For memcpy, memset */
  115. #include <math.h> /* For floor */
  116. /* Convenience macros. */
  117. #define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
  118. #define CHUNK_IHDR CHUNK(73,72,68,82)
  119. #define CHUNK_PLTE CHUNK(80,76,84,69)
  120. #define CHUNK_IDAT CHUNK(73,68,65,84)
  121. #define CHUNK_IEND CHUNK(73,69,78,68)
  122. #define CHUNK_cHRM CHUNK(99,72,82,77)
  123. #define CHUNK_gAMA CHUNK(103,65,77,65)
  124. #define CHUNK_sBIT CHUNK(115,66,73,84)
  125. #define CHUNK_sRGB CHUNK(115,82,71,66)
  126. /* Unused formal parameter errors are removed using the following macro which is
  127. * expected to have no bad effects on performance.
  128. */
  129. #ifndef UNUSED
  130. # if defined(__GNUC__) || defined(_MSC_VER)
  131. # define UNUSED(param) (void)param;
  132. # else
  133. # define UNUSED(param)
  134. # endif
  135. #endif
  136. /***************************** EXCEPTION HANDLING *****************************/
  137. #ifdef PNG_FREESTANDING_TESTS
  138. # include <cexcept.h>
  139. #else
  140. # include "../visupng/cexcept.h"
  141. #endif
  142. #ifdef __cplusplus
  143. # define this not_the_cpp_this
  144. # define new not_the_cpp_new
  145. # define voidcast(type, value) static_cast<type>(value)
  146. #else
  147. # define voidcast(type, value) (value)
  148. #endif /* __cplusplus */
  149. struct png_store;
  150. define_exception_type(struct png_store*);
  151. /* The following are macros to reduce typing everywhere where the well known
  152. * name 'the_exception_context' must be defined.
  153. */
  154. #define anon_context(ps) struct exception_context *the_exception_context = \
  155. &(ps)->exception_context
  156. #define context(ps,fault) anon_context(ps); png_store *fault
  157. /* This macro returns the number of elements in an array as an (unsigned int),
  158. * it is necessary to avoid the inability of certain versions of GCC to use
  159. * the value of a compile-time constant when performing range checks. It must
  160. * be passed an array name.
  161. */
  162. #define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0])))
  163. /* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires
  164. * some broken GCC versions to be fixed up to avoid invalid whining about auto
  165. * variables that are *not* changed within the scope of a setjmp being changed.
  166. *
  167. * Feel free to extend the list of broken versions.
  168. */
  169. #define is_gnu(major,minor)\
  170. (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor)
  171. #define is_gnu_patch(major,minor,patch)\
  172. is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0
  173. /* For the moment just do it always; all versions of GCC seem to be broken: */
  174. #ifdef __GNUC__
  175. const void * volatile make_volatile_for_gnu;
  176. # define gnu_volatile(x) make_volatile_for_gnu = &x;
  177. #else /* !GNUC broken versions */
  178. # define gnu_volatile(x)
  179. #endif /* !GNUC broken versions */
  180. /******************************* UTILITIES ************************************/
  181. /* Error handling is particularly problematic in production code - error
  182. * handlers often themselves have bugs which lead to programs that detect
  183. * minor errors crashing. The following functions deal with one very
  184. * common class of errors in error handlers - attempting to format error or
  185. * warning messages into buffers that are too small.
  186. */
  187. static size_t safecat(char *buffer, size_t bufsize, size_t pos,
  188. const char *cat)
  189. {
  190. while (pos < bufsize && cat != NULL && *cat != 0)
  191. buffer[pos++] = *cat++;
  192. if (pos >= bufsize)
  193. pos = bufsize-1;
  194. buffer[pos] = 0;
  195. return pos;
  196. }
  197. static size_t safecatn(char *buffer, size_t bufsize, size_t pos, int n)
  198. {
  199. char number[64];
  200. sprintf(number, "%d", n);
  201. return safecat(buffer, bufsize, pos, number);
  202. }
  203. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  204. static size_t safecatd(char *buffer, size_t bufsize, size_t pos, double d,
  205. int precision)
  206. {
  207. char number[64];
  208. sprintf(number, "%.*f", precision, d);
  209. return safecat(buffer, bufsize, pos, number);
  210. }
  211. #endif
  212. static const char invalid[] = "invalid";
  213. static const char sep[] = ": ";
  214. static const char *colour_types[8] =
  215. {
  216. "grayscale", invalid, "truecolour", "indexed-colour",
  217. "grayscale with alpha", invalid, "truecolour with alpha", invalid
  218. };
  219. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  220. /* Convert a double precision value to fixed point. */
  221. static png_fixed_point
  222. fix(double d)
  223. {
  224. d = floor(d * PNG_FP_1 + .5);
  225. return (png_fixed_point)d;
  226. }
  227. #endif /* PNG_READ_SUPPORTED */
  228. /* Generate random bytes. This uses a boring repeatable algorithm and it
  229. * is implemented here so that it gives the same set of numbers on every
  230. * architecture. It's a linear congruential generator (Knuth or Sedgewick
  231. * "Algorithms") but it comes from the 'feedback taps' table in Horowitz and
  232. * Hill, "The Art of Electronics" (Pseudo-Random Bit Sequences and Noise
  233. * Generation.)
  234. */
  235. static void
  236. make_random_bytes(png_uint_32* seed, void* pv, size_t size)
  237. {
  238. png_uint_32 u0 = seed[0], u1 = seed[1];
  239. png_bytep bytes = voidcast(png_bytep, pv);
  240. /* There are thirty three bits, the next bit in the sequence is bit-33 XOR
  241. * bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
  242. */
  243. size_t i;
  244. for (i=0; i<size; ++i)
  245. {
  246. /* First generate 8 new bits then shift them in at the end. */
  247. png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
  248. u1 <<= 8;
  249. u1 |= u0 >> 24;
  250. u0 <<= 8;
  251. u0 |= u;
  252. *bytes++ = (png_byte)u;
  253. }
  254. seed[0] = u0;
  255. seed[1] = u1;
  256. }
  257. static void
  258. make_four_random_bytes(png_uint_32* seed, png_bytep bytes)
  259. {
  260. make_random_bytes(seed, bytes, 4);
  261. }
  262. #if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED ||\
  263. defined PNG_WRITE_FILTER_SUPPORTED
  264. static void
  265. randomize(void *pv, size_t size)
  266. {
  267. static png_uint_32 random_seed[2] = {0x56789abc, 0xd};
  268. make_random_bytes(random_seed, pv, size);
  269. }
  270. #define R8(this) randomize(&(this), sizeof (this))
  271. #ifdef PNG_READ_SUPPORTED
  272. static png_byte
  273. random_byte(void)
  274. {
  275. unsigned char b1[1];
  276. randomize(b1, sizeof b1);
  277. return b1[0];
  278. }
  279. #endif /* READ */
  280. static png_uint_16
  281. random_u16(void)
  282. {
  283. unsigned char b2[2];
  284. randomize(b2, sizeof b2);
  285. return png_get_uint_16(b2);
  286. }
  287. #if defined PNG_READ_RGB_TO_GRAY_SUPPORTED ||\
  288. defined PNG_READ_FILLER_SUPPORTED
  289. static png_uint_32
  290. random_u32(void)
  291. {
  292. unsigned char b4[4];
  293. randomize(b4, sizeof b4);
  294. return png_get_uint_32(b4);
  295. }
  296. #endif /* READ_FILLER || READ_RGB_TO_GRAY */
  297. #endif /* READ || WRITE_tRNS || WRITE_FILTER */
  298. #if defined PNG_READ_TRANSFORMS_SUPPORTED ||\
  299. defined PNG_WRITE_FILTER_SUPPORTED
  300. static unsigned int
  301. random_mod(unsigned int max)
  302. {
  303. return random_u16() % max; /* 0 .. max-1 */
  304. }
  305. #endif /* READ_TRANSFORMS || WRITE_FILTER */
  306. #if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\
  307. (defined PNG_READ_FILLER_SUPPORTED)
  308. static int
  309. random_choice(void)
  310. {
  311. return random_byte() & 1;
  312. }
  313. #endif /* READ_RGB_TO_GRAY || READ_FILLER */
  314. /* A numeric ID based on PNG file characteristics. The 'do_interlace' field
  315. * simply records whether pngvalid did the interlace itself or whether it
  316. * was done by libpng. Width and height must be less than 256. 'palette' is an
  317. * index of the palette to use for formats with a palette otherwise a boolean
  318. * indicating if a tRNS chunk was generated.
  319. */
  320. #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \
  321. ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \
  322. (((do_interlace)!=0)<<15) + ((width)<<16) + ((height)<<24)))
  323. #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U))
  324. #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU))
  325. #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f)
  326. #define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3))
  327. #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1))
  328. #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff)
  329. #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff)
  330. /* Utility to construct a standard name for a standard image. */
  331. static size_t
  332. standard_name(char *buffer, size_t bufsize, size_t pos, png_byte colour_type,
  333. int bit_depth, unsigned int npalette, int interlace_type,
  334. png_uint_32 w, png_uint_32 h, int do_interlace)
  335. {
  336. pos = safecat(buffer, bufsize, pos, colour_types[colour_type]);
  337. if (colour_type == 3) /* must have a palette */
  338. {
  339. pos = safecat(buffer, bufsize, pos, "[");
  340. pos = safecatn(buffer, bufsize, pos, npalette);
  341. pos = safecat(buffer, bufsize, pos, "]");
  342. }
  343. else if (npalette != 0)
  344. pos = safecat(buffer, bufsize, pos, "+tRNS");
  345. pos = safecat(buffer, bufsize, pos, " ");
  346. pos = safecatn(buffer, bufsize, pos, bit_depth);
  347. pos = safecat(buffer, bufsize, pos, " bit");
  348. if (interlace_type != PNG_INTERLACE_NONE)
  349. {
  350. pos = safecat(buffer, bufsize, pos, " interlaced");
  351. if (do_interlace)
  352. pos = safecat(buffer, bufsize, pos, "(pngvalid)");
  353. else
  354. pos = safecat(buffer, bufsize, pos, "(libpng)");
  355. }
  356. if (w > 0 || h > 0)
  357. {
  358. pos = safecat(buffer, bufsize, pos, " ");
  359. pos = safecatn(buffer, bufsize, pos, w);
  360. pos = safecat(buffer, bufsize, pos, "x");
  361. pos = safecatn(buffer, bufsize, pos, h);
  362. }
  363. return pos;
  364. }
  365. static size_t
  366. standard_name_from_id(char *buffer, size_t bufsize, size_t pos, png_uint_32 id)
  367. {
  368. return standard_name(buffer, bufsize, pos, COL_FROM_ID(id),
  369. DEPTH_FROM_ID(id), PALETTE_FROM_ID(id), INTERLACE_FROM_ID(id),
  370. WIDTH_FROM_ID(id), HEIGHT_FROM_ID(id), DO_INTERLACE_FROM_ID(id));
  371. }
  372. /* Convenience API and defines to list valid formats. Note that 16 bit read and
  373. * write support is required to do 16 bit read tests (we must be able to make a
  374. * 16 bit image to test!)
  375. */
  376. #ifdef PNG_WRITE_16BIT_SUPPORTED
  377. # define WRITE_BDHI 4
  378. # ifdef PNG_READ_16BIT_SUPPORTED
  379. # define READ_BDHI 4
  380. # define DO_16BIT
  381. # endif
  382. #else
  383. # define WRITE_BDHI 3
  384. #endif
  385. #ifndef DO_16BIT
  386. # define READ_BDHI 3
  387. #endif
  388. /* The following defines the number of different palettes to generate for
  389. * each log bit depth of a colour type 3 standard image.
  390. */
  391. #define PALETTE_COUNT(bit_depth) ((bit_depth) > 4 ? 1U : 16U)
  392. static int
  393. next_format(png_bytep colour_type, png_bytep bit_depth,
  394. unsigned int* palette_number, int low_depth_gray, int tRNS)
  395. {
  396. if (*bit_depth == 0)
  397. {
  398. *colour_type = 0;
  399. if (low_depth_gray)
  400. *bit_depth = 1;
  401. else
  402. *bit_depth = 8;
  403. *palette_number = 0;
  404. return 1;
  405. }
  406. if (*colour_type < 4/*no alpha channel*/)
  407. {
  408. /* Add multiple palettes for colour type 3, one image with tRNS
  409. * and one without for other non-alpha formats:
  410. */
  411. unsigned int pn = ++*palette_number;
  412. png_byte ct = *colour_type;
  413. if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) ||
  414. (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth)))
  415. return 1;
  416. /* No: next bit depth */
  417. *palette_number = 0;
  418. }
  419. *bit_depth = (png_byte)(*bit_depth << 1);
  420. /* Palette images are restricted to 8 bit depth */
  421. if (*bit_depth <= 8
  422. #ifdef DO_16BIT
  423. || (*colour_type != 3 && *bit_depth <= 16)
  424. #endif
  425. )
  426. return 1;
  427. /* Move to the next color type, or return 0 at the end. */
  428. switch (*colour_type)
  429. {
  430. case 0:
  431. *colour_type = 2;
  432. *bit_depth = 8;
  433. return 1;
  434. case 2:
  435. *colour_type = 3;
  436. *bit_depth = 1;
  437. return 1;
  438. case 3:
  439. *colour_type = 4;
  440. *bit_depth = 8;
  441. return 1;
  442. case 4:
  443. *colour_type = 6;
  444. *bit_depth = 8;
  445. return 1;
  446. default:
  447. return 0;
  448. }
  449. }
  450. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  451. static unsigned int
  452. sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
  453. png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
  454. {
  455. png_uint_32 bit_index, result;
  456. /* Find a sample index for the desired sample: */
  457. x *= bit_depth;
  458. bit_index = x;
  459. if ((colour_type & 1) == 0) /* !palette */
  460. {
  461. if (colour_type & 2)
  462. bit_index *= 3;
  463. if (colour_type & 4)
  464. bit_index += x; /* Alpha channel */
  465. /* Multiple channels; select one: */
  466. if (colour_type & (2+4))
  467. bit_index += sample_index * bit_depth;
  468. }
  469. /* Return the sample from the row as an integer. */
  470. row += bit_index >> 3;
  471. result = *row;
  472. if (bit_depth == 8)
  473. return result;
  474. else if (bit_depth > 8)
  475. {
  476. if (swap16)
  477. return (*++row << 8) + result;
  478. else
  479. return (result << 8) + *++row;
  480. }
  481. /* Less than 8 bits per sample. By default PNG has the big end of
  482. * the egg on the left of the screen, but if littleendian is set
  483. * then the big end is on the right.
  484. */
  485. bit_index &= 7;
  486. if (!littleendian)
  487. bit_index = 8-bit_index-bit_depth;
  488. return (result >> bit_index) & ((1U<<bit_depth)-1);
  489. }
  490. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  491. /* Copy a single pixel, of a given size, from one buffer to another -
  492. * while this is basically bit addressed there is an implicit assumption
  493. * that pixels 8 or more bits in size are byte aligned and that pixels
  494. * do not otherwise cross byte boundaries. (This is, so far as I know,
  495. * universally true in bitmap computer graphics. [JCB 20101212])
  496. *
  497. * NOTE: The to and from buffers may be the same.
  498. */
  499. static void
  500. pixel_copy(png_bytep toBuffer, png_uint_32 toIndex,
  501. png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize,
  502. int littleendian)
  503. {
  504. /* Assume we can multiply by 'size' without overflow because we are
  505. * just working in a single buffer.
  506. */
  507. toIndex *= pixelSize;
  508. fromIndex *= pixelSize;
  509. if (pixelSize < 8) /* Sub-byte */
  510. {
  511. /* Mask to select the location of the copied pixel: */
  512. unsigned int destMask = ((1U<<pixelSize)-1) <<
  513. (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7));
  514. /* The following read the entire pixels and clears the extra: */
  515. unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask;
  516. unsigned int sourceByte = fromBuffer[fromIndex >> 3];
  517. /* Don't rely on << or >> supporting '0' here, just in case: */
  518. fromIndex &= 7;
  519. if (littleendian)
  520. {
  521. if (fromIndex > 0) sourceByte >>= fromIndex;
  522. if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7;
  523. }
  524. else
  525. {
  526. if (fromIndex > 0) sourceByte <<= fromIndex;
  527. if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7;
  528. }
  529. toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask));
  530. }
  531. else /* One or more bytes */
  532. memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3);
  533. }
  534. #ifdef PNG_READ_SUPPORTED
  535. /* Copy a complete row of pixels, taking into account potential partial
  536. * bytes at the end.
  537. */
  538. static void
  539. row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
  540. int littleendian)
  541. {
  542. memcpy(toBuffer, fromBuffer, bitWidth >> 3);
  543. if ((bitWidth & 7) != 0)
  544. {
  545. unsigned int mask;
  546. toBuffer += bitWidth >> 3;
  547. fromBuffer += bitWidth >> 3;
  548. if (littleendian)
  549. mask = 0xff << (bitWidth & 7);
  550. else
  551. mask = 0xff >> (bitWidth & 7);
  552. *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
  553. }
  554. }
  555. /* Compare pixels - they are assumed to start at the first byte in the
  556. * given buffers.
  557. */
  558. static int
  559. pixel_cmp(png_const_bytep pa, png_const_bytep pb, png_uint_32 bit_width)
  560. {
  561. #if PNG_LIBPNG_VER < 10506
  562. if (memcmp(pa, pb, bit_width>>3) == 0)
  563. {
  564. png_uint_32 p;
  565. if ((bit_width & 7) == 0) return 0;
  566. /* Ok, any differences? */
  567. p = pa[bit_width >> 3];
  568. p ^= pb[bit_width >> 3];
  569. if (p == 0) return 0;
  570. /* There are, but they may not be significant, remove the bits
  571. * after the end (the low order bits in PNG.)
  572. */
  573. bit_width &= 7;
  574. p >>= 8-bit_width;
  575. if (p == 0) return 0;
  576. }
  577. #else
  578. /* From libpng-1.5.6 the overwrite should be fixed, so compare the trailing
  579. * bits too:
  580. */
  581. if (memcmp(pa, pb, (bit_width+7)>>3) == 0)
  582. return 0;
  583. #endif
  584. /* Return the index of the changed byte. */
  585. {
  586. png_uint_32 where = 0;
  587. while (pa[where] == pb[where]) ++where;
  588. return 1+where;
  589. }
  590. }
  591. #endif /* PNG_READ_SUPPORTED */
  592. /*************************** BASIC PNG FILE WRITING ***************************/
  593. /* A png_store takes data from the sequential writer or provides data
  594. * to the sequential reader. It can also store the result of a PNG
  595. * write for later retrieval.
  596. */
  597. #define STORE_BUFFER_SIZE 500 /* arbitrary */
  598. typedef struct png_store_buffer
  599. {
  600. struct png_store_buffer* prev; /* NOTE: stored in reverse order */
  601. png_byte buffer[STORE_BUFFER_SIZE];
  602. } png_store_buffer;
  603. #define FILE_NAME_SIZE 64
  604. typedef struct store_palette_entry /* record of a single palette entry */
  605. {
  606. png_byte red;
  607. png_byte green;
  608. png_byte blue;
  609. png_byte alpha;
  610. } store_palette_entry, store_palette[256];
  611. typedef struct png_store_file
  612. {
  613. struct png_store_file* next; /* as many as you like... */
  614. char name[FILE_NAME_SIZE];
  615. unsigned int IDAT_bits; /* Number of bits in IDAT size */
  616. png_uint_32 IDAT_size; /* Total size of IDAT data */
  617. png_uint_32 id; /* must be correct (see FILEID) */
  618. size_t datacount; /* In this (the last) buffer */
  619. png_store_buffer data; /* Last buffer in file */
  620. int npalette; /* Number of entries in palette */
  621. store_palette_entry* palette; /* May be NULL */
  622. } png_store_file;
  623. /* The following is a pool of memory allocated by a single libpng read or write
  624. * operation.
  625. */
  626. typedef struct store_pool
  627. {
  628. struct png_store *store; /* Back pointer */
  629. struct store_memory *list; /* List of allocated memory */
  630. png_byte mark[4]; /* Before and after data */
  631. /* Statistics for this run. */
  632. png_alloc_size_t max; /* Maximum single allocation */
  633. png_alloc_size_t current; /* Current allocation */
  634. png_alloc_size_t limit; /* Highest current allocation */
  635. png_alloc_size_t total; /* Total allocation */
  636. /* Overall statistics (retained across successive runs). */
  637. png_alloc_size_t max_max;
  638. png_alloc_size_t max_limit;
  639. png_alloc_size_t max_total;
  640. } store_pool;
  641. typedef struct png_store
  642. {
  643. /* For cexcept.h exception handling - simply store one of these;
  644. * the context is a self pointer but it may point to a different
  645. * png_store (in fact it never does in this program.)
  646. */
  647. struct exception_context
  648. exception_context;
  649. unsigned int verbose :1;
  650. unsigned int treat_warnings_as_errors :1;
  651. unsigned int expect_error :1;
  652. unsigned int expect_warning :1;
  653. unsigned int saw_warning :1;
  654. unsigned int speed :1;
  655. unsigned int progressive :1; /* use progressive read */
  656. unsigned int validated :1; /* used as a temporary flag */
  657. int nerrors;
  658. int nwarnings;
  659. int noptions; /* number of options below: */
  660. struct {
  661. unsigned char option; /* option number, 0..30 */
  662. unsigned char setting; /* setting (unset,invalid,on,off) */
  663. } options[16];
  664. char test[128]; /* Name of test */
  665. char error[256];
  666. /* Share fields */
  667. png_uint_32 chunklen; /* Length of chunk+overhead (chunkpos >= 8) */
  668. png_uint_32 chunktype;/* Type of chunk (valid if chunkpos >= 4) */
  669. png_uint_32 chunkpos; /* Position in chunk */
  670. png_uint_32 IDAT_size;/* Accumulated IDAT size in .new */
  671. unsigned int IDAT_bits;/* Cache of the file store value */
  672. /* Read fields */
  673. png_structp pread; /* Used to read a saved file */
  674. png_infop piread;
  675. png_store_file* current; /* Set when reading */
  676. png_store_buffer* next; /* Set when reading */
  677. size_t readpos; /* Position in *next */
  678. png_byte* image; /* Buffer for reading interlaced images */
  679. size_t cb_image; /* Size of this buffer */
  680. size_t cb_row; /* Row size of the image(s) */
  681. uLong IDAT_crc;
  682. png_uint_32 IDAT_len; /* Used when re-chunking IDAT chunks */
  683. png_uint_32 IDAT_pos; /* Used when re-chunking IDAT chunks */
  684. png_uint_32 image_h; /* Number of rows in a single image */
  685. store_pool read_memory_pool;
  686. /* Write fields */
  687. png_store_file* saved;
  688. png_structp pwrite; /* Used when writing a new file */
  689. png_infop piwrite;
  690. size_t writepos; /* Position in .new */
  691. char wname[FILE_NAME_SIZE];
  692. png_store_buffer new; /* The end of the new PNG file being written. */
  693. store_pool write_memory_pool;
  694. store_palette_entry* palette;
  695. int npalette;
  696. } png_store;
  697. /* Initialization and cleanup */
  698. static void
  699. store_pool_mark(png_bytep mark)
  700. {
  701. static png_uint_32 store_seed[2] = { 0x12345678, 1};
  702. make_four_random_bytes(store_seed, mark);
  703. }
  704. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  705. /* Use this for random 32 bit values; this function makes sure the result is
  706. * non-zero.
  707. */
  708. static png_uint_32
  709. random_32(void)
  710. {
  711. for (;;)
  712. {
  713. png_byte mark[4];
  714. png_uint_32 result;
  715. store_pool_mark(mark);
  716. result = png_get_uint_32(mark);
  717. if (result != 0)
  718. return result;
  719. }
  720. }
  721. #endif /* PNG_READ_SUPPORTED */
  722. static void
  723. store_pool_init(png_store *ps, store_pool *pool)
  724. {
  725. memset(pool, 0, sizeof *pool);
  726. pool->store = ps;
  727. pool->list = NULL;
  728. pool->max = pool->current = pool->limit = pool->total = 0;
  729. pool->max_max = pool->max_limit = pool->max_total = 0;
  730. store_pool_mark(pool->mark);
  731. }
  732. static void
  733. store_init(png_store* ps)
  734. {
  735. memset(ps, 0, sizeof *ps);
  736. init_exception_context(&ps->exception_context);
  737. store_pool_init(ps, &ps->read_memory_pool);
  738. store_pool_init(ps, &ps->write_memory_pool);
  739. ps->verbose = 0;
  740. ps->treat_warnings_as_errors = 0;
  741. ps->expect_error = 0;
  742. ps->expect_warning = 0;
  743. ps->saw_warning = 0;
  744. ps->speed = 0;
  745. ps->progressive = 0;
  746. ps->validated = 0;
  747. ps->nerrors = ps->nwarnings = 0;
  748. ps->pread = NULL;
  749. ps->piread = NULL;
  750. ps->saved = ps->current = NULL;
  751. ps->next = NULL;
  752. ps->readpos = 0;
  753. ps->image = NULL;
  754. ps->cb_image = 0;
  755. ps->cb_row = 0;
  756. ps->image_h = 0;
  757. ps->pwrite = NULL;
  758. ps->piwrite = NULL;
  759. ps->writepos = 0;
  760. ps->chunkpos = 8;
  761. ps->chunktype = 0;
  762. ps->chunklen = 16;
  763. ps->IDAT_size = 0;
  764. ps->IDAT_bits = 0;
  765. ps->new.prev = NULL;
  766. ps->palette = NULL;
  767. ps->npalette = 0;
  768. ps->noptions = 0;
  769. }
  770. static void
  771. store_freebuffer(png_store_buffer* psb)
  772. {
  773. if (psb->prev)
  774. {
  775. store_freebuffer(psb->prev);
  776. free(psb->prev);
  777. psb->prev = NULL;
  778. }
  779. }
  780. static void
  781. store_freenew(png_store *ps)
  782. {
  783. store_freebuffer(&ps->new);
  784. ps->writepos = 0;
  785. ps->chunkpos = 8;
  786. ps->chunktype = 0;
  787. ps->chunklen = 16;
  788. ps->IDAT_size = 0;
  789. ps->IDAT_bits = 0;
  790. if (ps->palette != NULL)
  791. {
  792. free(ps->palette);
  793. ps->palette = NULL;
  794. ps->npalette = 0;
  795. }
  796. }
  797. static void
  798. store_storenew(png_store *ps)
  799. {
  800. png_store_buffer *pb;
  801. pb = voidcast(png_store_buffer*, malloc(sizeof *pb));
  802. if (pb == NULL)
  803. png_error(ps->pwrite, "store new: OOM");
  804. *pb = ps->new;
  805. ps->new.prev = pb;
  806. ps->writepos = 0;
  807. }
  808. static void
  809. store_freefile(png_store_file **ppf)
  810. {
  811. if (*ppf != NULL)
  812. {
  813. store_freefile(&(*ppf)->next);
  814. store_freebuffer(&(*ppf)->data);
  815. (*ppf)->datacount = 0;
  816. if ((*ppf)->palette != NULL)
  817. {
  818. free((*ppf)->palette);
  819. (*ppf)->palette = NULL;
  820. (*ppf)->npalette = 0;
  821. }
  822. free(*ppf);
  823. *ppf = NULL;
  824. }
  825. }
  826. static unsigned int
  827. bits_of(png_uint_32 num)
  828. {
  829. /* Return the number of bits in 'num' */
  830. unsigned int b = 0;
  831. if (num & 0xffff0000U) b += 16U, num >>= 16;
  832. if (num & 0xff00U) b += 8U, num >>= 8;
  833. if (num & 0xf0U) b += 4U, num >>= 4;
  834. if (num & 0xcU) b += 2U, num >>= 2;
  835. if (num & 0x2U) ++b, num >>= 1;
  836. if (num) ++b;
  837. return b; /* 0..32 */
  838. }
  839. /* Main interface to file storage, after writing a new PNG file (see the API
  840. * below) call store_storefile to store the result with the given name and id.
  841. */
  842. static void
  843. store_storefile(png_store *ps, png_uint_32 id)
  844. {
  845. png_store_file *pf;
  846. if (ps->chunkpos != 0U || ps->chunktype != 0U || ps->chunklen != 0U ||
  847. ps->IDAT_size == 0)
  848. png_error(ps->pwrite, "storefile: incomplete write");
  849. pf = voidcast(png_store_file*, malloc(sizeof *pf));
  850. if (pf == NULL)
  851. png_error(ps->pwrite, "storefile: OOM");
  852. safecat(pf->name, sizeof pf->name, 0, ps->wname);
  853. pf->id = id;
  854. pf->data = ps->new;
  855. pf->datacount = ps->writepos;
  856. pf->IDAT_size = ps->IDAT_size;
  857. pf->IDAT_bits = bits_of(ps->IDAT_size);
  858. /* Because the IDAT always has zlib header stuff this must be true: */
  859. if (pf->IDAT_bits == 0U)
  860. png_error(ps->pwrite, "storefile: 0 sized IDAT");
  861. ps->new.prev = NULL;
  862. ps->writepos = 0;
  863. ps->chunkpos = 8;
  864. ps->chunktype = 0;
  865. ps->chunklen = 16;
  866. ps->IDAT_size = 0;
  867. pf->palette = ps->palette;
  868. pf->npalette = ps->npalette;
  869. ps->palette = 0;
  870. ps->npalette = 0;
  871. /* And save it. */
  872. pf->next = ps->saved;
  873. ps->saved = pf;
  874. }
  875. /* Generate an error message (in the given buffer) */
  876. static size_t
  877. store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
  878. size_t pos, const char *msg)
  879. {
  880. if (pp != NULL && pp == ps->pread)
  881. {
  882. /* Reading a file */
  883. pos = safecat(buffer, bufsize, pos, "read: ");
  884. if (ps->current != NULL)
  885. {
  886. pos = safecat(buffer, bufsize, pos, ps->current->name);
  887. pos = safecat(buffer, bufsize, pos, sep);
  888. }
  889. }
  890. else if (pp != NULL && pp == ps->pwrite)
  891. {
  892. /* Writing a file */
  893. pos = safecat(buffer, bufsize, pos, "write: ");
  894. pos = safecat(buffer, bufsize, pos, ps->wname);
  895. pos = safecat(buffer, bufsize, pos, sep);
  896. }
  897. else
  898. {
  899. /* Neither reading nor writing (or a memory error in struct delete) */
  900. pos = safecat(buffer, bufsize, pos, "pngvalid: ");
  901. }
  902. if (ps->test[0] != 0)
  903. {
  904. pos = safecat(buffer, bufsize, pos, ps->test);
  905. pos = safecat(buffer, bufsize, pos, sep);
  906. }
  907. pos = safecat(buffer, bufsize, pos, msg);
  908. return pos;
  909. }
  910. /* Verbose output to the error stream: */
  911. static void
  912. store_verbose(png_store *ps, png_const_structp pp, png_const_charp prefix,
  913. png_const_charp message)
  914. {
  915. char buffer[512];
  916. if (prefix)
  917. fputs(prefix, stderr);
  918. (void)store_message(ps, pp, buffer, sizeof buffer, 0, message);
  919. fputs(buffer, stderr);
  920. fputc('\n', stderr);
  921. }
  922. /* Log an error or warning - the relevant count is always incremented. */
  923. static void
  924. store_log(png_store* ps, png_const_structp pp, png_const_charp message,
  925. int is_error)
  926. {
  927. /* The warning is copied to the error buffer if there are no errors and it is
  928. * the first warning. The error is copied to the error buffer if it is the
  929. * first error (overwriting any prior warnings).
  930. */
  931. if (is_error ? (ps->nerrors)++ == 0 :
  932. (ps->nwarnings)++ == 0 && ps->nerrors == 0)
  933. store_message(ps, pp, ps->error, sizeof ps->error, 0, message);
  934. if (ps->verbose)
  935. store_verbose(ps, pp, is_error ? "error: " : "warning: ", message);
  936. }
  937. #ifdef PNG_READ_SUPPORTED
  938. /* Internal error function, called with a png_store but no libpng stuff. */
  939. static void
  940. internal_error(png_store *ps, png_const_charp message)
  941. {
  942. store_log(ps, NULL, message, 1 /* error */);
  943. /* And finally throw an exception. */
  944. {
  945. struct exception_context *the_exception_context = &ps->exception_context;
  946. Throw ps;
  947. }
  948. }
  949. #endif /* PNG_READ_SUPPORTED */
  950. /* Functions to use as PNG callbacks. */
  951. static void PNGCBAPI
  952. store_error(png_structp ppIn, png_const_charp message) /* PNG_NORETURN */
  953. {
  954. png_const_structp pp = ppIn;
  955. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  956. if (!ps->expect_error)
  957. store_log(ps, pp, message, 1 /* error */);
  958. /* And finally throw an exception. */
  959. {
  960. struct exception_context *the_exception_context = &ps->exception_context;
  961. Throw ps;
  962. }
  963. }
  964. static void PNGCBAPI
  965. store_warning(png_structp ppIn, png_const_charp message)
  966. {
  967. png_const_structp pp = ppIn;
  968. png_store *ps = voidcast(png_store*, png_get_error_ptr(pp));
  969. if (!ps->expect_warning)
  970. store_log(ps, pp, message, 0 /* warning */);
  971. else
  972. ps->saw_warning = 1;
  973. }
  974. /* These somewhat odd functions are used when reading an image to ensure that
  975. * the buffer is big enough, the png_structp is for errors.
  976. */
  977. /* Return a single row from the correct image. */
  978. static png_bytep
  979. store_image_row(const png_store* ps, png_const_structp pp, int nImage,
  980. png_uint_32 y)
  981. {
  982. size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
  983. if (ps->image == NULL)
  984. png_error(pp, "no allocated image");
  985. if (coffset + ps->cb_row + 3 > ps->cb_image)
  986. png_error(pp, "image too small");
  987. return ps->image + coffset;
  988. }
  989. static void
  990. store_image_free(png_store *ps, png_const_structp pp)
  991. {
  992. if (ps->image != NULL)
  993. {
  994. png_bytep image = ps->image;
  995. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  996. {
  997. if (pp != NULL)
  998. png_error(pp, "png_store image overwrite (1)");
  999. else
  1000. store_log(ps, NULL, "png_store image overwrite (2)", 1);
  1001. }
  1002. ps->image = NULL;
  1003. ps->cb_image = 0;
  1004. --image;
  1005. free(image);
  1006. }
  1007. }
  1008. static void
  1009. store_ensure_image(png_store *ps, png_const_structp pp, int nImages,
  1010. size_t cbRow, png_uint_32 cRows)
  1011. {
  1012. size_t cb = nImages * cRows * (cbRow + 5);
  1013. if (ps->cb_image < cb)
  1014. {
  1015. png_bytep image;
  1016. store_image_free(ps, pp);
  1017. /* The buffer is deliberately mis-aligned. */
  1018. image = voidcast(png_bytep, malloc(cb+2));
  1019. if (image == NULL)
  1020. {
  1021. /* Called from the startup - ignore the error for the moment. */
  1022. if (pp == NULL)
  1023. return;
  1024. png_error(pp, "OOM allocating image buffer");
  1025. }
  1026. /* These magic tags are used to detect overwrites above. */
  1027. ++image;
  1028. image[-1] = 0xed;
  1029. image[cb] = 0xfe;
  1030. ps->image = image;
  1031. ps->cb_image = cb;
  1032. }
  1033. /* We have an adequate sized image; lay out the rows. There are 2 bytes at
  1034. * the start and three at the end of each (this ensures that the row
  1035. * alignment starts out odd - 2+1 and changes for larger images on each row.)
  1036. */
  1037. ps->cb_row = cbRow;
  1038. ps->image_h = cRows;
  1039. /* For error checking, the whole buffer is set to 10110010 (0xb2 - 178).
  1040. * This deliberately doesn't match the bits in the size test image which are
  1041. * outside the image; these are set to 0xff (all 1). To make the row
  1042. * comparison work in the 'size' test case the size rows are pre-initialized
  1043. * to the same value prior to calling 'standard_row'.
  1044. */
  1045. memset(ps->image, 178, cb);
  1046. /* Then put in the marks. */
  1047. while (--nImages >= 0)
  1048. {
  1049. png_uint_32 y;
  1050. for (y=0; y<cRows; ++y)
  1051. {
  1052. png_bytep row = store_image_row(ps, pp, nImages, y);
  1053. /* The markers: */
  1054. row[-2] = 190;
  1055. row[-1] = 239;
  1056. row[cbRow] = 222;
  1057. row[cbRow+1] = 173;
  1058. row[cbRow+2] = 17;
  1059. }
  1060. }
  1061. }
  1062. #ifdef PNG_READ_SUPPORTED
  1063. static void
  1064. store_image_check(const png_store* ps, png_const_structp pp, int iImage)
  1065. {
  1066. png_const_bytep image = ps->image;
  1067. if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
  1068. png_error(pp, "image overwrite");
  1069. else
  1070. {
  1071. size_t cbRow = ps->cb_row;
  1072. png_uint_32 rows = ps->image_h;
  1073. image += iImage * (cbRow+5) * ps->image_h;
  1074. image += 2; /* skip image first row markers */
  1075. for (; rows > 0; --rows)
  1076. {
  1077. if (image[-2] != 190 || image[-1] != 239)
  1078. png_error(pp, "row start overwritten");
  1079. if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
  1080. image[cbRow+2] != 17)
  1081. png_error(pp, "row end overwritten");
  1082. image += cbRow+5;
  1083. }
  1084. }
  1085. }
  1086. #endif /* PNG_READ_SUPPORTED */
  1087. static int
  1088. valid_chunktype(png_uint_32 chunktype)
  1089. {
  1090. /* Each byte in the chunk type must be in one of the ranges 65..90, 97..122
  1091. * (both inclusive), so:
  1092. */
  1093. unsigned int i;
  1094. for (i=0; i<4; ++i)
  1095. {
  1096. unsigned int c = chunktype & 0xffU;
  1097. if (!((c >= 65U && c <= 90U) || (c >= 97U && c <= 122U)))
  1098. return 0;
  1099. chunktype >>= 8;
  1100. }
  1101. return 1; /* It's valid */
  1102. }
  1103. static void PNGCBAPI
  1104. store_write(png_structp ppIn, png_bytep pb, size_t st)
  1105. {
  1106. png_const_structp pp = ppIn;
  1107. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  1108. size_t writepos = ps->writepos;
  1109. png_uint_32 chunkpos = ps->chunkpos;
  1110. png_uint_32 chunktype = ps->chunktype;
  1111. png_uint_32 chunklen = ps->chunklen;
  1112. if (ps->pwrite != pp)
  1113. png_error(pp, "store state damaged");
  1114. /* Technically this is legal, but in practice libpng never writes more than
  1115. * the maximum chunk size at once so if it happens something weird has
  1116. * changed inside libpng (probably).
  1117. */
  1118. if (st > 0x7fffffffU)
  1119. png_error(pp, "unexpected write size");
  1120. /* Now process the bytes to be written. Do this in units of the space in the
  1121. * output (write) buffer or, at the start 4 bytes for the chunk type and
  1122. * length limited in any case by the amount of data.
  1123. */
  1124. while (st > 0)
  1125. {
  1126. if (writepos >= STORE_BUFFER_SIZE)
  1127. store_storenew(ps), writepos = 0;
  1128. if (chunkpos < 4)
  1129. {
  1130. png_byte b = *pb++;
  1131. --st;
  1132. chunklen = (chunklen << 8) + b;
  1133. ps->new.buffer[writepos++] = b;
  1134. ++chunkpos;
  1135. }
  1136. else if (chunkpos < 8)
  1137. {
  1138. png_byte b = *pb++;
  1139. --st;
  1140. chunktype = (chunktype << 8) + b;
  1141. ps->new.buffer[writepos++] = b;
  1142. if (++chunkpos == 8)
  1143. {
  1144. chunklen &= 0xffffffffU;
  1145. if (chunklen > 0x7fffffffU)
  1146. png_error(pp, "chunk length too great");
  1147. chunktype &= 0xffffffffU;
  1148. if (chunktype == CHUNK_IDAT)
  1149. {
  1150. if (chunklen > ~ps->IDAT_size)
  1151. png_error(pp, "pngvalid internal image too large");
  1152. ps->IDAT_size += chunklen;
  1153. }
  1154. else if (!valid_chunktype(chunktype))
  1155. png_error(pp, "invalid chunk type");
  1156. chunklen += 12; /* for header and CRC */
  1157. }
  1158. }
  1159. else /* chunkpos >= 8 */
  1160. {
  1161. size_t cb = st;
  1162. if (cb > STORE_BUFFER_SIZE - writepos)
  1163. cb = STORE_BUFFER_SIZE - writepos;
  1164. if (cb > chunklen - chunkpos/* bytes left in chunk*/)
  1165. cb = (size_t)/*SAFE*/(chunklen - chunkpos);
  1166. memcpy(ps->new.buffer + writepos, pb, cb);
  1167. chunkpos += (png_uint_32)/*SAFE*/cb;
  1168. pb += cb;
  1169. writepos += cb;
  1170. st -= cb;
  1171. if (chunkpos >= chunklen) /* must be equal */
  1172. chunkpos = chunktype = chunklen = 0;
  1173. }
  1174. } /* while (st > 0) */
  1175. ps->writepos = writepos;
  1176. ps->chunkpos = chunkpos;
  1177. ps->chunktype = chunktype;
  1178. ps->chunklen = chunklen;
  1179. }
  1180. static void PNGCBAPI
  1181. store_flush(png_structp ppIn)
  1182. {
  1183. UNUSED(ppIn) /*DOES NOTHING*/
  1184. }
  1185. #ifdef PNG_READ_SUPPORTED
  1186. static size_t
  1187. store_read_buffer_size(png_store *ps)
  1188. {
  1189. /* Return the bytes available for read in the current buffer. */
  1190. if (ps->next != &ps->current->data)
  1191. return STORE_BUFFER_SIZE;
  1192. return ps->current->datacount;
  1193. }
  1194. /* Return total bytes available for read. */
  1195. static size_t
  1196. store_read_buffer_avail(png_store *ps)
  1197. {
  1198. if (ps->current != NULL && ps->next != NULL)
  1199. {
  1200. png_store_buffer *next = &ps->current->data;
  1201. size_t cbAvail = ps->current->datacount;
  1202. while (next != ps->next && next != NULL)
  1203. {
  1204. next = next->prev;
  1205. cbAvail += STORE_BUFFER_SIZE;
  1206. }
  1207. if (next != ps->next)
  1208. png_error(ps->pread, "buffer read error");
  1209. if (cbAvail > ps->readpos)
  1210. return cbAvail - ps->readpos;
  1211. }
  1212. return 0;
  1213. }
  1214. static int
  1215. store_read_buffer_next(png_store *ps)
  1216. {
  1217. png_store_buffer *pbOld = ps->next;
  1218. png_store_buffer *pbNew = &ps->current->data;
  1219. if (pbOld != pbNew)
  1220. {
  1221. while (pbNew != NULL && pbNew->prev != pbOld)
  1222. pbNew = pbNew->prev;
  1223. if (pbNew != NULL)
  1224. {
  1225. ps->next = pbNew;
  1226. ps->readpos = 0;
  1227. return 1;
  1228. }
  1229. png_error(ps->pread, "buffer lost");
  1230. }
  1231. return 0; /* EOF or error */
  1232. }
  1233. /* Need separate implementation and callback to allow use of the same code
  1234. * during progressive read, where the io_ptr is set internally by libpng.
  1235. */
  1236. static void
  1237. store_read_imp(png_store *ps, png_bytep pb, size_t st)
  1238. {
  1239. if (ps->current == NULL || ps->next == NULL)
  1240. png_error(ps->pread, "store state damaged");
  1241. while (st > 0)
  1242. {
  1243. size_t cbAvail = store_read_buffer_size(ps) - ps->readpos;
  1244. if (cbAvail > 0)
  1245. {
  1246. if (cbAvail > st) cbAvail = st;
  1247. memcpy(pb, ps->next->buffer + ps->readpos, cbAvail);
  1248. st -= cbAvail;
  1249. pb += cbAvail;
  1250. ps->readpos += cbAvail;
  1251. }
  1252. else if (!store_read_buffer_next(ps))
  1253. png_error(ps->pread, "read beyond end of file");
  1254. }
  1255. }
  1256. static size_t
  1257. store_read_chunk(png_store *ps, png_bytep pb, size_t max, size_t min)
  1258. {
  1259. png_uint_32 chunklen = ps->chunklen;
  1260. png_uint_32 chunktype = ps->chunktype;
  1261. png_uint_32 chunkpos = ps->chunkpos;
  1262. size_t st = max;
  1263. if (st > 0) do
  1264. {
  1265. if (chunkpos >= chunklen) /* end of last chunk */
  1266. {
  1267. png_byte buffer[8];
  1268. /* Read the header of the next chunk: */
  1269. store_read_imp(ps, buffer, 8U);
  1270. chunklen = png_get_uint_32(buffer) + 12U;
  1271. chunktype = png_get_uint_32(buffer+4U);
  1272. chunkpos = 0U; /* Position read so far */
  1273. }
  1274. if (chunktype == CHUNK_IDAT)
  1275. {
  1276. png_uint_32 IDAT_pos = ps->IDAT_pos;
  1277. png_uint_32 IDAT_len = ps->IDAT_len;
  1278. png_uint_32 IDAT_size = ps->IDAT_size;
  1279. /* The IDAT headers are constructed here; skip the input header. */
  1280. if (chunkpos < 8U)
  1281. chunkpos = 8U;
  1282. if (IDAT_pos == IDAT_len)
  1283. {
  1284. png_byte random = random_byte();
  1285. /* Make a new IDAT chunk, if IDAT_len is 0 this is the first IDAT,
  1286. * if IDAT_size is 0 this is the end. At present this is set up
  1287. * using a random number so that there is a 25% chance before
  1288. * the start of the first IDAT chunk being 0 length.
  1289. */
  1290. if (IDAT_len == 0U) /* First IDAT */
  1291. {
  1292. switch (random & 3U)
  1293. {
  1294. case 0U: IDAT_len = 12U; break; /* 0 bytes */
  1295. case 1U: IDAT_len = 13U; break; /* 1 byte */
  1296. default: IDAT_len = random_u32();
  1297. IDAT_len %= IDAT_size;
  1298. IDAT_len += 13U; /* 1..IDAT_size bytes */
  1299. break;
  1300. }
  1301. }
  1302. else if (IDAT_size == 0U) /* all IDAT data read */
  1303. {
  1304. /* The last (IDAT) chunk should be positioned at the CRC now: */
  1305. if (chunkpos != chunklen-4U)
  1306. png_error(ps->pread, "internal: IDAT size mismatch");
  1307. /* The only option here is to add a zero length IDAT, this
  1308. * happens 25% of the time. Because of the check above
  1309. * chunklen-4U-chunkpos must be zero, we just need to skip the
  1310. * CRC now.
  1311. */
  1312. if ((random & 3U) == 0U)
  1313. IDAT_len = 12U; /* Output another 0 length IDAT */
  1314. else
  1315. {
  1316. /* End of IDATs, skip the CRC to make the code above load the
  1317. * next chunk header next time round.
  1318. */
  1319. png_byte buffer[4];
  1320. store_read_imp(ps, buffer, 4U);
  1321. chunkpos += 4U;
  1322. ps->IDAT_pos = IDAT_pos;
  1323. ps->IDAT_len = IDAT_len;
  1324. ps->IDAT_size = 0U;
  1325. continue; /* Read the next chunk */
  1326. }
  1327. }
  1328. else
  1329. {
  1330. /* Middle of IDATs, use 'random' to determine the number of bits
  1331. * to use in the IDAT length.
  1332. */
  1333. IDAT_len = random_u32();
  1334. IDAT_len &= (1U << (1U + random % ps->IDAT_bits)) - 1U;
  1335. if (IDAT_len > IDAT_size)
  1336. IDAT_len = IDAT_size;
  1337. IDAT_len += 12U; /* zero bytes may occur */
  1338. }
  1339. IDAT_pos = 0U;
  1340. ps->IDAT_crc = 0x35af061e; /* Ie: crc32(0UL, "IDAT", 4) */
  1341. } /* IDAT_pos == IDAT_len */
  1342. if (IDAT_pos < 8U) /* Return the header */ do
  1343. {
  1344. png_uint_32 b;
  1345. unsigned int shift;
  1346. if (IDAT_pos < 4U)
  1347. b = IDAT_len - 12U;
  1348. else
  1349. b = CHUNK_IDAT;
  1350. shift = 3U & IDAT_pos;
  1351. ++IDAT_pos;
  1352. if (shift < 3U)
  1353. b >>= 8U*(3U-shift);
  1354. *pb++ = 0xffU & b;
  1355. }
  1356. while (--st > 0 && IDAT_pos < 8);
  1357. else if (IDAT_pos < IDAT_len - 4U) /* I.e not the CRC */
  1358. {
  1359. if (chunkpos < chunklen-4U)
  1360. {
  1361. uInt avail = (uInt)-1;
  1362. if (avail > (IDAT_len-4U) - IDAT_pos)
  1363. avail = (uInt)/*SAFE*/((IDAT_len-4U) - IDAT_pos);
  1364. if (avail > st)
  1365. avail = (uInt)/*SAFE*/st;
  1366. if (avail > (chunklen-4U) - chunkpos)
  1367. avail = (uInt)/*SAFE*/((chunklen-4U) - chunkpos);
  1368. store_read_imp(ps, pb, avail);
  1369. ps->IDAT_crc = crc32(ps->IDAT_crc, pb, avail);
  1370. pb += (size_t)/*SAFE*/avail;
  1371. st -= (size_t)/*SAFE*/avail;
  1372. chunkpos += (png_uint_32)/*SAFE*/avail;
  1373. IDAT_size -= (png_uint_32)/*SAFE*/avail;
  1374. IDAT_pos += (png_uint_32)/*SAFE*/avail;
  1375. }
  1376. else /* skip the input CRC */
  1377. {
  1378. png_byte buffer[4];
  1379. store_read_imp(ps, buffer, 4U);
  1380. chunkpos += 4U;
  1381. }
  1382. }
  1383. else /* IDAT crc */ do
  1384. {
  1385. uLong b = ps->IDAT_crc;
  1386. unsigned int shift = (IDAT_len - IDAT_pos); /* 4..1 */
  1387. ++IDAT_pos;
  1388. if (shift > 1U)
  1389. b >>= 8U*(shift-1U);
  1390. *pb++ = 0xffU & b;
  1391. }
  1392. while (--st > 0 && IDAT_pos < IDAT_len);
  1393. ps->IDAT_pos = IDAT_pos;
  1394. ps->IDAT_len = IDAT_len;
  1395. ps->IDAT_size = IDAT_size;
  1396. }
  1397. else /* !IDAT */
  1398. {
  1399. /* If there is still some pending IDAT data after the IDAT chunks have
  1400. * been processed there is a problem:
  1401. */
  1402. if (ps->IDAT_len > 0 && ps->IDAT_size > 0)
  1403. png_error(ps->pread, "internal: missing IDAT data");
  1404. if (chunktype == CHUNK_IEND && ps->IDAT_len == 0U)
  1405. png_error(ps->pread, "internal: missing IDAT");
  1406. if (chunkpos < 8U) /* Return the header */ do
  1407. {
  1408. png_uint_32 b;
  1409. unsigned int shift;
  1410. if (chunkpos < 4U)
  1411. b = chunklen - 12U;
  1412. else
  1413. b = chunktype;
  1414. shift = 3U & chunkpos;
  1415. ++chunkpos;
  1416. if (shift < 3U)
  1417. b >>= 8U*(3U-shift);
  1418. *pb++ = 0xffU & b;
  1419. }
  1420. while (--st > 0 && chunkpos < 8);
  1421. else /* Return chunk bytes, including the CRC */
  1422. {
  1423. size_t avail = st;
  1424. if (avail > chunklen - chunkpos)
  1425. avail = (size_t)/*SAFE*/(chunklen - chunkpos);
  1426. store_read_imp(ps, pb, avail);
  1427. pb += avail;
  1428. st -= avail;
  1429. chunkpos += (png_uint_32)/*SAFE*/avail;
  1430. /* Check for end of chunk and end-of-file; don't try to read a new
  1431. * chunk header at this point unless instructed to do so by 'min'.
  1432. */
  1433. if (chunkpos >= chunklen && max-st >= min &&
  1434. store_read_buffer_avail(ps) == 0)
  1435. break;
  1436. }
  1437. } /* !IDAT */
  1438. }
  1439. while (st > 0);
  1440. ps->chunklen = chunklen;
  1441. ps->chunktype = chunktype;
  1442. ps->chunkpos = chunkpos;
  1443. return st; /* space left */
  1444. }
  1445. static void PNGCBAPI
  1446. store_read(png_structp ppIn, png_bytep pb, size_t st)
  1447. {
  1448. png_const_structp pp = ppIn;
  1449. png_store *ps = voidcast(png_store*, png_get_io_ptr(pp));
  1450. if (ps == NULL || ps->pread != pp)
  1451. png_error(pp, "bad store read call");
  1452. store_read_chunk(ps, pb, st, st);
  1453. }
  1454. static void
  1455. store_progressive_read(png_store *ps, png_structp pp, png_infop pi)
  1456. {
  1457. if (ps->pread != pp || ps->current == NULL || ps->next == NULL)
  1458. png_error(pp, "store state damaged (progressive)");
  1459. /* This is another Horowitz and Hill random noise generator. In this case
  1460. * the aim is to stress the progressive reader with truly horrible variable
  1461. * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
  1462. * is generated. We could probably just count from 1 to 32767 and get as
  1463. * good a result.
  1464. */
  1465. while (store_read_buffer_avail(ps) > 0)
  1466. {
  1467. static png_uint_32 noise = 2;
  1468. size_t cb;
  1469. png_byte buffer[512];
  1470. /* Generate 15 more bits of stuff: */
  1471. noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
  1472. cb = noise & 0x1ff;
  1473. cb -= store_read_chunk(ps, buffer, cb, 1);
  1474. png_process_data(pp, pi, buffer, cb);
  1475. }
  1476. }
  1477. #endif /* PNG_READ_SUPPORTED */
  1478. /* The caller must fill this in: */
  1479. static store_palette_entry *
  1480. store_write_palette(png_store *ps, int npalette)
  1481. {
  1482. if (ps->pwrite == NULL)
  1483. store_log(ps, NULL, "attempt to write palette without write stream", 1);
  1484. if (ps->palette != NULL)
  1485. png_error(ps->pwrite, "multiple store_write_palette calls");
  1486. /* This function can only return NULL if called with '0'! */
  1487. if (npalette > 0)
  1488. {
  1489. ps->palette = voidcast(store_palette_entry*, malloc(npalette *
  1490. sizeof *ps->palette));
  1491. if (ps->palette == NULL)
  1492. png_error(ps->pwrite, "store new palette: OOM");
  1493. ps->npalette = npalette;
  1494. }
  1495. return ps->palette;
  1496. }
  1497. #ifdef PNG_READ_SUPPORTED
  1498. static store_palette_entry *
  1499. store_current_palette(png_store *ps, int *npalette)
  1500. {
  1501. /* This is an internal error (the call has been made outside a read
  1502. * operation.)
  1503. */
  1504. if (ps->current == NULL)
  1505. {
  1506. store_log(ps, ps->pread, "no current stream for palette", 1);
  1507. return NULL;
  1508. }
  1509. /* The result may be null if there is no palette. */
  1510. *npalette = ps->current->npalette;
  1511. return ps->current->palette;
  1512. }
  1513. #endif /* PNG_READ_SUPPORTED */
  1514. /***************************** MEMORY MANAGEMENT*** ***************************/
  1515. #ifdef PNG_USER_MEM_SUPPORTED
  1516. /* A store_memory is simply the header for an allocated block of memory. The
  1517. * pointer returned to libpng is just after the end of the header block, the
  1518. * allocated memory is followed by a second copy of the 'mark'.
  1519. */
  1520. typedef struct store_memory
  1521. {
  1522. store_pool *pool; /* Originating pool */
  1523. struct store_memory *next; /* Singly linked list */
  1524. png_alloc_size_t size; /* Size of memory allocated */
  1525. png_byte mark[4]; /* ID marker */
  1526. } store_memory;
  1527. /* Handle a fatal error in memory allocation. This calls png_error if the
  1528. * libpng struct is non-NULL, else it outputs a message and returns. This means
  1529. * that a memory problem while libpng is running will abort (png_error) the
  1530. * handling of particular file while one in cleanup (after the destroy of the
  1531. * struct has returned) will simply keep going and free (or attempt to free)
  1532. * all the memory.
  1533. */
  1534. static void
  1535. store_pool_error(png_store *ps, png_const_structp pp, const char *msg)
  1536. {
  1537. if (pp != NULL)
  1538. png_error(pp, msg);
  1539. /* Else we have to do it ourselves. png_error eventually calls store_log,
  1540. * above. store_log accepts a NULL png_structp - it just changes what gets
  1541. * output by store_message.
  1542. */
  1543. store_log(ps, pp, msg, 1 /* error */);
  1544. }
  1545. static void
  1546. store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
  1547. {
  1548. /* Note that pp may be NULL (see store_pool_delete below), the caller has
  1549. * found 'memory' in pool->list *and* unlinked this entry, so this is a valid
  1550. * pointer (for sure), but the contents may have been trashed.
  1551. */
  1552. if (memory->pool != pool)
  1553. store_pool_error(pool->store, pp, "memory corrupted (pool)");
  1554. else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
  1555. store_pool_error(pool->store, pp, "memory corrupted (start)");
  1556. /* It should be safe to read the size field now. */
  1557. else
  1558. {
  1559. png_alloc_size_t cb = memory->size;
  1560. if (cb > pool->max)
  1561. store_pool_error(pool->store, pp, "memory corrupted (size)");
  1562. else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
  1563. != 0)
  1564. store_pool_error(pool->store, pp, "memory corrupted (end)");
  1565. /* Finally give the library a chance to find problems too: */
  1566. else
  1567. {
  1568. pool->current -= cb;
  1569. free(memory);
  1570. }
  1571. }
  1572. }
  1573. static void
  1574. store_pool_delete(png_store *ps, store_pool *pool)
  1575. {
  1576. if (pool->list != NULL)
  1577. {
  1578. fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
  1579. pool == &ps->read_memory_pool ? "read" : "write",
  1580. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1581. ps->current->name : "unknown file") : ps->wname);
  1582. ++ps->nerrors;
  1583. do
  1584. {
  1585. store_memory *next = pool->list;
  1586. pool->list = next->next;
  1587. next->next = NULL;
  1588. fprintf(stderr, "\t%lu bytes @ %p\n",
  1589. (unsigned long)next->size, (const void*)(next+1));
  1590. /* The NULL means this will always return, even if the memory is
  1591. * corrupted.
  1592. */
  1593. store_memory_free(NULL, pool, next);
  1594. }
  1595. while (pool->list != NULL);
  1596. }
  1597. /* And reset the other fields too for the next time. */
  1598. if (pool->max > pool->max_max) pool->max_max = pool->max;
  1599. pool->max = 0;
  1600. if (pool->current != 0) /* unexpected internal error */
  1601. fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
  1602. ps->test, pool == &ps->read_memory_pool ? "read" : "write",
  1603. pool == &ps->read_memory_pool ? (ps->current != NULL ?
  1604. ps->current->name : "unknown file") : ps->wname);
  1605. pool->current = 0;
  1606. if (pool->limit > pool->max_limit)
  1607. pool->max_limit = pool->limit;
  1608. pool->limit = 0;
  1609. if (pool->total > pool->max_total)
  1610. pool->max_total = pool->total;
  1611. pool->total = 0;
  1612. /* Get a new mark too. */
  1613. store_pool_mark(pool->mark);
  1614. }
  1615. /* The memory callbacks: */
  1616. static png_voidp PNGCBAPI
  1617. store_malloc(png_structp ppIn, png_alloc_size_t cb)
  1618. {
  1619. png_const_structp pp = ppIn;
  1620. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1621. store_memory *new = voidcast(store_memory*, malloc(cb + (sizeof *new) +
  1622. (sizeof pool->mark)));
  1623. if (new != NULL)
  1624. {
  1625. if (cb > pool->max)
  1626. pool->max = cb;
  1627. pool->current += cb;
  1628. if (pool->current > pool->limit)
  1629. pool->limit = pool->current;
  1630. pool->total += cb;
  1631. new->size = cb;
  1632. memcpy(new->mark, pool->mark, sizeof new->mark);
  1633. memcpy((png_byte*)(new+1) + cb, pool->mark, sizeof pool->mark);
  1634. new->pool = pool;
  1635. new->next = pool->list;
  1636. pool->list = new;
  1637. ++new;
  1638. }
  1639. else
  1640. {
  1641. /* NOTE: the PNG user malloc function cannot use the png_ptr it is passed
  1642. * other than to retrieve the allocation pointer! libpng calls the
  1643. * store_malloc callback in two basic cases:
  1644. *
  1645. * 1) From png_malloc; png_malloc will do a png_error itself if NULL is
  1646. * returned.
  1647. * 2) From png_struct or png_info structure creation; png_malloc is
  1648. * to return so cleanup can be performed.
  1649. *
  1650. * To handle this store_malloc can log a message, but can't do anything
  1651. * else.
  1652. */
  1653. store_log(pool->store, pp, "out of memory", 1 /* is_error */);
  1654. }
  1655. return new;
  1656. }
  1657. static void PNGCBAPI
  1658. store_free(png_structp ppIn, png_voidp memory)
  1659. {
  1660. png_const_structp pp = ppIn;
  1661. store_pool *pool = voidcast(store_pool*, png_get_mem_ptr(pp));
  1662. store_memory *this = voidcast(store_memory*, memory), **test;
  1663. /* Because libpng calls store_free with a dummy png_struct when deleting
  1664. * png_struct or png_info via png_destroy_struct_2 it is necessary to check
  1665. * the passed in png_structp to ensure it is valid, and not pass it to
  1666. * png_error if it is not.
  1667. */
  1668. if (pp != pool->store->pread && pp != pool->store->pwrite)
  1669. pp = NULL;
  1670. /* First check that this 'memory' really is valid memory - it must be in the
  1671. * pool list. If it is, use the shared memory_free function to free it.
  1672. */
  1673. --this;
  1674. for (test = &pool->list; *test != this; test = &(*test)->next)
  1675. {
  1676. if (*test == NULL)
  1677. {
  1678. store_pool_error(pool->store, pp, "bad pointer to free");
  1679. return;
  1680. }
  1681. }
  1682. /* Unlink this entry, *test == this. */
  1683. *test = this->next;
  1684. this->next = NULL;
  1685. store_memory_free(pp, pool, this);
  1686. }
  1687. #endif /* PNG_USER_MEM_SUPPORTED */
  1688. /* Setup functions. */
  1689. /* Cleanup when aborting a write or after storing the new file. */
  1690. static void
  1691. store_write_reset(png_store *ps)
  1692. {
  1693. if (ps->pwrite != NULL)
  1694. {
  1695. anon_context(ps);
  1696. Try
  1697. png_destroy_write_struct(&ps->pwrite, &ps->piwrite);
  1698. Catch_anonymous
  1699. {
  1700. /* memory corruption: continue. */
  1701. }
  1702. ps->pwrite = NULL;
  1703. ps->piwrite = NULL;
  1704. }
  1705. /* And make sure that all the memory has been freed - this will output
  1706. * spurious errors in the case of memory corruption above, but this is safe.
  1707. */
  1708. # ifdef PNG_USER_MEM_SUPPORTED
  1709. store_pool_delete(ps, &ps->write_memory_pool);
  1710. # endif
  1711. store_freenew(ps);
  1712. }
  1713. /* The following is the main write function, it returns a png_struct and,
  1714. * optionally, a png_info suitable for writiing a new PNG file. Use
  1715. * store_storefile above to record this file after it has been written. The
  1716. * returned libpng structures as destroyed by store_write_reset above.
  1717. */
  1718. static png_structp
  1719. set_store_for_write(png_store *ps, png_infopp ppi, const char *name)
  1720. {
  1721. anon_context(ps);
  1722. Try
  1723. {
  1724. if (ps->pwrite != NULL)
  1725. png_error(ps->pwrite, "write store already in use");
  1726. store_write_reset(ps);
  1727. safecat(ps->wname, sizeof ps->wname, 0, name);
  1728. /* Don't do the slow memory checks if doing a speed test, also if user
  1729. * memory is not supported we can't do it anyway.
  1730. */
  1731. # ifdef PNG_USER_MEM_SUPPORTED
  1732. if (!ps->speed)
  1733. ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
  1734. ps, store_error, store_warning, &ps->write_memory_pool,
  1735. store_malloc, store_free);
  1736. else
  1737. # endif
  1738. ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  1739. ps, store_error, store_warning);
  1740. png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
  1741. # ifdef PNG_SET_OPTION_SUPPORTED
  1742. {
  1743. int opt;
  1744. for (opt=0; opt<ps->noptions; ++opt)
  1745. if (png_set_option(ps->pwrite, ps->options[opt].option,
  1746. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1747. png_error(ps->pwrite, "png option invalid");
  1748. }
  1749. # endif
  1750. if (ppi != NULL)
  1751. *ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
  1752. }
  1753. Catch_anonymous
  1754. return NULL;
  1755. return ps->pwrite;
  1756. }
  1757. /* Cleanup when finished reading (either due to error or in the success case).
  1758. * This routine exists even when there is no read support to make the code
  1759. * tidier (avoid a mass of ifdefs) and so easier to maintain.
  1760. */
  1761. static void
  1762. store_read_reset(png_store *ps)
  1763. {
  1764. # ifdef PNG_READ_SUPPORTED
  1765. if (ps->pread != NULL)
  1766. {
  1767. anon_context(ps);
  1768. Try
  1769. png_destroy_read_struct(&ps->pread, &ps->piread, NULL);
  1770. Catch_anonymous
  1771. {
  1772. /* error already output: continue */
  1773. }
  1774. ps->pread = NULL;
  1775. ps->piread = NULL;
  1776. }
  1777. # endif
  1778. # ifdef PNG_USER_MEM_SUPPORTED
  1779. /* Always do this to be safe. */
  1780. store_pool_delete(ps, &ps->read_memory_pool);
  1781. # endif
  1782. ps->current = NULL;
  1783. ps->next = NULL;
  1784. ps->readpos = 0;
  1785. ps->validated = 0;
  1786. ps->chunkpos = 8;
  1787. ps->chunktype = 0;
  1788. ps->chunklen = 16;
  1789. ps->IDAT_size = 0;
  1790. }
  1791. #ifdef PNG_READ_SUPPORTED
  1792. static void
  1793. store_read_set(png_store *ps, png_uint_32 id)
  1794. {
  1795. png_store_file *pf = ps->saved;
  1796. while (pf != NULL)
  1797. {
  1798. if (pf->id == id)
  1799. {
  1800. ps->current = pf;
  1801. ps->next = NULL;
  1802. ps->IDAT_size = pf->IDAT_size;
  1803. ps->IDAT_bits = pf->IDAT_bits; /* just a cache */
  1804. ps->IDAT_len = 0;
  1805. ps->IDAT_pos = 0;
  1806. ps->IDAT_crc = 0UL;
  1807. store_read_buffer_next(ps);
  1808. return;
  1809. }
  1810. pf = pf->next;
  1811. }
  1812. {
  1813. size_t pos;
  1814. char msg[FILE_NAME_SIZE+64];
  1815. pos = standard_name_from_id(msg, sizeof msg, 0, id);
  1816. pos = safecat(msg, sizeof msg, pos, ": file not found");
  1817. png_error(ps->pread, msg);
  1818. }
  1819. }
  1820. /* The main interface for reading a saved file - pass the id number of the file
  1821. * to retrieve. Ids must be unique or the earlier file will be hidden. The API
  1822. * returns a png_struct and, optionally, a png_info. Both of these will be
  1823. * destroyed by store_read_reset above.
  1824. */
  1825. static png_structp
  1826. set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id,
  1827. const char *name)
  1828. {
  1829. /* Set the name for png_error */
  1830. safecat(ps->test, sizeof ps->test, 0, name);
  1831. if (ps->pread != NULL)
  1832. png_error(ps->pread, "read store already in use");
  1833. store_read_reset(ps);
  1834. /* Both the create APIs can return NULL if used in their default mode
  1835. * (because there is no other way of handling an error because the jmp_buf
  1836. * by default is stored in png_struct and that has not been allocated!)
  1837. * However, given that store_error works correctly in these circumstances
  1838. * we don't ever expect NULL in this program.
  1839. */
  1840. # ifdef PNG_USER_MEM_SUPPORTED
  1841. if (!ps->speed)
  1842. ps->pread = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, ps,
  1843. store_error, store_warning, &ps->read_memory_pool, store_malloc,
  1844. store_free);
  1845. else
  1846. # endif
  1847. ps->pread = png_create_read_struct(PNG_LIBPNG_VER_STRING, ps, store_error,
  1848. store_warning);
  1849. if (ps->pread == NULL)
  1850. {
  1851. struct exception_context *the_exception_context = &ps->exception_context;
  1852. store_log(ps, NULL, "png_create_read_struct returned NULL (unexpected)",
  1853. 1 /*error*/);
  1854. Throw ps;
  1855. }
  1856. # ifdef PNG_SET_OPTION_SUPPORTED
  1857. {
  1858. int opt;
  1859. for (opt=0; opt<ps->noptions; ++opt)
  1860. if (png_set_option(ps->pread, ps->options[opt].option,
  1861. ps->options[opt].setting) == PNG_OPTION_INVALID)
  1862. png_error(ps->pread, "png option invalid");
  1863. }
  1864. # endif
  1865. store_read_set(ps, id);
  1866. if (ppi != NULL)
  1867. *ppi = ps->piread = png_create_info_struct(ps->pread);
  1868. return ps->pread;
  1869. }
  1870. #endif /* PNG_READ_SUPPORTED */
  1871. /* The overall cleanup of a store simply calls the above then removes all the
  1872. * saved files. This does not delete the store itself.
  1873. */
  1874. static void
  1875. store_delete(png_store *ps)
  1876. {
  1877. store_write_reset(ps);
  1878. store_read_reset(ps);
  1879. store_freefile(&ps->saved);
  1880. store_image_free(ps, NULL);
  1881. }
  1882. /*********************** PNG FILE MODIFICATION ON READ ************************/
  1883. /* Files may be modified on read. The following structure contains a complete
  1884. * png_store together with extra members to handle modification and a special
  1885. * read callback for libpng. To use this the 'modifications' field must be set
  1886. * to a list of png_modification structures that actually perform the
  1887. * modification, otherwise a png_modifier is functionally equivalent to a
  1888. * png_store. There is a special read function, set_modifier_for_read, which
  1889. * replaces set_store_for_read.
  1890. */
  1891. typedef enum modifier_state
  1892. {
  1893. modifier_start, /* Initial value */
  1894. modifier_signature, /* Have a signature */
  1895. modifier_IHDR /* Have an IHDR */
  1896. } modifier_state;
  1897. typedef struct CIE_color
  1898. {
  1899. /* A single CIE tristimulus value, representing the unique response of a
  1900. * standard observer to a variety of light spectra. The observer recognizes
  1901. * all spectra that produce this response as the same color, therefore this
  1902. * is effectively a description of a color.
  1903. */
  1904. double X, Y, Z;
  1905. } CIE_color;
  1906. typedef struct color_encoding
  1907. {
  1908. /* A description of an (R,G,B) encoding of color (as defined above); this
  1909. * includes the actual colors of the (R,G,B) triples (1,0,0), (0,1,0) and
  1910. * (0,0,1) plus an encoding value that is used to encode the linear
  1911. * components R, G and B to give the actual values R^gamma, G^gamma and
  1912. * B^gamma that are stored.
  1913. */
  1914. double gamma; /* Encoding (file) gamma of space */
  1915. CIE_color red, green, blue; /* End points */
  1916. } color_encoding;
  1917. #ifdef PNG_READ_SUPPORTED
  1918. #if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED
  1919. static double
  1920. chromaticity_x(CIE_color c)
  1921. {
  1922. return c.X / (c.X + c.Y + c.Z);
  1923. }
  1924. static double
  1925. chromaticity_y(CIE_color c)
  1926. {
  1927. return c.Y / (c.X + c.Y + c.Z);
  1928. }
  1929. static CIE_color
  1930. white_point(const color_encoding *encoding)
  1931. {
  1932. CIE_color white;
  1933. white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
  1934. white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
  1935. white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
  1936. return white;
  1937. }
  1938. #endif /* READ_TRANSFORMS && READ_cHRM */
  1939. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  1940. static void
  1941. normalize_color_encoding(color_encoding *encoding)
  1942. {
  1943. const double whiteY = encoding->red.Y + encoding->green.Y +
  1944. encoding->blue.Y;
  1945. if (whiteY != 1)
  1946. {
  1947. encoding->red.X /= whiteY;
  1948. encoding->red.Y /= whiteY;
  1949. encoding->red.Z /= whiteY;
  1950. encoding->green.X /= whiteY;
  1951. encoding->green.Y /= whiteY;
  1952. encoding->green.Z /= whiteY;
  1953. encoding->blue.X /= whiteY;
  1954. encoding->blue.Y /= whiteY;
  1955. encoding->blue.Z /= whiteY;
  1956. }
  1957. }
  1958. #endif
  1959. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  1960. static size_t
  1961. safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
  1962. const color_encoding *e, double encoding_gamma)
  1963. {
  1964. if (e != 0)
  1965. {
  1966. if (encoding_gamma != 0)
  1967. pos = safecat(buffer, bufsize, pos, "(");
  1968. pos = safecat(buffer, bufsize, pos, "R(");
  1969. pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
  1970. pos = safecat(buffer, bufsize, pos, ",");
  1971. pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
  1972. pos = safecat(buffer, bufsize, pos, ",");
  1973. pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
  1974. pos = safecat(buffer, bufsize, pos, "),G(");
  1975. pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
  1976. pos = safecat(buffer, bufsize, pos, ",");
  1977. pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
  1978. pos = safecat(buffer, bufsize, pos, ",");
  1979. pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
  1980. pos = safecat(buffer, bufsize, pos, "),B(");
  1981. pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
  1982. pos = safecat(buffer, bufsize, pos, ",");
  1983. pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
  1984. pos = safecat(buffer, bufsize, pos, ",");
  1985. pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
  1986. pos = safecat(buffer, bufsize, pos, ")");
  1987. if (encoding_gamma != 0)
  1988. pos = safecat(buffer, bufsize, pos, ")");
  1989. }
  1990. if (encoding_gamma != 0)
  1991. {
  1992. pos = safecat(buffer, bufsize, pos, "^");
  1993. pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
  1994. }
  1995. return pos;
  1996. }
  1997. #endif /* READ_TRANSFORMS */
  1998. #endif /* PNG_READ_SUPPORTED */
  1999. typedef struct png_modifier
  2000. {
  2001. png_store this; /* I am a png_store */
  2002. struct png_modification *modifications; /* Changes to make */
  2003. modifier_state state; /* My state */
  2004. /* Information from IHDR: */
  2005. png_byte bit_depth; /* From IHDR */
  2006. png_byte colour_type; /* From IHDR */
  2007. /* While handling PLTE, IDAT and IEND these chunks may be pended to allow
  2008. * other chunks to be inserted.
  2009. */
  2010. png_uint_32 pending_len;
  2011. png_uint_32 pending_chunk;
  2012. /* Test values */
  2013. double *gammas;
  2014. unsigned int ngammas;
  2015. unsigned int ngamma_tests; /* Number of gamma tests to run*/
  2016. double current_gamma; /* 0 if not set */
  2017. const color_encoding *encodings;
  2018. unsigned int nencodings;
  2019. const color_encoding *current_encoding; /* If an encoding has been set */
  2020. unsigned int encoding_counter; /* For iteration */
  2021. int encoding_ignored; /* Something overwrote it */
  2022. /* Control variables used to iterate through possible encodings, the
  2023. * following must be set to 0 and tested by the function that uses the
  2024. * png_modifier because the modifier only sets it to 1 (true.)
  2025. */
  2026. unsigned int repeat :1; /* Repeat this transform test. */
  2027. unsigned int test_uses_encoding :1;
  2028. /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */
  2029. png_byte sbitlow;
  2030. /* Error control - these are the limits on errors accepted by the gamma tests
  2031. * below.
  2032. */
  2033. double maxout8; /* Maximum output value error */
  2034. double maxabs8; /* Absolute sample error 0..1 */
  2035. double maxcalc8; /* Absolute sample error 0..1 */
  2036. double maxpc8; /* Percentage sample error 0..100% */
  2037. double maxout16; /* Maximum output value error */
  2038. double maxabs16; /* Absolute sample error 0..1 */
  2039. double maxcalc16;/* Absolute sample error 0..1 */
  2040. double maxcalcG; /* Absolute sample error 0..1 */
  2041. double maxpc16; /* Percentage sample error 0..100% */
  2042. /* This is set by transforms that need to allow a higher limit, it is an
  2043. * internal check on pngvalid to ensure that the calculated error limits are
  2044. * not ridiculous; without this it is too easy to make a mistake in pngvalid
  2045. * that allows any value through.
  2046. *
  2047. * NOTE: this is not checked in release builds.
  2048. */
  2049. double limit; /* limit on error values, normally 4E-3 */
  2050. /* Log limits - values above this are logged, but not necessarily
  2051. * warned.
  2052. */
  2053. double log8; /* Absolute error in 8 bits to log */
  2054. double log16; /* Absolute error in 16 bits to log */
  2055. /* Logged 8 and 16 bit errors ('output' values): */
  2056. double error_gray_2;
  2057. double error_gray_4;
  2058. double error_gray_8;
  2059. double error_gray_16;
  2060. double error_color_8;
  2061. double error_color_16;
  2062. double error_indexed;
  2063. /* Flags: */
  2064. /* Whether to call png_read_update_info, not png_read_start_image, and how
  2065. * many times to call it.
  2066. */
  2067. int use_update_info;
  2068. /* Whether or not to interlace. */
  2069. int interlace_type :9; /* int, but must store '1' */
  2070. /* Run the standard tests? */
  2071. unsigned int test_standard :1;
  2072. /* Run the odd-sized image and interlace read/write tests? */
  2073. unsigned int test_size :1;
  2074. /* Run tests on reading with a combination of transforms, */
  2075. unsigned int test_transform :1;
  2076. unsigned int test_tRNS :1; /* Includes tRNS images */
  2077. /* When to use the use_input_precision option, this controls the gamma
  2078. * validation code checks. If set any value that is within the transformed
  2079. * range input-.5 to input+.5 will be accepted, otherwise the value must be
  2080. * within the normal limits. It should not be necessary to set this; the
  2081. * result should always be exact within the permitted error limits.
  2082. */
  2083. unsigned int use_input_precision :1;
  2084. unsigned int use_input_precision_sbit :1;
  2085. unsigned int use_input_precision_16to8 :1;
  2086. /* If set assume that the calculation bit depth is set by the input
  2087. * precision, not the output precision.
  2088. */
  2089. unsigned int calculations_use_input_precision :1;
  2090. /* If set assume that the calculations are done in 16 bits even if the sample
  2091. * depth is 8 bits.
  2092. */
  2093. unsigned int assume_16_bit_calculations :1;
  2094. /* Which gamma tests to run: */
  2095. unsigned int test_gamma_threshold :1;
  2096. unsigned int test_gamma_transform :1; /* main tests */
  2097. unsigned int test_gamma_sbit :1;
  2098. unsigned int test_gamma_scale16 :1;
  2099. unsigned int test_gamma_background :1;
  2100. unsigned int test_gamma_alpha_mode :1;
  2101. unsigned int test_gamma_expand16 :1;
  2102. unsigned int test_exhaustive :1;
  2103. /* Whether or not to run the low-bit-depth grayscale tests. This fails on
  2104. * gamma images in some cases because of gross inaccuracies in the grayscale
  2105. * gamma handling for low bit depth.
  2106. */
  2107. unsigned int test_lbg :1;
  2108. unsigned int test_lbg_gamma_threshold :1;
  2109. unsigned int test_lbg_gamma_transform :1;
  2110. unsigned int test_lbg_gamma_sbit :1;
  2111. unsigned int test_lbg_gamma_composition :1;
  2112. unsigned int log :1; /* Log max error */
  2113. /* Buffer information, the buffer size limits the size of the chunks that can
  2114. * be modified - they must fit (including header and CRC) into the buffer!
  2115. */
  2116. size_t flush; /* Count of bytes to flush */
  2117. size_t buffer_count; /* Bytes in buffer */
  2118. size_t buffer_position; /* Position in buffer */
  2119. png_byte buffer[1024];
  2120. } png_modifier;
  2121. /* This returns true if the test should be stopped now because it has already
  2122. * failed and it is running silently.
  2123. */
  2124. static int fail(png_modifier *pm)
  2125. {
  2126. return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
  2127. (pm->this.treat_warnings_as_errors && pm->this.nwarnings > 0));
  2128. }
  2129. static void
  2130. modifier_init(png_modifier *pm)
  2131. {
  2132. memset(pm, 0, sizeof *pm);
  2133. store_init(&pm->this);
  2134. pm->modifications = NULL;
  2135. pm->state = modifier_start;
  2136. pm->sbitlow = 1U;
  2137. pm->ngammas = 0;
  2138. pm->ngamma_tests = 0;
  2139. pm->gammas = 0;
  2140. pm->current_gamma = 0;
  2141. pm->encodings = 0;
  2142. pm->nencodings = 0;
  2143. pm->current_encoding = 0;
  2144. pm->encoding_counter = 0;
  2145. pm->encoding_ignored = 0;
  2146. pm->repeat = 0;
  2147. pm->test_uses_encoding = 0;
  2148. pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0;
  2149. pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0;
  2150. pm->maxcalcG = 0;
  2151. pm->limit = 4E-3;
  2152. pm->log8 = pm->log16 = 0; /* Means 'off' */
  2153. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0;
  2154. pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0;
  2155. pm->error_indexed = 0;
  2156. pm->use_update_info = 0;
  2157. pm->interlace_type = PNG_INTERLACE_NONE;
  2158. pm->test_standard = 0;
  2159. pm->test_size = 0;
  2160. pm->test_transform = 0;
  2161. # ifdef PNG_WRITE_tRNS_SUPPORTED
  2162. pm->test_tRNS = 1;
  2163. # else
  2164. pm->test_tRNS = 0;
  2165. # endif
  2166. pm->use_input_precision = 0;
  2167. pm->use_input_precision_sbit = 0;
  2168. pm->use_input_precision_16to8 = 0;
  2169. pm->calculations_use_input_precision = 0;
  2170. pm->assume_16_bit_calculations = 0;
  2171. pm->test_gamma_threshold = 0;
  2172. pm->test_gamma_transform = 0;
  2173. pm->test_gamma_sbit = 0;
  2174. pm->test_gamma_scale16 = 0;
  2175. pm->test_gamma_background = 0;
  2176. pm->test_gamma_alpha_mode = 0;
  2177. pm->test_gamma_expand16 = 0;
  2178. pm->test_lbg = 1;
  2179. pm->test_lbg_gamma_threshold = 1;
  2180. pm->test_lbg_gamma_transform = 1;
  2181. pm->test_lbg_gamma_sbit = 1;
  2182. pm->test_lbg_gamma_composition = 1;
  2183. pm->test_exhaustive = 0;
  2184. pm->log = 0;
  2185. /* Rely on the memset for all the other fields - there are no pointers */
  2186. }
  2187. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  2188. /* This controls use of checks that explicitly know how libpng digitizes the
  2189. * samples in calculations; setting this circumvents simple error limit checking
  2190. * in the rgb_to_gray check, replacing it with an exact copy of the libpng 1.5
  2191. * algorithm.
  2192. */
  2193. #define DIGITIZE PNG_LIBPNG_VER < 10700
  2194. /* If pm->calculations_use_input_precision is set then operations will happen
  2195. * with the precision of the input, not the precision of the output depth.
  2196. *
  2197. * If pm->assume_16_bit_calculations is set then even 8 bit calculations use 16
  2198. * bit precision. This only affects those of the following limits that pertain
  2199. * to a calculation - not a digitization operation - unless the following API is
  2200. * called directly.
  2201. */
  2202. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  2203. #if DIGITIZE
  2204. static double digitize(double value, int depth, int do_round)
  2205. {
  2206. /* 'value' is in the range 0 to 1, the result is the same value rounded to a
  2207. * multiple of the digitization factor - 8 or 16 bits depending on both the
  2208. * sample depth and the 'assume' setting. Digitization is normally by
  2209. * rounding and 'do_round' should be 1, if it is 0 the digitized value will
  2210. * be truncated.
  2211. */
  2212. unsigned int digitization_factor = (1U << depth) - 1;
  2213. /* Limiting the range is done as a convenience to the caller - it's easier to
  2214. * do it once here than every time at the call site.
  2215. */
  2216. if (value <= 0)
  2217. value = 0;
  2218. else if (value >= 1)
  2219. value = 1;
  2220. value *= digitization_factor;
  2221. if (do_round) value += .5;
  2222. return floor(value)/digitization_factor;
  2223. }
  2224. #endif
  2225. #endif /* RGB_TO_GRAY */
  2226. #ifdef PNG_READ_GAMMA_SUPPORTED
  2227. static double abserr(const png_modifier *pm, int in_depth, int out_depth)
  2228. {
  2229. /* Absolute error permitted in linear values - affected by the bit depth of
  2230. * the calculations.
  2231. */
  2232. if (pm->assume_16_bit_calculations ||
  2233. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2234. return pm->maxabs16;
  2235. else
  2236. return pm->maxabs8;
  2237. }
  2238. static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
  2239. {
  2240. /* Error in the linear composition arithmetic - only relevant when
  2241. * composition actually happens (0 < alpha < 1).
  2242. */
  2243. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2244. return pm->maxcalc16;
  2245. else if (pm->assume_16_bit_calculations)
  2246. return pm->maxcalcG;
  2247. else
  2248. return pm->maxcalc8;
  2249. }
  2250. static double pcerr(const png_modifier *pm, int in_depth, int out_depth)
  2251. {
  2252. /* Percentage error permitted in the linear values. Note that the specified
  2253. * value is a percentage but this routine returns a simple number.
  2254. */
  2255. if (pm->assume_16_bit_calculations ||
  2256. (pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2257. return pm->maxpc16 * .01;
  2258. else
  2259. return pm->maxpc8 * .01;
  2260. }
  2261. /* Output error - the error in the encoded value. This is determined by the
  2262. * digitization of the output so can be +/-0.5 in the actual output value. In
  2263. * the expand_16 case with the current code in libpng the expand happens after
  2264. * all the calculations are done in 8 bit arithmetic, so even though the output
  2265. * depth is 16 the output error is determined by the 8 bit calculation.
  2266. *
  2267. * This limit is not determined by the bit depth of internal calculations.
  2268. *
  2269. * The specified parameter does *not* include the base .5 digitization error but
  2270. * it is added here.
  2271. */
  2272. static double outerr(const png_modifier *pm, int in_depth, int out_depth)
  2273. {
  2274. /* There is a serious error in the 2 and 4 bit grayscale transform because
  2275. * the gamma table value (8 bits) is simply shifted, not rounded, so the
  2276. * error in 4 bit grayscale gamma is up to the value below. This is a hack
  2277. * to allow pngvalid to succeed:
  2278. *
  2279. * TODO: fix this in libpng
  2280. */
  2281. if (out_depth == 2)
  2282. return .73182-.5;
  2283. if (out_depth == 4)
  2284. return .90644-.5;
  2285. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2286. return pm->maxout16;
  2287. /* This is the case where the value was calculated at 8-bit precision then
  2288. * scaled to 16 bits.
  2289. */
  2290. else if (out_depth == 16)
  2291. return pm->maxout8 * 257;
  2292. else
  2293. return pm->maxout8;
  2294. }
  2295. /* This does the same thing as the above however it returns the value to log,
  2296. * rather than raising a warning. This is useful for debugging to track down
  2297. * exactly what set of parameters cause high error values.
  2298. */
  2299. static double outlog(const png_modifier *pm, int in_depth, int out_depth)
  2300. {
  2301. /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535)
  2302. * and so must be adjusted for low bit depth grayscale:
  2303. */
  2304. if (out_depth <= 8)
  2305. {
  2306. if (pm->log8 == 0) /* switched off */
  2307. return 256;
  2308. if (out_depth < 8)
  2309. return pm->log8 / 255 * ((1<<out_depth)-1);
  2310. return pm->log8;
  2311. }
  2312. if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
  2313. {
  2314. if (pm->log16 == 0)
  2315. return 65536;
  2316. return pm->log16;
  2317. }
  2318. /* This is the case where the value was calculated at 8-bit precision then
  2319. * scaled to 16 bits.
  2320. */
  2321. if (pm->log8 == 0)
  2322. return 65536;
  2323. return pm->log8 * 257;
  2324. }
  2325. /* This complements the above by providing the appropriate quantization for the
  2326. * final value. Normally this would just be quantization to an integral value,
  2327. * but in the 8 bit calculation case it's actually quantization to a multiple of
  2328. * 257!
  2329. */
  2330. static int output_quantization_factor(const png_modifier *pm, int in_depth,
  2331. int out_depth)
  2332. {
  2333. if (out_depth == 16 && in_depth != 16 &&
  2334. pm->calculations_use_input_precision)
  2335. return 257;
  2336. else
  2337. return 1;
  2338. }
  2339. #endif /* PNG_READ_GAMMA_SUPPORTED */
  2340. /* One modification structure must be provided for each chunk to be modified (in
  2341. * fact more than one can be provided if multiple separate changes are desired
  2342. * for a single chunk.) Modifications include adding a new chunk when a
  2343. * suitable chunk does not exist.
  2344. *
  2345. * The caller of modify_fn will reset the CRC of the chunk and record 'modified'
  2346. * or 'added' as appropriate if the modify_fn returns 1 (true). If the
  2347. * modify_fn is NULL the chunk is simply removed.
  2348. */
  2349. typedef struct png_modification
  2350. {
  2351. struct png_modification *next;
  2352. png_uint_32 chunk;
  2353. /* If the following is NULL all matching chunks will be removed: */
  2354. int (*modify_fn)(struct png_modifier *pm,
  2355. struct png_modification *me, int add);
  2356. /* If the following is set to PLTE, IDAT or IEND and the chunk has not been
  2357. * found and modified (and there is a modify_fn) the modify_fn will be called
  2358. * to add the chunk before the relevant chunk.
  2359. */
  2360. png_uint_32 add;
  2361. unsigned int modified :1; /* Chunk was modified */
  2362. unsigned int added :1; /* Chunk was added */
  2363. unsigned int removed :1; /* Chunk was removed */
  2364. } png_modification;
  2365. static void
  2366. modification_reset(png_modification *pmm)
  2367. {
  2368. if (pmm != NULL)
  2369. {
  2370. pmm->modified = 0;
  2371. pmm->added = 0;
  2372. pmm->removed = 0;
  2373. modification_reset(pmm->next);
  2374. }
  2375. }
  2376. static void
  2377. modification_init(png_modification *pmm)
  2378. {
  2379. memset(pmm, 0, sizeof *pmm);
  2380. pmm->next = NULL;
  2381. pmm->chunk = 0;
  2382. pmm->modify_fn = NULL;
  2383. pmm->add = 0;
  2384. modification_reset(pmm);
  2385. }
  2386. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  2387. static void
  2388. modifier_current_encoding(const png_modifier *pm, color_encoding *ce)
  2389. {
  2390. if (pm->current_encoding != 0)
  2391. *ce = *pm->current_encoding;
  2392. else
  2393. memset(ce, 0, sizeof *ce);
  2394. ce->gamma = pm->current_gamma;
  2395. }
  2396. #endif
  2397. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  2398. static size_t
  2399. safecat_current_encoding(char *buffer, size_t bufsize, size_t pos,
  2400. const png_modifier *pm)
  2401. {
  2402. pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding,
  2403. pm->current_gamma);
  2404. if (pm->encoding_ignored)
  2405. pos = safecat(buffer, bufsize, pos, "[overridden]");
  2406. return pos;
  2407. }
  2408. #endif
  2409. /* Iterate through the usefully testable color encodings. An encoding is one
  2410. * of:
  2411. *
  2412. * 1) Nothing (no color space, no gamma).
  2413. * 2) Just a gamma value from the gamma array (including 1.0)
  2414. * 3) A color space from the encodings array with the corresponding gamma.
  2415. * 4) The same, but with gamma 1.0 (only really useful with 16 bit calculations)
  2416. *
  2417. * The iterator selects these in turn, the randomizer selects one at random,
  2418. * which is used depends on the setting of the 'test_exhaustive' flag. Notice
  2419. * that this function changes the colour space encoding so it must only be
  2420. * called on completion of the previous test. This is what 'modifier_reset'
  2421. * does, below.
  2422. *
  2423. * After the function has been called the 'repeat' flag will still be set; the
  2424. * caller of modifier_reset must reset it at the start of each run of the test!
  2425. */
  2426. static unsigned int
  2427. modifier_total_encodings(const png_modifier *pm)
  2428. {
  2429. return 1 + /* (1) nothing */
  2430. pm->ngammas + /* (2) gamma values to test */
  2431. pm->nencodings + /* (3) total number of encodings */
  2432. /* The following test only works after the first time through the
  2433. * png_modifier code because 'bit_depth' is set when the IHDR is read.
  2434. * modifier_reset, below, preserves the setting until after it has called
  2435. * the iterate function (also below.)
  2436. *
  2437. * For this reason do not rely on this function outside a call to
  2438. * modifier_reset.
  2439. */
  2440. ((pm->bit_depth == 16 || pm->assume_16_bit_calculations) ?
  2441. pm->nencodings : 0); /* (4) encodings with gamma == 1.0 */
  2442. }
  2443. static void
  2444. modifier_encoding_iterate(png_modifier *pm)
  2445. {
  2446. if (!pm->repeat && /* Else something needs the current encoding again. */
  2447. pm->test_uses_encoding) /* Some transform is encoding dependent */
  2448. {
  2449. if (pm->test_exhaustive)
  2450. {
  2451. if (++pm->encoding_counter >= modifier_total_encodings(pm))
  2452. pm->encoding_counter = 0; /* This will stop the repeat */
  2453. }
  2454. else
  2455. {
  2456. /* Not exhaustive - choose an encoding at random; generate a number in
  2457. * the range 1..(max-1), so the result is always non-zero:
  2458. */
  2459. if (pm->encoding_counter == 0)
  2460. pm->encoding_counter = random_mod(modifier_total_encodings(pm)-1)+1;
  2461. else
  2462. pm->encoding_counter = 0;
  2463. }
  2464. if (pm->encoding_counter > 0)
  2465. pm->repeat = 1;
  2466. }
  2467. else if (!pm->repeat)
  2468. pm->encoding_counter = 0;
  2469. }
  2470. static void
  2471. modifier_reset(png_modifier *pm)
  2472. {
  2473. store_read_reset(&pm->this);
  2474. pm->limit = 4E-3;
  2475. pm->pending_len = pm->pending_chunk = 0;
  2476. pm->flush = pm->buffer_count = pm->buffer_position = 0;
  2477. pm->modifications = NULL;
  2478. pm->state = modifier_start;
  2479. modifier_encoding_iterate(pm);
  2480. /* The following must be set in the next run. In particular
  2481. * test_uses_encodings must be set in the _ini function of each transform
  2482. * that looks at the encodings. (Not the 'add' function!)
  2483. */
  2484. pm->test_uses_encoding = 0;
  2485. pm->current_gamma = 0;
  2486. pm->current_encoding = 0;
  2487. pm->encoding_ignored = 0;
  2488. /* These only become value after IHDR is read: */
  2489. pm->bit_depth = pm->colour_type = 0;
  2490. }
  2491. /* The following must be called before anything else to get the encoding set up
  2492. * on the modifier. In particular it must be called before the transform init
  2493. * functions are called.
  2494. */
  2495. static void
  2496. modifier_set_encoding(png_modifier *pm)
  2497. {
  2498. /* Set the encoding to the one specified by the current encoding counter,
  2499. * first clear out all the settings - this corresponds to an encoding_counter
  2500. * of 0.
  2501. */
  2502. pm->current_gamma = 0;
  2503. pm->current_encoding = 0;
  2504. pm->encoding_ignored = 0; /* not ignored yet - happens in _ini functions. */
  2505. /* Now, if required, set the gamma and encoding fields. */
  2506. if (pm->encoding_counter > 0)
  2507. {
  2508. /* The gammas[] array is an array of screen gammas, not encoding gammas,
  2509. * so we need the inverse:
  2510. */
  2511. if (pm->encoding_counter <= pm->ngammas)
  2512. pm->current_gamma = 1/pm->gammas[pm->encoding_counter-1];
  2513. else
  2514. {
  2515. unsigned int i = pm->encoding_counter - pm->ngammas;
  2516. if (i >= pm->nencodings)
  2517. {
  2518. i %= pm->nencodings;
  2519. pm->current_gamma = 1; /* Linear, only in the 16 bit case */
  2520. }
  2521. else
  2522. pm->current_gamma = pm->encodings[i].gamma;
  2523. pm->current_encoding = pm->encodings + i;
  2524. }
  2525. }
  2526. }
  2527. /* Enquiry functions to find out what is set. Notice that there is an implicit
  2528. * assumption below that the first encoding in the list is the one for sRGB.
  2529. */
  2530. static int
  2531. modifier_color_encoding_is_sRGB(const png_modifier *pm)
  2532. {
  2533. return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
  2534. pm->current_encoding->gamma == pm->current_gamma;
  2535. }
  2536. static int
  2537. modifier_color_encoding_is_set(const png_modifier *pm)
  2538. {
  2539. return pm->current_gamma != 0;
  2540. }
  2541. /* The guts of modification are performed during a read. */
  2542. static void
  2543. modifier_crc(png_bytep buffer)
  2544. {
  2545. /* Recalculate the chunk CRC - a complete chunk must be in
  2546. * the buffer, at the start.
  2547. */
  2548. uInt datalen = png_get_uint_32(buffer);
  2549. uLong crc = crc32(0, buffer+4, datalen+4);
  2550. /* The cast to png_uint_32 is safe because a crc32 is always a 32 bit value.
  2551. */
  2552. png_save_uint_32(buffer+datalen+8, (png_uint_32)crc);
  2553. }
  2554. static void
  2555. modifier_setbuffer(png_modifier *pm)
  2556. {
  2557. modifier_crc(pm->buffer);
  2558. pm->buffer_count = png_get_uint_32(pm->buffer)+12;
  2559. pm->buffer_position = 0;
  2560. }
  2561. /* Separate the callback into the actual implementation (which is passed the
  2562. * png_modifier explicitly) and the callback, which gets the modifier from the
  2563. * png_struct.
  2564. */
  2565. static void
  2566. modifier_read_imp(png_modifier *pm, png_bytep pb, size_t st)
  2567. {
  2568. while (st > 0)
  2569. {
  2570. size_t cb;
  2571. png_uint_32 len, chunk;
  2572. png_modification *mod;
  2573. if (pm->buffer_position >= pm->buffer_count) switch (pm->state)
  2574. {
  2575. static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
  2576. case modifier_start:
  2577. store_read_chunk(&pm->this, pm->buffer, 8, 8); /* signature. */
  2578. pm->buffer_count = 8;
  2579. pm->buffer_position = 0;
  2580. if (memcmp(pm->buffer, sign, 8) != 0)
  2581. png_error(pm->this.pread, "invalid PNG file signature");
  2582. pm->state = modifier_signature;
  2583. break;
  2584. case modifier_signature:
  2585. store_read_chunk(&pm->this, pm->buffer, 13+12, 13+12); /* IHDR */
  2586. pm->buffer_count = 13+12;
  2587. pm->buffer_position = 0;
  2588. if (png_get_uint_32(pm->buffer) != 13 ||
  2589. png_get_uint_32(pm->buffer+4) != CHUNK_IHDR)
  2590. png_error(pm->this.pread, "invalid IHDR");
  2591. /* Check the list of modifiers for modifications to the IHDR. */
  2592. mod = pm->modifications;
  2593. while (mod != NULL)
  2594. {
  2595. if (mod->chunk == CHUNK_IHDR && mod->modify_fn &&
  2596. (*mod->modify_fn)(pm, mod, 0))
  2597. {
  2598. mod->modified = 1;
  2599. modifier_setbuffer(pm);
  2600. }
  2601. /* Ignore removal or add if IHDR! */
  2602. mod = mod->next;
  2603. }
  2604. /* Cache information from the IHDR (the modified one.) */
  2605. pm->bit_depth = pm->buffer[8+8];
  2606. pm->colour_type = pm->buffer[8+8+1];
  2607. pm->state = modifier_IHDR;
  2608. pm->flush = 0;
  2609. break;
  2610. case modifier_IHDR:
  2611. default:
  2612. /* Read a new chunk and process it until we see PLTE, IDAT or
  2613. * IEND. 'flush' indicates that there is still some data to
  2614. * output from the preceding chunk.
  2615. */
  2616. if ((cb = pm->flush) > 0)
  2617. {
  2618. if (cb > st) cb = st;
  2619. pm->flush -= cb;
  2620. store_read_chunk(&pm->this, pb, cb, cb);
  2621. pb += cb;
  2622. st -= cb;
  2623. if (st == 0) return;
  2624. }
  2625. /* No more bytes to flush, read a header, or handle a pending
  2626. * chunk.
  2627. */
  2628. if (pm->pending_chunk != 0)
  2629. {
  2630. png_save_uint_32(pm->buffer, pm->pending_len);
  2631. png_save_uint_32(pm->buffer+4, pm->pending_chunk);
  2632. pm->pending_len = 0;
  2633. pm->pending_chunk = 0;
  2634. }
  2635. else
  2636. store_read_chunk(&pm->this, pm->buffer, 8, 8);
  2637. pm->buffer_count = 8;
  2638. pm->buffer_position = 0;
  2639. /* Check for something to modify or a terminator chunk. */
  2640. len = png_get_uint_32(pm->buffer);
  2641. chunk = png_get_uint_32(pm->buffer+4);
  2642. /* Terminators first, they may have to be delayed for added
  2643. * chunks
  2644. */
  2645. if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT ||
  2646. chunk == CHUNK_IEND)
  2647. {
  2648. mod = pm->modifications;
  2649. while (mod != NULL)
  2650. {
  2651. if ((mod->add == chunk ||
  2652. (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) &&
  2653. mod->modify_fn != NULL && !mod->modified && !mod->added)
  2654. {
  2655. /* Regardless of what the modify function does do not run
  2656. * this again.
  2657. */
  2658. mod->added = 1;
  2659. if ((*mod->modify_fn)(pm, mod, 1 /*add*/))
  2660. {
  2661. /* Reset the CRC on a new chunk */
  2662. if (pm->buffer_count > 0)
  2663. modifier_setbuffer(pm);
  2664. else
  2665. {
  2666. pm->buffer_position = 0;
  2667. mod->removed = 1;
  2668. }
  2669. /* The buffer has been filled with something (we assume)
  2670. * so output this. Pend the current chunk.
  2671. */
  2672. pm->pending_len = len;
  2673. pm->pending_chunk = chunk;
  2674. break; /* out of while */
  2675. }
  2676. }
  2677. mod = mod->next;
  2678. }
  2679. /* Don't do any further processing if the buffer was modified -
  2680. * otherwise the code will end up modifying a chunk that was
  2681. * just added.
  2682. */
  2683. if (mod != NULL)
  2684. break; /* out of switch */
  2685. }
  2686. /* If we get to here then this chunk may need to be modified. To
  2687. * do this it must be less than 1024 bytes in total size, otherwise
  2688. * it just gets flushed.
  2689. */
  2690. if (len+12 <= sizeof pm->buffer)
  2691. {
  2692. size_t s = len+12-pm->buffer_count;
  2693. store_read_chunk(&pm->this, pm->buffer+pm->buffer_count, s, s);
  2694. pm->buffer_count = len+12;
  2695. /* Check for a modification, else leave it be. */
  2696. mod = pm->modifications;
  2697. while (mod != NULL)
  2698. {
  2699. if (mod->chunk == chunk)
  2700. {
  2701. if (mod->modify_fn == NULL)
  2702. {
  2703. /* Remove this chunk */
  2704. pm->buffer_count = pm->buffer_position = 0;
  2705. mod->removed = 1;
  2706. break; /* Terminate the while loop */
  2707. }
  2708. else if ((*mod->modify_fn)(pm, mod, 0))
  2709. {
  2710. mod->modified = 1;
  2711. /* The chunk may have been removed: */
  2712. if (pm->buffer_count == 0)
  2713. {
  2714. pm->buffer_position = 0;
  2715. break;
  2716. }
  2717. modifier_setbuffer(pm);
  2718. }
  2719. }
  2720. mod = mod->next;
  2721. }
  2722. }
  2723. else
  2724. pm->flush = len+12 - pm->buffer_count; /* data + crc */
  2725. /* Take the data from the buffer (if there is any). */
  2726. break;
  2727. }
  2728. /* Here to read from the modifier buffer (not directly from
  2729. * the store, as in the flush case above.)
  2730. */
  2731. cb = pm->buffer_count - pm->buffer_position;
  2732. if (cb > st)
  2733. cb = st;
  2734. memcpy(pb, pm->buffer + pm->buffer_position, cb);
  2735. st -= cb;
  2736. pb += cb;
  2737. pm->buffer_position += cb;
  2738. }
  2739. }
  2740. /* The callback: */
  2741. static void PNGCBAPI
  2742. modifier_read(png_structp ppIn, png_bytep pb, size_t st)
  2743. {
  2744. png_const_structp pp = ppIn;
  2745. png_modifier *pm = voidcast(png_modifier*, png_get_io_ptr(pp));
  2746. if (pm == NULL || pm->this.pread != pp)
  2747. png_error(pp, "bad modifier_read call");
  2748. modifier_read_imp(pm, pb, st);
  2749. }
  2750. /* Like store_progressive_read but the data is getting changed as we go so we
  2751. * need a local buffer.
  2752. */
  2753. static void
  2754. modifier_progressive_read(png_modifier *pm, png_structp pp, png_infop pi)
  2755. {
  2756. if (pm->this.pread != pp || pm->this.current == NULL ||
  2757. pm->this.next == NULL)
  2758. png_error(pp, "store state damaged (progressive)");
  2759. /* This is another Horowitz and Hill random noise generator. In this case
  2760. * the aim is to stress the progressive reader with truly horrible variable
  2761. * buffer sizes in the range 1..500, so a sequence of 9 bit random numbers
  2762. * is generated. We could probably just count from 1 to 32767 and get as
  2763. * good a result.
  2764. */
  2765. for (;;)
  2766. {
  2767. static png_uint_32 noise = 1;
  2768. size_t cb, cbAvail;
  2769. png_byte buffer[512];
  2770. /* Generate 15 more bits of stuff: */
  2771. noise = (noise << 9) | ((noise ^ (noise >> (9-5))) & 0x1ff);
  2772. cb = noise & 0x1ff;
  2773. /* Check that this number of bytes are available (in the current buffer.)
  2774. * (This doesn't quite work - the modifier might delete a chunk; unlikely
  2775. * but possible, it doesn't happen at present because the modifier only
  2776. * adds chunks to standard images.)
  2777. */
  2778. cbAvail = store_read_buffer_avail(&pm->this);
  2779. if (pm->buffer_count > pm->buffer_position)
  2780. cbAvail += pm->buffer_count - pm->buffer_position;
  2781. if (cb > cbAvail)
  2782. {
  2783. /* Check for EOF: */
  2784. if (cbAvail == 0)
  2785. break;
  2786. cb = cbAvail;
  2787. }
  2788. modifier_read_imp(pm, buffer, cb);
  2789. png_process_data(pp, pi, buffer, cb);
  2790. }
  2791. /* Check the invariants at the end (if this fails it's a problem in this
  2792. * file!)
  2793. */
  2794. if (pm->buffer_count > pm->buffer_position ||
  2795. pm->this.next != &pm->this.current->data ||
  2796. pm->this.readpos < pm->this.current->datacount)
  2797. png_error(pp, "progressive read implementation error");
  2798. }
  2799. /* Set up a modifier. */
  2800. static png_structp
  2801. set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id,
  2802. const char *name)
  2803. {
  2804. /* Do this first so that the modifier fields are cleared even if an error
  2805. * happens allocating the png_struct. No allocation is done here so no
  2806. * cleanup is required.
  2807. */
  2808. pm->state = modifier_start;
  2809. pm->bit_depth = 0;
  2810. pm->colour_type = 255;
  2811. pm->pending_len = 0;
  2812. pm->pending_chunk = 0;
  2813. pm->flush = 0;
  2814. pm->buffer_count = 0;
  2815. pm->buffer_position = 0;
  2816. return set_store_for_read(&pm->this, ppi, id, name);
  2817. }
  2818. /******************************** MODIFICATIONS *******************************/
  2819. /* Standard modifications to add chunks. These do not require the _SUPPORTED
  2820. * macros because the chunks can be there regardless of whether this specific
  2821. * libpng supports them.
  2822. */
  2823. typedef struct gama_modification
  2824. {
  2825. png_modification this;
  2826. png_fixed_point gamma;
  2827. } gama_modification;
  2828. static int
  2829. gama_modify(png_modifier *pm, png_modification *me, int add)
  2830. {
  2831. UNUSED(add)
  2832. /* This simply dumps the given gamma value into the buffer. */
  2833. png_save_uint_32(pm->buffer, 4);
  2834. png_save_uint_32(pm->buffer+4, CHUNK_gAMA);
  2835. png_save_uint_32(pm->buffer+8, ((gama_modification*)me)->gamma);
  2836. return 1;
  2837. }
  2838. static void
  2839. gama_modification_init(gama_modification *me, png_modifier *pm, double gammad)
  2840. {
  2841. double g;
  2842. modification_init(&me->this);
  2843. me->this.chunk = CHUNK_gAMA;
  2844. me->this.modify_fn = gama_modify;
  2845. me->this.add = CHUNK_PLTE;
  2846. g = fix(gammad);
  2847. me->gamma = (png_fixed_point)g;
  2848. me->this.next = pm->modifications;
  2849. pm->modifications = &me->this;
  2850. }
  2851. typedef struct chrm_modification
  2852. {
  2853. png_modification this;
  2854. const color_encoding *encoding;
  2855. png_fixed_point wx, wy, rx, ry, gx, gy, bx, by;
  2856. } chrm_modification;
  2857. static int
  2858. chrm_modify(png_modifier *pm, png_modification *me, int add)
  2859. {
  2860. UNUSED(add)
  2861. /* As with gAMA this just adds the required cHRM chunk to the buffer. */
  2862. png_save_uint_32(pm->buffer , 32);
  2863. png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
  2864. png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
  2865. png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
  2866. png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
  2867. png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
  2868. png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
  2869. png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
  2870. png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
  2871. png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
  2872. return 1;
  2873. }
  2874. static void
  2875. chrm_modification_init(chrm_modification *me, png_modifier *pm,
  2876. const color_encoding *encoding)
  2877. {
  2878. CIE_color white = white_point(encoding);
  2879. /* Original end points: */
  2880. me->encoding = encoding;
  2881. /* Chromaticities (in fixed point): */
  2882. me->wx = fix(chromaticity_x(white));
  2883. me->wy = fix(chromaticity_y(white));
  2884. me->rx = fix(chromaticity_x(encoding->red));
  2885. me->ry = fix(chromaticity_y(encoding->red));
  2886. me->gx = fix(chromaticity_x(encoding->green));
  2887. me->gy = fix(chromaticity_y(encoding->green));
  2888. me->bx = fix(chromaticity_x(encoding->blue));
  2889. me->by = fix(chromaticity_y(encoding->blue));
  2890. modification_init(&me->this);
  2891. me->this.chunk = CHUNK_cHRM;
  2892. me->this.modify_fn = chrm_modify;
  2893. me->this.add = CHUNK_PLTE;
  2894. me->this.next = pm->modifications;
  2895. pm->modifications = &me->this;
  2896. }
  2897. typedef struct srgb_modification
  2898. {
  2899. png_modification this;
  2900. png_byte intent;
  2901. } srgb_modification;
  2902. static int
  2903. srgb_modify(png_modifier *pm, png_modification *me, int add)
  2904. {
  2905. UNUSED(add)
  2906. /* As above, ignore add and just make a new chunk */
  2907. png_save_uint_32(pm->buffer, 1);
  2908. png_save_uint_32(pm->buffer+4, CHUNK_sRGB);
  2909. pm->buffer[8] = ((srgb_modification*)me)->intent;
  2910. return 1;
  2911. }
  2912. static void
  2913. srgb_modification_init(srgb_modification *me, png_modifier *pm, png_byte intent)
  2914. {
  2915. modification_init(&me->this);
  2916. me->this.chunk = CHUNK_sBIT;
  2917. if (intent <= 3) /* if valid, else *delete* sRGB chunks */
  2918. {
  2919. me->this.modify_fn = srgb_modify;
  2920. me->this.add = CHUNK_PLTE;
  2921. me->intent = intent;
  2922. }
  2923. else
  2924. {
  2925. me->this.modify_fn = 0;
  2926. me->this.add = 0;
  2927. me->intent = 0;
  2928. }
  2929. me->this.next = pm->modifications;
  2930. pm->modifications = &me->this;
  2931. }
  2932. #ifdef PNG_READ_GAMMA_SUPPORTED
  2933. typedef struct sbit_modification
  2934. {
  2935. png_modification this;
  2936. png_byte sbit;
  2937. } sbit_modification;
  2938. static int
  2939. sbit_modify(png_modifier *pm, png_modification *me, int add)
  2940. {
  2941. png_byte sbit = ((sbit_modification*)me)->sbit;
  2942. if (pm->bit_depth > sbit)
  2943. {
  2944. int cb = 0;
  2945. switch (pm->colour_type)
  2946. {
  2947. case 0:
  2948. cb = 1;
  2949. break;
  2950. case 2:
  2951. case 3:
  2952. cb = 3;
  2953. break;
  2954. case 4:
  2955. cb = 2;
  2956. break;
  2957. case 6:
  2958. cb = 4;
  2959. break;
  2960. default:
  2961. png_error(pm->this.pread,
  2962. "unexpected colour type in sBIT modification");
  2963. }
  2964. png_save_uint_32(pm->buffer, cb);
  2965. png_save_uint_32(pm->buffer+4, CHUNK_sBIT);
  2966. while (cb > 0)
  2967. (pm->buffer+8)[--cb] = sbit;
  2968. return 1;
  2969. }
  2970. else if (!add)
  2971. {
  2972. /* Remove the sBIT chunk */
  2973. pm->buffer_count = pm->buffer_position = 0;
  2974. return 1;
  2975. }
  2976. else
  2977. return 0; /* do nothing */
  2978. }
  2979. static void
  2980. sbit_modification_init(sbit_modification *me, png_modifier *pm, png_byte sbit)
  2981. {
  2982. modification_init(&me->this);
  2983. me->this.chunk = CHUNK_sBIT;
  2984. me->this.modify_fn = sbit_modify;
  2985. me->this.add = CHUNK_PLTE;
  2986. me->sbit = sbit;
  2987. me->this.next = pm->modifications;
  2988. pm->modifications = &me->this;
  2989. }
  2990. #endif /* PNG_READ_GAMMA_SUPPORTED */
  2991. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  2992. /***************************** STANDARD PNG FILES *****************************/
  2993. /* Standard files - write and save standard files. */
  2994. /* There are two basic forms of standard images. Those which attempt to have
  2995. * all the possible pixel values (not possible for 16bpp images, but a range of
  2996. * values are produced) and those which have a range of image sizes. The former
  2997. * are used for testing transforms, in particular gamma correction and bit
  2998. * reduction and increase. The latter are reserved for testing the behavior of
  2999. * libpng with respect to 'odd' image sizes - particularly small images where
  3000. * rows become 1 byte and interlace passes disappear.
  3001. *
  3002. * The first, most useful, set are the 'transform' images, the second set of
  3003. * small images are the 'size' images.
  3004. *
  3005. * The transform files are constructed with rows which fit into a 1024 byte row
  3006. * buffer. This makes allocation easier below. Further regardless of the file
  3007. * format every row has 128 pixels (giving 1024 bytes for 64bpp formats).
  3008. *
  3009. * Files are stored with no gAMA or sBIT chunks, with a PLTE only when needed
  3010. * and with an ID derived from the colour type, bit depth and interlace type
  3011. * as above (FILEID). The width (128) and height (variable) are not stored in
  3012. * the FILEID - instead the fields are set to 0, indicating a transform file.
  3013. *
  3014. * The size files ar constructed with rows a maximum of 128 bytes wide, allowing
  3015. * a maximum width of 16 pixels (for the 64bpp case.) They also have a maximum
  3016. * height of 16 rows. The width and height are stored in the FILEID and, being
  3017. * non-zero, indicate a size file.
  3018. *
  3019. * Because the PNG filter code is typically the largest CPU consumer within
  3020. * libpng itself there is a tendency to attempt to optimize it. This results in
  3021. * special case code which needs to be validated. To cause this to happen the
  3022. * 'size' images are made to use each possible filter, in so far as this is
  3023. * possible for smaller images.
  3024. *
  3025. * For palette image (colour type 3) multiple transform images are stored with
  3026. * the same bit depth to allow testing of more colour combinations -
  3027. * particularly important for testing the gamma code because libpng uses a
  3028. * different code path for palette images. For size images a single palette is
  3029. * used.
  3030. */
  3031. /* Make a 'standard' palette. Because there are only 256 entries in a palette
  3032. * (maximum) this actually makes a random palette in the hope that enough tests
  3033. * will catch enough errors. (Note that the same palette isn't produced every
  3034. * time for the same test - it depends on what previous tests have been run -
  3035. * but a given set of arguments to pngvalid will always produce the same palette
  3036. * at the same test! This is why pseudo-random number generators are useful for
  3037. * testing.)
  3038. *
  3039. * The store must be open for write when this is called, otherwise an internal
  3040. * error will occur. This routine contains its own magic number seed, so the
  3041. * palettes generated don't change if there are intervening errors (changing the
  3042. * calls to the store_mark seed.)
  3043. */
  3044. static store_palette_entry *
  3045. make_standard_palette(png_store* ps, int npalette, int do_tRNS)
  3046. {
  3047. static png_uint_32 palette_seed[2] = { 0x87654321, 9 };
  3048. int i = 0;
  3049. png_byte values[256][4];
  3050. /* Always put in black and white plus the six primary and secondary colors.
  3051. */
  3052. for (; i<8; ++i)
  3053. {
  3054. values[i][1] = (png_byte)((i&1) ? 255U : 0U);
  3055. values[i][2] = (png_byte)((i&2) ? 255U : 0U);
  3056. values[i][3] = (png_byte)((i&4) ? 255U : 0U);
  3057. }
  3058. /* Then add 62 grays (one quarter of the remaining 256 slots). */
  3059. {
  3060. int j = 0;
  3061. png_byte random_bytes[4];
  3062. png_byte need[256];
  3063. need[0] = 0; /*got black*/
  3064. memset(need+1, 1, (sizeof need)-2); /*need these*/
  3065. need[255] = 0; /*but not white*/
  3066. while (i<70)
  3067. {
  3068. png_byte b;
  3069. if (j==0)
  3070. {
  3071. make_four_random_bytes(palette_seed, random_bytes);
  3072. j = 4;
  3073. }
  3074. b = random_bytes[--j];
  3075. if (need[b])
  3076. {
  3077. values[i][1] = b;
  3078. values[i][2] = b;
  3079. values[i++][3] = b;
  3080. }
  3081. }
  3082. }
  3083. /* Finally add 192 colors at random - don't worry about matches to things we
  3084. * already have, chance is less than 1/65536. Don't worry about grays,
  3085. * chance is the same, so we get a duplicate or extra gray less than 1 time
  3086. * in 170.
  3087. */
  3088. for (; i<256; ++i)
  3089. make_four_random_bytes(palette_seed, values[i]);
  3090. /* Fill in the alpha values in the first byte. Just use all possible values
  3091. * (0..255) in an apparently random order:
  3092. */
  3093. {
  3094. store_palette_entry *palette;
  3095. png_byte selector[4];
  3096. make_four_random_bytes(palette_seed, selector);
  3097. if (do_tRNS)
  3098. for (i=0; i<256; ++i)
  3099. values[i][0] = (png_byte)(i ^ selector[0]);
  3100. else
  3101. for (i=0; i<256; ++i)
  3102. values[i][0] = 255; /* no transparency/tRNS chunk */
  3103. /* 'values' contains 256 ARGB values, but we only need 'npalette'.
  3104. * 'npalette' will always be a power of 2: 2, 4, 16 or 256. In the low
  3105. * bit depth cases select colors at random, else it is difficult to have
  3106. * a set of low bit depth palette test with any chance of a reasonable
  3107. * range of colors. Do this by randomly permuting values into the low
  3108. * 'npalette' entries using an XOR mask generated here. This also
  3109. * permutes the npalette == 256 case in a potentially useful way (there is
  3110. * no relationship between palette index and the color value therein!)
  3111. */
  3112. palette = store_write_palette(ps, npalette);
  3113. for (i=0; i<npalette; ++i)
  3114. {
  3115. palette[i].alpha = values[i ^ selector[1]][0];
  3116. palette[i].red = values[i ^ selector[1]][1];
  3117. palette[i].green = values[i ^ selector[1]][2];
  3118. palette[i].blue = values[i ^ selector[1]][3];
  3119. }
  3120. return palette;
  3121. }
  3122. }
  3123. /* Initialize a standard palette on a write stream. The 'do_tRNS' argument
  3124. * indicates whether or not to also set the tRNS chunk.
  3125. */
  3126. /* TODO: the png_structp here can probably be 'const' in the future */
  3127. static void
  3128. init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette,
  3129. int do_tRNS)
  3130. {
  3131. store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS);
  3132. {
  3133. int i;
  3134. png_color palette[256];
  3135. /* Set all entries to detect overread errors. */
  3136. for (i=0; i<npalette; ++i)
  3137. {
  3138. palette[i].red = ppal[i].red;
  3139. palette[i].green = ppal[i].green;
  3140. palette[i].blue = ppal[i].blue;
  3141. }
  3142. /* Just in case fill in the rest with detectable values: */
  3143. for (; i<256; ++i)
  3144. palette[i].red = palette[i].green = palette[i].blue = 42;
  3145. png_set_PLTE(pp, pi, palette, npalette);
  3146. }
  3147. if (do_tRNS)
  3148. {
  3149. int i, j;
  3150. png_byte tRNS[256];
  3151. /* Set all the entries, but skip trailing opaque entries */
  3152. for (i=j=0; i<npalette; ++i)
  3153. if ((tRNS[i] = ppal[i].alpha) < 255)
  3154. j = i+1;
  3155. /* Fill in the remainder with a detectable value: */
  3156. for (; i<256; ++i)
  3157. tRNS[i] = 24;
  3158. #ifdef PNG_WRITE_tRNS_SUPPORTED
  3159. if (j > 0)
  3160. png_set_tRNS(pp, pi, tRNS, j, 0/*color*/);
  3161. #endif
  3162. }
  3163. }
  3164. #ifdef PNG_WRITE_tRNS_SUPPORTED
  3165. static void
  3166. set_random_tRNS(png_structp pp, png_infop pi, png_byte colour_type,
  3167. int bit_depth)
  3168. {
  3169. /* To make this useful the tRNS color needs to match at least one pixel.
  3170. * Random values are fine for gray, including the 16-bit case where we know
  3171. * that the test image contains all the gray values. For RGB we need more
  3172. * method as only 65536 different RGB values are generated.
  3173. */
  3174. png_color_16 tRNS;
  3175. png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1);
  3176. R8(tRNS); /* makes unset fields random */
  3177. if (colour_type & 2/*RGB*/)
  3178. {
  3179. if (bit_depth == 8)
  3180. {
  3181. tRNS.red = random_u16();
  3182. tRNS.green = random_u16();
  3183. tRNS.blue = tRNS.red ^ tRNS.green;
  3184. tRNS.red &= mask;
  3185. tRNS.green &= mask;
  3186. tRNS.blue &= mask;
  3187. }
  3188. else /* bit_depth == 16 */
  3189. {
  3190. tRNS.red = random_u16();
  3191. tRNS.green = (png_uint_16)(tRNS.red * 257);
  3192. tRNS.blue = (png_uint_16)(tRNS.green * 17);
  3193. }
  3194. }
  3195. else
  3196. {
  3197. tRNS.gray = random_u16();
  3198. tRNS.gray &= mask;
  3199. }
  3200. png_set_tRNS(pp, pi, NULL, 0, &tRNS);
  3201. }
  3202. #endif
  3203. /* The number of passes is related to the interlace type. There was no libpng
  3204. * API to determine this prior to 1.5, so we need an inquiry function:
  3205. */
  3206. static int
  3207. npasses_from_interlace_type(png_const_structp pp, int interlace_type)
  3208. {
  3209. switch (interlace_type)
  3210. {
  3211. default:
  3212. png_error(pp, "invalid interlace type");
  3213. case PNG_INTERLACE_NONE:
  3214. return 1;
  3215. case PNG_INTERLACE_ADAM7:
  3216. return PNG_INTERLACE_ADAM7_PASSES;
  3217. }
  3218. }
  3219. static unsigned int
  3220. bit_size(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  3221. {
  3222. switch (colour_type)
  3223. {
  3224. default: png_error(pp, "invalid color type");
  3225. case 0: return bit_depth;
  3226. case 2: return 3*bit_depth;
  3227. case 3: return bit_depth;
  3228. case 4: return 2*bit_depth;
  3229. case 6: return 4*bit_depth;
  3230. }
  3231. }
  3232. #define TRANSFORM_WIDTH 128U
  3233. #define TRANSFORM_ROWMAX (TRANSFORM_WIDTH*8U)
  3234. #define SIZE_ROWMAX (16*8U) /* 16 pixels, max 8 bytes each - 128 bytes */
  3235. #define STANDARD_ROWMAX TRANSFORM_ROWMAX /* The larger of the two */
  3236. #define SIZE_HEIGHTMAX 16 /* Maximum range of size images */
  3237. static size_t
  3238. transform_rowsize(png_const_structp pp, png_byte colour_type,
  3239. png_byte bit_depth)
  3240. {
  3241. return (TRANSFORM_WIDTH * bit_size(pp, colour_type, bit_depth)) / 8;
  3242. }
  3243. /* transform_width(pp, colour_type, bit_depth) current returns the same number
  3244. * every time, so just use a macro:
  3245. */
  3246. #define transform_width(pp, colour_type, bit_depth) TRANSFORM_WIDTH
  3247. static png_uint_32
  3248. transform_height(png_const_structp pp, png_byte colour_type, png_byte bit_depth)
  3249. {
  3250. switch (bit_size(pp, colour_type, bit_depth))
  3251. {
  3252. case 1:
  3253. case 2:
  3254. case 4:
  3255. return 1; /* Total of 128 pixels */
  3256. case 8:
  3257. return 2; /* Total of 256 pixels/bytes */
  3258. case 16:
  3259. return 512; /* Total of 65536 pixels */
  3260. case 24:
  3261. case 32:
  3262. return 512; /* 65536 pixels */
  3263. case 48:
  3264. case 64:
  3265. return 2048;/* 4 x 65536 pixels. */
  3266. # define TRANSFORM_HEIGHTMAX 2048
  3267. default:
  3268. return 0; /* Error, will be caught later */
  3269. }
  3270. }
  3271. #ifdef PNG_READ_SUPPORTED
  3272. /* The following can only be defined here, now we have the definitions
  3273. * of the transform image sizes.
  3274. */
  3275. static png_uint_32
  3276. standard_width(png_const_structp pp, png_uint_32 id)
  3277. {
  3278. png_uint_32 width = WIDTH_FROM_ID(id);
  3279. UNUSED(pp)
  3280. if (width == 0)
  3281. width = transform_width(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  3282. return width;
  3283. }
  3284. static png_uint_32
  3285. standard_height(png_const_structp pp, png_uint_32 id)
  3286. {
  3287. png_uint_32 height = HEIGHT_FROM_ID(id);
  3288. if (height == 0)
  3289. height = transform_height(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  3290. return height;
  3291. }
  3292. static png_uint_32
  3293. standard_rowsize(png_const_structp pp, png_uint_32 id)
  3294. {
  3295. png_uint_32 width = standard_width(pp, id);
  3296. /* This won't overflow: */
  3297. width *= bit_size(pp, COL_FROM_ID(id), DEPTH_FROM_ID(id));
  3298. return (width + 7) / 8;
  3299. }
  3300. #endif /* PNG_READ_SUPPORTED */
  3301. static void
  3302. transform_row(png_const_structp pp, png_byte buffer[TRANSFORM_ROWMAX],
  3303. png_byte colour_type, png_byte bit_depth, png_uint_32 y)
  3304. {
  3305. png_uint_32 v = y << 7;
  3306. png_uint_32 i = 0;
  3307. switch (bit_size(pp, colour_type, bit_depth))
  3308. {
  3309. case 1:
  3310. while (i<128/8) buffer[i] = (png_byte)(v & 0xff), v += 17, ++i;
  3311. return;
  3312. case 2:
  3313. while (i<128/4) buffer[i] = (png_byte)(v & 0xff), v += 33, ++i;
  3314. return;
  3315. case 4:
  3316. while (i<128/2) buffer[i] = (png_byte)(v & 0xff), v += 65, ++i;
  3317. return;
  3318. case 8:
  3319. /* 256 bytes total, 128 bytes in each row set as follows: */
  3320. while (i<128) buffer[i] = (png_byte)(v & 0xff), ++v, ++i;
  3321. return;
  3322. case 16:
  3323. /* Generate all 65536 pixel values in order, which includes the 8 bit
  3324. * GA case as well as the 16 bit G case.
  3325. */
  3326. while (i<128)
  3327. {
  3328. buffer[2*i] = (png_byte)((v>>8) & 0xff);
  3329. buffer[2*i+1] = (png_byte)(v & 0xff);
  3330. ++v;
  3331. ++i;
  3332. }
  3333. return;
  3334. case 24:
  3335. /* 65535 pixels, but rotate the values. */
  3336. while (i<128)
  3337. {
  3338. /* Three bytes per pixel, r, g, b, make b by r^g */
  3339. buffer[3*i+0] = (png_byte)((v >> 8) & 0xff);
  3340. buffer[3*i+1] = (png_byte)(v & 0xff);
  3341. buffer[3*i+2] = (png_byte)(((v >> 8) ^ v) & 0xff);
  3342. ++v;
  3343. ++i;
  3344. }
  3345. return;
  3346. case 32:
  3347. /* 65535 pixels, r, g, b, a; just replicate */
  3348. while (i<128)
  3349. {
  3350. buffer[4*i+0] = (png_byte)((v >> 8) & 0xff);
  3351. buffer[4*i+1] = (png_byte)(v & 0xff);
  3352. buffer[4*i+2] = (png_byte)((v >> 8) & 0xff);
  3353. buffer[4*i+3] = (png_byte)(v & 0xff);
  3354. ++v;
  3355. ++i;
  3356. }
  3357. return;
  3358. case 48:
  3359. /* y is maximum 2047, giving 4x65536 pixels, make 'r' increase by 1 at
  3360. * each pixel, g increase by 257 (0x101) and 'b' by 0x1111:
  3361. */
  3362. while (i<128)
  3363. {
  3364. png_uint_32 t = v++;
  3365. buffer[6*i+0] = (png_byte)((t >> 8) & 0xff);
  3366. buffer[6*i+1] = (png_byte)(t & 0xff);
  3367. t *= 257;
  3368. buffer[6*i+2] = (png_byte)((t >> 8) & 0xff);
  3369. buffer[6*i+3] = (png_byte)(t & 0xff);
  3370. t *= 17;
  3371. buffer[6*i+4] = (png_byte)((t >> 8) & 0xff);
  3372. buffer[6*i+5] = (png_byte)(t & 0xff);
  3373. ++i;
  3374. }
  3375. return;
  3376. case 64:
  3377. /* As above in the 32 bit case. */
  3378. while (i<128)
  3379. {
  3380. png_uint_32 t = v++;
  3381. buffer[8*i+0] = (png_byte)((t >> 8) & 0xff);
  3382. buffer[8*i+1] = (png_byte)(t & 0xff);
  3383. buffer[8*i+4] = (png_byte)((t >> 8) & 0xff);
  3384. buffer[8*i+5] = (png_byte)(t & 0xff);
  3385. t *= 257;
  3386. buffer[8*i+2] = (png_byte)((t >> 8) & 0xff);
  3387. buffer[8*i+3] = (png_byte)(t & 0xff);
  3388. buffer[8*i+6] = (png_byte)((t >> 8) & 0xff);
  3389. buffer[8*i+7] = (png_byte)(t & 0xff);
  3390. ++i;
  3391. }
  3392. return;
  3393. default:
  3394. break;
  3395. }
  3396. png_error(pp, "internal error");
  3397. }
  3398. /* This is just to do the right cast - could be changed to a function to check
  3399. * 'bd' but there isn't much point.
  3400. */
  3401. #define DEPTH(bd) ((png_byte)(1U << (bd)))
  3402. /* This is just a helper for compiling on minimal systems with no write
  3403. * interlacing support. If there is no write interlacing we can't generate test
  3404. * cases with interlace:
  3405. */
  3406. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  3407. # define INTERLACE_LAST PNG_INTERLACE_LAST
  3408. # define check_interlace_type(type) ((void)(type))
  3409. # define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp)
  3410. # define do_own_interlace 0
  3411. #elif PNG_LIBPNG_VER < 10700
  3412. # define set_write_interlace_handling(pp,type) (1)
  3413. static void
  3414. check_interlace_type(int const interlace_type)
  3415. {
  3416. /* Prior to 1.7.0 libpng does not support the write of an interlaced image
  3417. * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the
  3418. * code here does the pixel interlace itself, so:
  3419. */
  3420. if (interlace_type != PNG_INTERLACE_NONE)
  3421. {
  3422. /* This is an internal error - --interlace tests should be skipped, not
  3423. * attempted.
  3424. */
  3425. fprintf(stderr, "pngvalid: no interlace support\n");
  3426. exit(99);
  3427. }
  3428. }
  3429. # define INTERLACE_LAST (PNG_INTERLACE_NONE+1)
  3430. # define do_own_interlace 0
  3431. #else /* libpng 1.7+ */
  3432. # define set_write_interlace_handling(pp,type)\
  3433. npasses_from_interlace_type(pp,type)
  3434. # define check_interlace_type(type) ((void)(type))
  3435. # define INTERLACE_LAST PNG_INTERLACE_LAST
  3436. # define do_own_interlace 1
  3437. #endif /* WRITE_INTERLACING tests */
  3438. #if PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED
  3439. # define CAN_WRITE_INTERLACE 1
  3440. #else
  3441. # define CAN_WRITE_INTERLACE 0
  3442. #endif
  3443. /* Do the same thing for read interlacing; this controls whether read tests do
  3444. * their own de-interlace or use libpng.
  3445. */
  3446. #ifdef PNG_READ_INTERLACING_SUPPORTED
  3447. # define do_read_interlace 0
  3448. #else /* no libpng read interlace support */
  3449. # define do_read_interlace 1
  3450. #endif
  3451. /* The following two routines use the PNG interlace support macros from
  3452. * png.h to interlace or deinterlace rows.
  3453. */
  3454. static void
  3455. interlace_row(png_bytep buffer, png_const_bytep imageRow,
  3456. unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
  3457. {
  3458. png_uint_32 xin, xout, xstep;
  3459. /* Note that this can, trivially, be optimized to a memcpy on pass 7, the
  3460. * code is presented this way to make it easier to understand. In practice
  3461. * consult the code in the libpng source to see other ways of doing this.
  3462. *
  3463. * It is OK for buffer and imageRow to be identical, because 'xin' moves
  3464. * faster than 'xout' and we copy up.
  3465. */
  3466. xin = PNG_PASS_START_COL(pass);
  3467. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3468. for (xout=0; xin<w; xin+=xstep)
  3469. {
  3470. pixel_copy(buffer, xout, imageRow, xin, pixel_size, littleendian);
  3471. ++xout;
  3472. }
  3473. }
  3474. #ifdef PNG_READ_SUPPORTED
  3475. static void
  3476. deinterlace_row(png_bytep buffer, png_const_bytep row,
  3477. unsigned int pixel_size, png_uint_32 w, int pass, int littleendian)
  3478. {
  3479. /* The inverse of the above, 'row' is part of row 'y' of the output image,
  3480. * in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
  3481. * the pixels of row into buffer and return the number written (to allow
  3482. * this to be checked).
  3483. */
  3484. png_uint_32 xin, xout, xstep;
  3485. xout = PNG_PASS_START_COL(pass);
  3486. xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
  3487. for (xin=0; xout<w; xout+=xstep)
  3488. {
  3489. pixel_copy(buffer, xout, row, xin, pixel_size, littleendian);
  3490. ++xin;
  3491. }
  3492. }
  3493. #endif /* PNG_READ_SUPPORTED */
  3494. /* Make a standardized image given an image colour type, bit depth and
  3495. * interlace type. The standard images have a very restricted range of
  3496. * rows and heights and are used for testing transforms rather than image
  3497. * layout details. See make_size_images below for a way to make images
  3498. * that test odd sizes along with the libpng interlace handling.
  3499. */
  3500. #ifdef PNG_WRITE_FILTER_SUPPORTED
  3501. static void
  3502. choose_random_filter(png_structp pp, int start)
  3503. {
  3504. /* Choose filters randomly except that on the very first row ensure that
  3505. * there is at least one previous row filter.
  3506. */
  3507. int filters = PNG_ALL_FILTERS & random_mod(256U);
  3508. /* There may be no filters; skip the setting. */
  3509. if (filters != 0)
  3510. {
  3511. if (start && filters < PNG_FILTER_UP)
  3512. filters |= PNG_FILTER_UP;
  3513. png_set_filter(pp, 0/*method*/, filters);
  3514. }
  3515. }
  3516. #else /* !WRITE_FILTER */
  3517. # define choose_random_filter(pp, start) ((void)0)
  3518. #endif /* !WRITE_FILTER */
  3519. static void
  3520. make_transform_image(png_store* const ps, png_byte const colour_type,
  3521. png_byte const bit_depth, unsigned int palette_number,
  3522. int interlace_type, png_const_charp name)
  3523. {
  3524. context(ps, fault);
  3525. check_interlace_type(interlace_type);
  3526. Try
  3527. {
  3528. png_infop pi;
  3529. png_structp pp = set_store_for_write(ps, &pi, name);
  3530. png_uint_32 h, w;
  3531. /* In the event of a problem return control to the Catch statement below
  3532. * to do the clean up - it is not possible to 'return' directly from a Try
  3533. * block.
  3534. */
  3535. if (pp == NULL)
  3536. Throw ps;
  3537. w = transform_width(pp, colour_type, bit_depth);
  3538. h = transform_height(pp, colour_type, bit_depth);
  3539. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3540. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3541. #ifdef PNG_TEXT_SUPPORTED
  3542. # if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
  3543. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
  3544. # else
  3545. # define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
  3546. # endif
  3547. {
  3548. static char key[] = "image name"; /* must be writeable */
  3549. size_t pos;
  3550. png_text text;
  3551. char copy[FILE_NAME_SIZE];
  3552. /* Use a compressed text string to test the correct interaction of text
  3553. * compression and IDAT compression.
  3554. */
  3555. text.compression = TEXT_COMPRESSION;
  3556. text.key = key;
  3557. /* Yuck: the text must be writable! */
  3558. pos = safecat(copy, sizeof copy, 0, ps->wname);
  3559. text.text = copy;
  3560. text.text_length = pos;
  3561. text.itxt_length = 0;
  3562. text.lang = 0;
  3563. text.lang_key = 0;
  3564. png_set_text(pp, pi, &text, 1);
  3565. }
  3566. #endif
  3567. if (colour_type == 3) /* palette */
  3568. init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
  3569. # ifdef PNG_WRITE_tRNS_SUPPORTED
  3570. else if (palette_number)
  3571. set_random_tRNS(pp, pi, colour_type, bit_depth);
  3572. # endif
  3573. png_write_info(pp, pi);
  3574. if (png_get_rowbytes(pp, pi) !=
  3575. transform_rowsize(pp, colour_type, bit_depth))
  3576. png_error(pp, "transform row size incorrect");
  3577. else
  3578. {
  3579. /* Somewhat confusingly this must be called *after* png_write_info
  3580. * because if it is called before, the information in *pp has not been
  3581. * updated to reflect the interlaced image.
  3582. */
  3583. int npasses = set_write_interlace_handling(pp, interlace_type);
  3584. int pass;
  3585. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  3586. png_error(pp, "write: png_set_interlace_handling failed");
  3587. for (pass=0; pass<npasses; ++pass)
  3588. {
  3589. png_uint_32 y;
  3590. /* do_own_interlace is a pre-defined boolean (a #define) which is
  3591. * set if we have to work out the interlaced rows here.
  3592. */
  3593. for (y=0; y<h; ++y)
  3594. {
  3595. png_byte buffer[TRANSFORM_ROWMAX];
  3596. transform_row(pp, buffer, colour_type, bit_depth, y);
  3597. # if do_own_interlace
  3598. /* If do_own_interlace *and* the image is interlaced we need a
  3599. * reduced interlace row; this may be reduced to empty.
  3600. */
  3601. if (interlace_type == PNG_INTERLACE_ADAM7)
  3602. {
  3603. /* The row must not be written if it doesn't exist, notice
  3604. * that there are two conditions here, either the row isn't
  3605. * ever in the pass or the row would be but isn't wide
  3606. * enough to contribute any pixels. In fact the wPass test
  3607. * can be used to skip the whole y loop in this case.
  3608. */
  3609. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  3610. PNG_PASS_COLS(w, pass) > 0)
  3611. interlace_row(buffer, buffer,
  3612. bit_size(pp, colour_type, bit_depth), w, pass,
  3613. 0/*data always bigendian*/);
  3614. else
  3615. continue;
  3616. }
  3617. # endif /* do_own_interlace */
  3618. choose_random_filter(pp, pass == 0 && y == 0);
  3619. png_write_row(pp, buffer);
  3620. }
  3621. }
  3622. }
  3623. #ifdef PNG_TEXT_SUPPORTED
  3624. {
  3625. static char key[] = "end marker";
  3626. static char comment[] = "end";
  3627. png_text text;
  3628. /* Use a compressed text string to test the correct interaction of text
  3629. * compression and IDAT compression.
  3630. */
  3631. text.compression = TEXT_COMPRESSION;
  3632. text.key = key;
  3633. text.text = comment;
  3634. text.text_length = (sizeof comment)-1;
  3635. text.itxt_length = 0;
  3636. text.lang = 0;
  3637. text.lang_key = 0;
  3638. png_set_text(pp, pi, &text, 1);
  3639. }
  3640. #endif
  3641. png_write_end(pp, pi);
  3642. /* And store this under the appropriate id, then clean up. */
  3643. store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
  3644. interlace_type, 0, 0, 0));
  3645. store_write_reset(ps);
  3646. }
  3647. Catch(fault)
  3648. {
  3649. /* Use the png_store returned by the exception. This may help the compiler
  3650. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3651. * and ps will always be the same value.
  3652. */
  3653. store_write_reset(fault);
  3654. }
  3655. }
  3656. static void
  3657. make_transform_images(png_modifier *pm)
  3658. {
  3659. png_byte colour_type = 0;
  3660. png_byte bit_depth = 0;
  3661. unsigned int palette_number = 0;
  3662. /* This is in case of errors. */
  3663. safecat(pm->this.test, sizeof pm->this.test, 0, "make standard images");
  3664. /* Use next_format to enumerate all the combinations we test, including
  3665. * generating multiple low bit depth palette images. Non-A images (palette
  3666. * and direct) are created with and without tRNS chunks.
  3667. */
  3668. while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1))
  3669. {
  3670. int interlace_type;
  3671. for (interlace_type = PNG_INTERLACE_NONE;
  3672. interlace_type < INTERLACE_LAST; ++interlace_type)
  3673. {
  3674. char name[FILE_NAME_SIZE];
  3675. standard_name(name, sizeof name, 0, colour_type, bit_depth,
  3676. palette_number, interlace_type, 0, 0, do_own_interlace);
  3677. make_transform_image(&pm->this, colour_type, bit_depth, palette_number,
  3678. interlace_type, name);
  3679. }
  3680. }
  3681. }
  3682. /* Build a single row for the 'size' test images; this fills in only the
  3683. * first bit_width bits of the sample row.
  3684. */
  3685. static void
  3686. size_row(png_byte buffer[SIZE_ROWMAX], png_uint_32 bit_width, png_uint_32 y)
  3687. {
  3688. /* height is in the range 1 to 16, so: */
  3689. y = ((y & 1) << 7) + ((y & 2) << 6) + ((y & 4) << 5) + ((y & 8) << 4);
  3690. /* the following ensures bits are set in small images: */
  3691. y ^= 0xA5;
  3692. while (bit_width >= 8)
  3693. *buffer++ = (png_byte)y++, bit_width -= 8;
  3694. /* There may be up to 7 remaining bits, these go in the most significant
  3695. * bits of the byte.
  3696. */
  3697. if (bit_width > 0)
  3698. {
  3699. png_uint_32 mask = (1U<<(8-bit_width))-1;
  3700. *buffer = (png_byte)((*buffer & mask) | (y & ~mask));
  3701. }
  3702. }
  3703. static void
  3704. make_size_image(png_store* const ps, png_byte const colour_type,
  3705. png_byte const bit_depth, int const interlace_type,
  3706. png_uint_32 const w, png_uint_32 const h,
  3707. int const do_interlace)
  3708. {
  3709. context(ps, fault);
  3710. check_interlace_type(interlace_type);
  3711. Try
  3712. {
  3713. png_infop pi;
  3714. png_structp pp;
  3715. unsigned int pixel_size;
  3716. /* Make a name and get an appropriate id for the store: */
  3717. char name[FILE_NAME_SIZE];
  3718. png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/,
  3719. interlace_type, w, h, do_interlace);
  3720. standard_name_from_id(name, sizeof name, 0, id);
  3721. pp = set_store_for_write(ps, &pi, name);
  3722. /* In the event of a problem return control to the Catch statement below
  3723. * to do the clean up - it is not possible to 'return' directly from a Try
  3724. * block.
  3725. */
  3726. if (pp == NULL)
  3727. Throw ps;
  3728. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3729. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3730. #ifdef PNG_TEXT_SUPPORTED
  3731. {
  3732. static char key[] = "image name"; /* must be writeable */
  3733. size_t pos;
  3734. png_text text;
  3735. char copy[FILE_NAME_SIZE];
  3736. /* Use a compressed text string to test the correct interaction of text
  3737. * compression and IDAT compression.
  3738. */
  3739. text.compression = TEXT_COMPRESSION;
  3740. text.key = key;
  3741. /* Yuck: the text must be writable! */
  3742. pos = safecat(copy, sizeof copy, 0, ps->wname);
  3743. text.text = copy;
  3744. text.text_length = pos;
  3745. text.itxt_length = 0;
  3746. text.lang = 0;
  3747. text.lang_key = 0;
  3748. png_set_text(pp, pi, &text, 1);
  3749. }
  3750. #endif
  3751. if (colour_type == 3) /* palette */
  3752. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  3753. png_write_info(pp, pi);
  3754. /* Calculate the bit size, divide by 8 to get the byte size - this won't
  3755. * overflow because we know the w values are all small enough even for
  3756. * a system where 'unsigned int' is only 16 bits.
  3757. */
  3758. pixel_size = bit_size(pp, colour_type, bit_depth);
  3759. if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8)
  3760. png_error(pp, "size row size incorrect");
  3761. else
  3762. {
  3763. int npasses = npasses_from_interlace_type(pp, interlace_type);
  3764. png_uint_32 y;
  3765. int pass;
  3766. png_byte image[16][SIZE_ROWMAX];
  3767. /* To help consistent error detection make the parts of this buffer
  3768. * that aren't set below all '1':
  3769. */
  3770. memset(image, 0xff, sizeof image);
  3771. if (!do_interlace &&
  3772. npasses != set_write_interlace_handling(pp, interlace_type))
  3773. png_error(pp, "write: png_set_interlace_handling failed");
  3774. /* Prepare the whole image first to avoid making it 7 times: */
  3775. for (y=0; y<h; ++y)
  3776. size_row(image[y], w * pixel_size, y);
  3777. for (pass=0; pass<npasses; ++pass)
  3778. {
  3779. /* The following two are for checking the macros: */
  3780. png_uint_32 wPass = PNG_PASS_COLS(w, pass);
  3781. /* If do_interlace is set we don't call png_write_row for every
  3782. * row because some of them are empty. In fact, for a 1x1 image,
  3783. * most of them are empty!
  3784. */
  3785. for (y=0; y<h; ++y)
  3786. {
  3787. png_const_bytep row = image[y];
  3788. png_byte tempRow[SIZE_ROWMAX];
  3789. /* If do_interlace *and* the image is interlaced we
  3790. * need a reduced interlace row; this may be reduced
  3791. * to empty.
  3792. */
  3793. if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7)
  3794. {
  3795. /* The row must not be written if it doesn't exist, notice
  3796. * that there are two conditions here, either the row isn't
  3797. * ever in the pass or the row would be but isn't wide
  3798. * enough to contribute any pixels. In fact the wPass test
  3799. * can be used to skip the whole y loop in this case.
  3800. */
  3801. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0)
  3802. {
  3803. /* Set to all 1's for error detection (libpng tends to
  3804. * set unset things to 0).
  3805. */
  3806. memset(tempRow, 0xff, sizeof tempRow);
  3807. interlace_row(tempRow, row, pixel_size, w, pass,
  3808. 0/*data always bigendian*/);
  3809. row = tempRow;
  3810. }
  3811. else
  3812. continue;
  3813. }
  3814. # ifdef PNG_WRITE_FILTER_SUPPORTED
  3815. /* Only get to here if the row has some pixels in it, set the
  3816. * filters to 'all' for the very first row and thereafter to a
  3817. * single filter. It isn't well documented, but png_set_filter
  3818. * does accept a filter number (per the spec) as well as a bit
  3819. * mask.
  3820. *
  3821. * The code now uses filters at random, except that on the first
  3822. * row of an image it ensures that a previous row filter is in
  3823. * the set so that libpng allocates the row buffer.
  3824. */
  3825. {
  3826. int filters = 8 << random_mod(PNG_FILTER_VALUE_LAST);
  3827. if (pass == 0 && y == 0 &&
  3828. (filters < PNG_FILTER_UP || w == 1U))
  3829. filters |= PNG_FILTER_UP;
  3830. png_set_filter(pp, 0/*method*/, filters);
  3831. }
  3832. # endif
  3833. png_write_row(pp, row);
  3834. }
  3835. }
  3836. }
  3837. #ifdef PNG_TEXT_SUPPORTED
  3838. {
  3839. static char key[] = "end marker";
  3840. static char comment[] = "end";
  3841. png_text text;
  3842. /* Use a compressed text string to test the correct interaction of text
  3843. * compression and IDAT compression.
  3844. */
  3845. text.compression = TEXT_COMPRESSION;
  3846. text.key = key;
  3847. text.text = comment;
  3848. text.text_length = (sizeof comment)-1;
  3849. text.itxt_length = 0;
  3850. text.lang = 0;
  3851. text.lang_key = 0;
  3852. png_set_text(pp, pi, &text, 1);
  3853. }
  3854. #endif
  3855. png_write_end(pp, pi);
  3856. /* And store this under the appropriate id, then clean up. */
  3857. store_storefile(ps, id);
  3858. store_write_reset(ps);
  3859. }
  3860. Catch(fault)
  3861. {
  3862. /* Use the png_store returned by the exception. This may help the compiler
  3863. * because 'ps' is not used in this branch of the setjmp. Note that fault
  3864. * and ps will always be the same value.
  3865. */
  3866. store_write_reset(fault);
  3867. }
  3868. }
  3869. static void
  3870. make_size(png_store* const ps, png_byte const colour_type, int bdlo,
  3871. int const bdhi)
  3872. {
  3873. for (; bdlo <= bdhi; ++bdlo)
  3874. {
  3875. png_uint_32 width;
  3876. for (width = 1; width <= 16; ++width)
  3877. {
  3878. png_uint_32 height;
  3879. for (height = 1; height <= 16; ++height)
  3880. {
  3881. /* The four combinations of DIY interlace and interlace or not -
  3882. * no interlace + DIY should be identical to no interlace with
  3883. * libpng doing it.
  3884. */
  3885. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3886. width, height, 0);
  3887. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE,
  3888. width, height, 1);
  3889. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  3890. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3891. width, height, 0);
  3892. # endif
  3893. # if CAN_WRITE_INTERLACE
  3894. /* 1.7.0 removes the hack that prevented app write of an interlaced
  3895. * image if WRITE_INTERLACE was not supported
  3896. */
  3897. make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7,
  3898. width, height, 1);
  3899. # endif
  3900. }
  3901. }
  3902. }
  3903. }
  3904. static void
  3905. make_size_images(png_store *ps)
  3906. {
  3907. /* This is in case of errors. */
  3908. safecat(ps->test, sizeof ps->test, 0, "make size images");
  3909. /* Arguments are colour_type, low bit depth, high bit depth
  3910. */
  3911. make_size(ps, 0, 0, WRITE_BDHI);
  3912. make_size(ps, 2, 3, WRITE_BDHI);
  3913. make_size(ps, 3, 0, 3 /*palette: max 8 bits*/);
  3914. make_size(ps, 4, 3, WRITE_BDHI);
  3915. make_size(ps, 6, 3, WRITE_BDHI);
  3916. }
  3917. #ifdef PNG_READ_SUPPORTED
  3918. /* Return a row based on image id and 'y' for checking: */
  3919. static void
  3920. standard_row(png_const_structp pp, png_byte std[STANDARD_ROWMAX],
  3921. png_uint_32 id, png_uint_32 y)
  3922. {
  3923. if (WIDTH_FROM_ID(id) == 0)
  3924. transform_row(pp, std, COL_FROM_ID(id), DEPTH_FROM_ID(id), y);
  3925. else
  3926. size_row(std, WIDTH_FROM_ID(id) * bit_size(pp, COL_FROM_ID(id),
  3927. DEPTH_FROM_ID(id)), y);
  3928. }
  3929. #endif /* PNG_READ_SUPPORTED */
  3930. /* Tests - individual test cases */
  3931. /* Like 'make_standard' but errors are deliberately introduced into the calls
  3932. * to ensure that they get detected - it should not be possible to write an
  3933. * invalid image with libpng!
  3934. */
  3935. /* TODO: the 'set' functions can probably all be made to take a
  3936. * png_const_structp rather than a modifiable one.
  3937. */
  3938. #ifdef PNG_WARNINGS_SUPPORTED
  3939. static void
  3940. sBIT0_error_fn(png_structp pp, png_infop pi)
  3941. {
  3942. /* 0 is invalid... */
  3943. png_color_8 bad;
  3944. bad.red = bad.green = bad.blue = bad.gray = bad.alpha = 0;
  3945. png_set_sBIT(pp, pi, &bad);
  3946. }
  3947. static void
  3948. sBIT_error_fn(png_structp pp, png_infop pi)
  3949. {
  3950. png_byte bit_depth;
  3951. png_color_8 bad;
  3952. if (png_get_color_type(pp, pi) == PNG_COLOR_TYPE_PALETTE)
  3953. bit_depth = 8;
  3954. else
  3955. bit_depth = png_get_bit_depth(pp, pi);
  3956. /* Now we know the bit depth we can easily generate an invalid sBIT entry */
  3957. bad.red = bad.green = bad.blue = bad.gray = bad.alpha =
  3958. (png_byte)(bit_depth+1);
  3959. png_set_sBIT(pp, pi, &bad);
  3960. }
  3961. static const struct
  3962. {
  3963. void (*fn)(png_structp, png_infop);
  3964. const char *msg;
  3965. unsigned int warning :1; /* the error is a warning... */
  3966. } error_test[] =
  3967. {
  3968. /* no warnings makes these errors undetectable prior to 1.7.0 */
  3969. { sBIT0_error_fn, "sBIT(0): failed to detect error",
  3970. PNG_LIBPNG_VER < 10700 },
  3971. { sBIT_error_fn, "sBIT(too big): failed to detect error",
  3972. PNG_LIBPNG_VER < 10700 },
  3973. };
  3974. static void
  3975. make_error(png_store* const ps, png_byte const colour_type,
  3976. png_byte bit_depth, int interlace_type, int test, png_const_charp name)
  3977. {
  3978. context(ps, fault);
  3979. check_interlace_type(interlace_type);
  3980. Try
  3981. {
  3982. png_infop pi;
  3983. png_structp pp = set_store_for_write(ps, &pi, name);
  3984. png_uint_32 w, h;
  3985. gnu_volatile(pp)
  3986. if (pp == NULL)
  3987. Throw ps;
  3988. w = transform_width(pp, colour_type, bit_depth);
  3989. gnu_volatile(w)
  3990. h = transform_height(pp, colour_type, bit_depth);
  3991. gnu_volatile(h)
  3992. png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type,
  3993. PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  3994. if (colour_type == 3) /* palette */
  3995. init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
  3996. /* Time for a few errors; these are in various optional chunks, the
  3997. * standard tests test the standard chunks pretty well.
  3998. */
  3999. # define exception__prev exception_prev_1
  4000. # define exception__env exception_env_1
  4001. Try
  4002. {
  4003. gnu_volatile(exception__prev)
  4004. /* Expect this to throw: */
  4005. ps->expect_error = !error_test[test].warning;
  4006. ps->expect_warning = error_test[test].warning;
  4007. ps->saw_warning = 0;
  4008. error_test[test].fn(pp, pi);
  4009. /* Normally the error is only detected here: */
  4010. png_write_info(pp, pi);
  4011. /* And handle the case where it was only a warning: */
  4012. if (ps->expect_warning && ps->saw_warning)
  4013. Throw ps;
  4014. /* If we get here there is a problem, we have success - no error or
  4015. * no warning - when we shouldn't have success. Log an error.
  4016. */
  4017. store_log(ps, pp, error_test[test].msg, 1 /*error*/);
  4018. }
  4019. Catch (fault)
  4020. { /* expected exit */
  4021. }
  4022. #undef exception__prev
  4023. #undef exception__env
  4024. /* And clear these flags */
  4025. ps->expect_warning = 0;
  4026. if (ps->expect_error)
  4027. ps->expect_error = 0;
  4028. else
  4029. {
  4030. /* Now write the whole image, just to make sure that the detected, or
  4031. * undetected, error has not created problems inside libpng. This
  4032. * doesn't work if there was a png_error in png_write_info because that
  4033. * can abort before PLTE was written.
  4034. */
  4035. if (png_get_rowbytes(pp, pi) !=
  4036. transform_rowsize(pp, colour_type, bit_depth))
  4037. png_error(pp, "row size incorrect");
  4038. else
  4039. {
  4040. int npasses = set_write_interlace_handling(pp, interlace_type);
  4041. int pass;
  4042. if (npasses != npasses_from_interlace_type(pp, interlace_type))
  4043. png_error(pp, "write: png_set_interlace_handling failed");
  4044. for (pass=0; pass<npasses; ++pass)
  4045. {
  4046. png_uint_32 y;
  4047. for (y=0; y<h; ++y)
  4048. {
  4049. png_byte buffer[TRANSFORM_ROWMAX];
  4050. transform_row(pp, buffer, colour_type, bit_depth, y);
  4051. # if do_own_interlace
  4052. /* If do_own_interlace *and* the image is interlaced we
  4053. * need a reduced interlace row; this may be reduced to
  4054. * empty.
  4055. */
  4056. if (interlace_type == PNG_INTERLACE_ADAM7)
  4057. {
  4058. /* The row must not be written if it doesn't exist,
  4059. * notice that there are two conditions here, either the
  4060. * row isn't ever in the pass or the row would be but
  4061. * isn't wide enough to contribute any pixels. In fact
  4062. * the wPass test can be used to skip the whole y loop
  4063. * in this case.
  4064. */
  4065. if (PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  4066. PNG_PASS_COLS(w, pass) > 0)
  4067. interlace_row(buffer, buffer,
  4068. bit_size(pp, colour_type, bit_depth), w, pass,
  4069. 0/*data always bigendian*/);
  4070. else
  4071. continue;
  4072. }
  4073. # endif /* do_own_interlace */
  4074. png_write_row(pp, buffer);
  4075. }
  4076. }
  4077. } /* image writing */
  4078. png_write_end(pp, pi);
  4079. }
  4080. /* The following deletes the file that was just written. */
  4081. store_write_reset(ps);
  4082. }
  4083. Catch(fault)
  4084. {
  4085. store_write_reset(fault);
  4086. }
  4087. }
  4088. static int
  4089. make_errors(png_modifier* const pm, png_byte const colour_type,
  4090. int bdlo, int const bdhi)
  4091. {
  4092. for (; bdlo <= bdhi; ++bdlo)
  4093. {
  4094. int interlace_type;
  4095. for (interlace_type = PNG_INTERLACE_NONE;
  4096. interlace_type < INTERLACE_LAST; ++interlace_type)
  4097. {
  4098. unsigned int test;
  4099. char name[FILE_NAME_SIZE];
  4100. standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0,
  4101. interlace_type, 0, 0, do_own_interlace);
  4102. for (test=0; test<ARRAY_SIZE(error_test); ++test)
  4103. {
  4104. make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type,
  4105. test, name);
  4106. if (fail(pm))
  4107. return 0;
  4108. }
  4109. }
  4110. }
  4111. return 1; /* keep going */
  4112. }
  4113. #endif /* PNG_WARNINGS_SUPPORTED */
  4114. static void
  4115. perform_error_test(png_modifier *pm)
  4116. {
  4117. #ifdef PNG_WARNINGS_SUPPORTED /* else there are no cases that work! */
  4118. /* Need to do this here because we just write in this test. */
  4119. safecat(pm->this.test, sizeof pm->this.test, 0, "error test");
  4120. if (!make_errors(pm, 0, 0, WRITE_BDHI))
  4121. return;
  4122. if (!make_errors(pm, 2, 3, WRITE_BDHI))
  4123. return;
  4124. if (!make_errors(pm, 3, 0, 3))
  4125. return;
  4126. if (!make_errors(pm, 4, 3, WRITE_BDHI))
  4127. return;
  4128. if (!make_errors(pm, 6, 3, WRITE_BDHI))
  4129. return;
  4130. #else
  4131. UNUSED(pm)
  4132. #endif
  4133. }
  4134. /* This is just to validate the internal PNG formatting code - if this fails
  4135. * then the warning messages the library outputs will probably be garbage.
  4136. */
  4137. static void
  4138. perform_formatting_test(png_store *ps)
  4139. {
  4140. #ifdef PNG_TIME_RFC1123_SUPPORTED
  4141. /* The handle into the formatting code is the RFC1123 support; this test does
  4142. * nothing if that is compiled out.
  4143. */
  4144. context(ps, fault);
  4145. Try
  4146. {
  4147. png_const_charp correct = "29 Aug 2079 13:53:60 +0000";
  4148. png_const_charp result;
  4149. # if PNG_LIBPNG_VER >= 10600
  4150. char timestring[29];
  4151. # endif
  4152. png_structp pp;
  4153. png_time pt;
  4154. pp = set_store_for_write(ps, NULL, "libpng formatting test");
  4155. if (pp == NULL)
  4156. Throw ps;
  4157. /* Arbitrary settings: */
  4158. pt.year = 2079;
  4159. pt.month = 8;
  4160. pt.day = 29;
  4161. pt.hour = 13;
  4162. pt.minute = 53;
  4163. pt.second = 60; /* a leap second */
  4164. # if PNG_LIBPNG_VER < 10600
  4165. result = png_convert_to_rfc1123(pp, &pt);
  4166. # else
  4167. if (png_convert_to_rfc1123_buffer(timestring, &pt))
  4168. result = timestring;
  4169. else
  4170. result = NULL;
  4171. # endif
  4172. if (result == NULL)
  4173. png_error(pp, "png_convert_to_rfc1123 failed");
  4174. if (strcmp(result, correct) != 0)
  4175. {
  4176. size_t pos = 0;
  4177. char msg[128];
  4178. pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123(");
  4179. pos = safecat(msg, sizeof msg, pos, correct);
  4180. pos = safecat(msg, sizeof msg, pos, ") returned: '");
  4181. pos = safecat(msg, sizeof msg, pos, result);
  4182. pos = safecat(msg, sizeof msg, pos, "'");
  4183. png_error(pp, msg);
  4184. }
  4185. store_write_reset(ps);
  4186. }
  4187. Catch(fault)
  4188. {
  4189. store_write_reset(fault);
  4190. }
  4191. #else
  4192. UNUSED(ps)
  4193. #endif
  4194. }
  4195. #ifdef PNG_READ_SUPPORTED
  4196. /* Because we want to use the same code in both the progressive reader and the
  4197. * sequential reader it is necessary to deal with the fact that the progressive
  4198. * reader callbacks only have one parameter (png_get_progressive_ptr()), so this
  4199. * must contain all the test parameters and all the local variables directly
  4200. * accessible to the sequential reader implementation.
  4201. *
  4202. * The technique adopted is to reinvent part of what Dijkstra termed a
  4203. * 'display'; an array of pointers to the stack frames of enclosing functions so
  4204. * that a nested function definition can access the local (C auto) variables of
  4205. * the functions that contain its definition. In fact C provides the first
  4206. * pointer (the local variables - the stack frame pointer) and the last (the
  4207. * global variables - the BCPL global vector typically implemented as global
  4208. * addresses), this code requires one more pointer to make the display - the
  4209. * local variables (and function call parameters) of the function that actually
  4210. * invokes either the progressive or sequential reader.
  4211. *
  4212. * Perhaps confusingly this technique is confounded with classes - the
  4213. * 'standard_display' defined here is sub-classed as the 'gamma_display' below.
  4214. * A gamma_display is a standard_display, taking advantage of the ANSI-C
  4215. * requirement that the pointer to the first member of a structure must be the
  4216. * same as the pointer to the structure. This allows us to reuse standard_
  4217. * functions in the gamma test code; something that could not be done with
  4218. * nested functions!
  4219. */
  4220. typedef struct standard_display
  4221. {
  4222. png_store* ps; /* Test parameters (passed to the function) */
  4223. png_byte colour_type;
  4224. png_byte bit_depth;
  4225. png_byte red_sBIT; /* Input data sBIT values. */
  4226. png_byte green_sBIT;
  4227. png_byte blue_sBIT;
  4228. png_byte alpha_sBIT;
  4229. png_byte interlace_type;
  4230. png_byte filler; /* Output has a filler */
  4231. png_uint_32 id; /* Calculated file ID */
  4232. png_uint_32 w; /* Width of image */
  4233. png_uint_32 h; /* Height of image */
  4234. int npasses; /* Number of interlaced passes */
  4235. png_uint_32 pixel_size; /* Width of one pixel in bits */
  4236. png_uint_32 bit_width; /* Width of output row in bits */
  4237. size_t cbRow; /* Bytes in a row of the output image */
  4238. int do_interlace; /* Do interlacing internally */
  4239. int littleendian; /* App (row) data is little endian */
  4240. int is_transparent; /* Transparency information was present. */
  4241. int has_tRNS; /* color type GRAY or RGB with a tRNS chunk. */
  4242. int speed; /* Doing a speed test */
  4243. int use_update_info;/* Call update_info, not start_image */
  4244. struct
  4245. {
  4246. png_uint_16 red;
  4247. png_uint_16 green;
  4248. png_uint_16 blue;
  4249. } transparent; /* The transparent color, if set. */
  4250. int npalette; /* Number of entries in the palette. */
  4251. store_palette
  4252. palette;
  4253. } standard_display;
  4254. static void
  4255. standard_display_init(standard_display *dp, png_store* ps, png_uint_32 id,
  4256. int do_interlace, int use_update_info)
  4257. {
  4258. memset(dp, 0, sizeof *dp);
  4259. dp->ps = ps;
  4260. dp->colour_type = COL_FROM_ID(id);
  4261. dp->bit_depth = DEPTH_FROM_ID(id);
  4262. if (dp->bit_depth < 1 || dp->bit_depth > 16)
  4263. internal_error(ps, "internal: bad bit depth");
  4264. if (dp->colour_type == 3)
  4265. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT = 8;
  4266. else
  4267. dp->red_sBIT = dp->blue_sBIT = dp->green_sBIT = dp->alpha_sBIT =
  4268. dp->bit_depth;
  4269. dp->interlace_type = INTERLACE_FROM_ID(id);
  4270. check_interlace_type(dp->interlace_type);
  4271. dp->id = id;
  4272. /* All the rest are filled in after the read_info: */
  4273. dp->w = 0;
  4274. dp->h = 0;
  4275. dp->npasses = 0;
  4276. dp->pixel_size = 0;
  4277. dp->bit_width = 0;
  4278. dp->cbRow = 0;
  4279. dp->do_interlace = do_interlace;
  4280. dp->littleendian = 0;
  4281. dp->is_transparent = 0;
  4282. dp->speed = ps->speed;
  4283. dp->use_update_info = use_update_info;
  4284. dp->npalette = 0;
  4285. /* Preset the transparent color to black: */
  4286. memset(&dp->transparent, 0, sizeof dp->transparent);
  4287. /* Preset the palette to full intensity/opaque throughout: */
  4288. memset(dp->palette, 0xff, sizeof dp->palette);
  4289. }
  4290. /* Initialize the palette fields - this must be done later because the palette
  4291. * comes from the particular png_store_file that is selected.
  4292. */
  4293. static void
  4294. standard_palette_init(standard_display *dp)
  4295. {
  4296. store_palette_entry *palette = store_current_palette(dp->ps, &dp->npalette);
  4297. /* The remaining entries remain white/opaque. */
  4298. if (dp->npalette > 0)
  4299. {
  4300. int i = dp->npalette;
  4301. memcpy(dp->palette, palette, i * sizeof *palette);
  4302. /* Check for a non-opaque palette entry: */
  4303. while (--i >= 0)
  4304. if (palette[i].alpha < 255)
  4305. break;
  4306. # ifdef __GNUC__
  4307. /* GCC can't handle the more obviously optimizable version. */
  4308. if (i >= 0)
  4309. dp->is_transparent = 1;
  4310. else
  4311. dp->is_transparent = 0;
  4312. # else
  4313. dp->is_transparent = (i >= 0);
  4314. # endif
  4315. }
  4316. }
  4317. /* Utility to read the palette from the PNG file and convert it into
  4318. * store_palette format. This returns 1 if there is any transparency in the
  4319. * palette (it does not check for a transparent colour in the non-palette case.)
  4320. */
  4321. static int
  4322. read_palette(store_palette palette, int *npalette, png_const_structp pp,
  4323. png_infop pi)
  4324. {
  4325. png_colorp pal;
  4326. png_bytep trans_alpha;
  4327. int num;
  4328. pal = 0;
  4329. *npalette = -1;
  4330. if (png_get_PLTE(pp, pi, &pal, npalette) & PNG_INFO_PLTE)
  4331. {
  4332. int i = *npalette;
  4333. if (i <= 0 || i > 256)
  4334. png_error(pp, "validate: invalid PLTE count");
  4335. while (--i >= 0)
  4336. {
  4337. palette[i].red = pal[i].red;
  4338. palette[i].green = pal[i].green;
  4339. palette[i].blue = pal[i].blue;
  4340. }
  4341. /* Mark the remainder of the entries with a flag value (other than
  4342. * white/opaque which is the flag value stored above.)
  4343. */
  4344. memset(palette + *npalette, 126, (256-*npalette) * sizeof *palette);
  4345. }
  4346. else /* !png_get_PLTE */
  4347. {
  4348. if (*npalette != (-1))
  4349. png_error(pp, "validate: invalid PLTE result");
  4350. /* But there is no palette, so record this: */
  4351. *npalette = 0;
  4352. memset(palette, 113, sizeof (store_palette));
  4353. }
  4354. trans_alpha = 0;
  4355. num = 2; /* force error below */
  4356. if ((png_get_tRNS(pp, pi, &trans_alpha, &num, 0) & PNG_INFO_tRNS) != 0 &&
  4357. (trans_alpha != NULL || num != 1/*returns 1 for a transparent color*/) &&
  4358. /* Oops, if a palette tRNS gets expanded png_read_update_info (at least so
  4359. * far as 1.5.4) does not remove the trans_alpha pointer, only num_trans,
  4360. * so in the above call we get a success, we get a pointer (who knows what
  4361. * to) and we get num_trans == 0:
  4362. */
  4363. !(trans_alpha != NULL && num == 0)) /* TODO: fix this in libpng. */
  4364. {
  4365. int i;
  4366. /* Any of these are crash-worthy - given the implementation of
  4367. * png_get_tRNS up to 1.5 an app won't crash if it just checks the
  4368. * result above and fails to check that the variables it passed have
  4369. * actually been filled in! Note that if the app were to pass the
  4370. * last, png_color_16p, variable too it couldn't rely on this.
  4371. */
  4372. if (trans_alpha == NULL || num <= 0 || num > 256 || num > *npalette)
  4373. png_error(pp, "validate: unexpected png_get_tRNS (palette) result");
  4374. for (i=0; i<num; ++i)
  4375. palette[i].alpha = trans_alpha[i];
  4376. for (num=*npalette; i<num; ++i)
  4377. palette[i].alpha = 255;
  4378. for (; i<256; ++i)
  4379. palette[i].alpha = 33; /* flag value */
  4380. return 1; /* transparency */
  4381. }
  4382. else
  4383. {
  4384. /* No palette transparency - just set the alpha channel to opaque. */
  4385. int i;
  4386. for (i=0, num=*npalette; i<num; ++i)
  4387. palette[i].alpha = 255;
  4388. for (; i<256; ++i)
  4389. palette[i].alpha = 55; /* flag value */
  4390. return 0; /* no transparency */
  4391. }
  4392. }
  4393. /* Utility to validate the palette if it should not have changed (the
  4394. * non-transform case).
  4395. */
  4396. static void
  4397. standard_palette_validate(standard_display *dp, png_const_structp pp,
  4398. png_infop pi)
  4399. {
  4400. int npalette;
  4401. store_palette palette;
  4402. if (read_palette(palette, &npalette, pp, pi) != dp->is_transparent)
  4403. png_error(pp, "validate: palette transparency changed");
  4404. if (npalette != dp->npalette)
  4405. {
  4406. size_t pos = 0;
  4407. char msg[64];
  4408. pos = safecat(msg, sizeof msg, pos, "validate: palette size changed: ");
  4409. pos = safecatn(msg, sizeof msg, pos, dp->npalette);
  4410. pos = safecat(msg, sizeof msg, pos, " -> ");
  4411. pos = safecatn(msg, sizeof msg, pos, npalette);
  4412. png_error(pp, msg);
  4413. }
  4414. {
  4415. int i = npalette; /* npalette is aliased */
  4416. while (--i >= 0)
  4417. if (palette[i].red != dp->palette[i].red ||
  4418. palette[i].green != dp->palette[i].green ||
  4419. palette[i].blue != dp->palette[i].blue ||
  4420. palette[i].alpha != dp->palette[i].alpha)
  4421. png_error(pp, "validate: PLTE or tRNS chunk changed");
  4422. }
  4423. }
  4424. /* By passing a 'standard_display' the progressive callbacks can be used
  4425. * directly by the sequential code, the functions suffixed "_imp" are the
  4426. * implementations, the functions without the suffix are the callbacks.
  4427. *
  4428. * The code for the info callback is split into two because this callback calls
  4429. * png_read_update_info or png_start_read_image and what gets called depends on
  4430. * whether the info needs updating (we want to test both calls in pngvalid.)
  4431. */
  4432. static void
  4433. standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
  4434. {
  4435. if (png_get_bit_depth(pp, pi) != dp->bit_depth)
  4436. png_error(pp, "validate: bit depth changed");
  4437. if (png_get_color_type(pp, pi) != dp->colour_type)
  4438. png_error(pp, "validate: color type changed");
  4439. if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
  4440. png_error(pp, "validate: filter type changed");
  4441. if (png_get_interlace_type(pp, pi) != dp->interlace_type)
  4442. png_error(pp, "validate: interlacing changed");
  4443. if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
  4444. png_error(pp, "validate: compression type changed");
  4445. dp->w = png_get_image_width(pp, pi);
  4446. if (dp->w != standard_width(pp, dp->id))
  4447. png_error(pp, "validate: image width changed");
  4448. dp->h = png_get_image_height(pp, pi);
  4449. if (dp->h != standard_height(pp, dp->id))
  4450. png_error(pp, "validate: image height changed");
  4451. /* Record (but don't check at present) the input sBIT according to the colour
  4452. * type information.
  4453. */
  4454. {
  4455. png_color_8p sBIT = 0;
  4456. if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
  4457. {
  4458. int sBIT_invalid = 0;
  4459. if (sBIT == 0)
  4460. png_error(pp, "validate: unexpected png_get_sBIT result");
  4461. if (dp->colour_type & PNG_COLOR_MASK_COLOR)
  4462. {
  4463. if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
  4464. sBIT_invalid = 1;
  4465. else
  4466. dp->red_sBIT = sBIT->red;
  4467. if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
  4468. sBIT_invalid = 1;
  4469. else
  4470. dp->green_sBIT = sBIT->green;
  4471. if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
  4472. sBIT_invalid = 1;
  4473. else
  4474. dp->blue_sBIT = sBIT->blue;
  4475. }
  4476. else /* !COLOR */
  4477. {
  4478. if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
  4479. sBIT_invalid = 1;
  4480. else
  4481. dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
  4482. }
  4483. /* All 8 bits in tRNS for a palette image are significant - see the
  4484. * spec.
  4485. */
  4486. if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
  4487. {
  4488. if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
  4489. sBIT_invalid = 1;
  4490. else
  4491. dp->alpha_sBIT = sBIT->alpha;
  4492. }
  4493. if (sBIT_invalid)
  4494. png_error(pp, "validate: sBIT value out of range");
  4495. }
  4496. }
  4497. /* Important: this is validating the value *before* any transforms have been
  4498. * put in place. It doesn't matter for the standard tests, where there are
  4499. * no transforms, but it does for other tests where rowbytes may change after
  4500. * png_read_update_info.
  4501. */
  4502. if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
  4503. png_error(pp, "validate: row size changed");
  4504. /* Validate the colour type 3 palette (this can be present on other color
  4505. * types.)
  4506. */
  4507. standard_palette_validate(dp, pp, pi);
  4508. /* In any case always check for a transparent color (notice that the
  4509. * colour type 3 case must not give a successful return on the get_tRNS call
  4510. * with these arguments!)
  4511. */
  4512. {
  4513. png_color_16p trans_color = 0;
  4514. if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
  4515. {
  4516. if (trans_color == 0)
  4517. png_error(pp, "validate: unexpected png_get_tRNS (color) result");
  4518. switch (dp->colour_type)
  4519. {
  4520. case 0:
  4521. dp->transparent.red = dp->transparent.green = dp->transparent.blue =
  4522. trans_color->gray;
  4523. dp->has_tRNS = 1;
  4524. break;
  4525. case 2:
  4526. dp->transparent.red = trans_color->red;
  4527. dp->transparent.green = trans_color->green;
  4528. dp->transparent.blue = trans_color->blue;
  4529. dp->has_tRNS = 1;
  4530. break;
  4531. case 3:
  4532. /* Not expected because it should result in the array case
  4533. * above.
  4534. */
  4535. png_error(pp, "validate: unexpected png_get_tRNS result");
  4536. break;
  4537. default:
  4538. png_error(pp, "validate: invalid tRNS chunk with alpha image");
  4539. }
  4540. }
  4541. }
  4542. /* Read the number of passes - expected to match the value used when
  4543. * creating the image (interlaced or not). This has the side effect of
  4544. * turning on interlace handling (if do_interlace is not set.)
  4545. */
  4546. dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
  4547. if (!dp->do_interlace)
  4548. {
  4549. # ifdef PNG_READ_INTERLACING_SUPPORTED
  4550. if (dp->npasses != png_set_interlace_handling(pp))
  4551. png_error(pp, "validate: file changed interlace type");
  4552. # else /* !READ_INTERLACING */
  4553. /* This should never happen: the relevant tests (!do_interlace) should
  4554. * not be run.
  4555. */
  4556. if (dp->npasses > 1)
  4557. png_error(pp, "validate: no libpng interlace support");
  4558. # endif /* !READ_INTERLACING */
  4559. }
  4560. /* Caller calls png_read_update_info or png_start_read_image now, then calls
  4561. * part2.
  4562. */
  4563. }
  4564. /* This must be called *after* the png_read_update_info call to get the correct
  4565. * 'rowbytes' value, otherwise png_get_rowbytes will refer to the untransformed
  4566. * image.
  4567. */
  4568. static void
  4569. standard_info_part2(standard_display *dp, png_const_structp pp,
  4570. png_const_infop pi, int nImages)
  4571. {
  4572. /* Record cbRow now that it can be found. */
  4573. {
  4574. png_byte ct = png_get_color_type(pp, pi);
  4575. png_byte bd = png_get_bit_depth(pp, pi);
  4576. if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) &&
  4577. dp->filler)
  4578. ct |= 4; /* handle filler as faked alpha channel */
  4579. dp->pixel_size = bit_size(pp, ct, bd);
  4580. }
  4581. dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size;
  4582. dp->cbRow = png_get_rowbytes(pp, pi);
  4583. /* Validate the rowbytes here again. */
  4584. if (dp->cbRow != (dp->bit_width+7)/8)
  4585. png_error(pp, "bad png_get_rowbytes calculation");
  4586. /* Then ensure there is enough space for the output image(s). */
  4587. store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h);
  4588. }
  4589. static void
  4590. standard_info_imp(standard_display *dp, png_structp pp, png_infop pi,
  4591. int nImages)
  4592. {
  4593. /* Note that the validation routine has the side effect of turning on
  4594. * interlace handling in the subsequent code.
  4595. */
  4596. standard_info_part1(dp, pp, pi);
  4597. /* And the info callback has to call this (or png_read_update_info - see
  4598. * below in the png_modifier code for that variant.
  4599. */
  4600. if (dp->use_update_info)
  4601. {
  4602. /* For debugging the effect of multiple calls: */
  4603. int i = dp->use_update_info;
  4604. while (i-- > 0)
  4605. png_read_update_info(pp, pi);
  4606. }
  4607. else
  4608. png_start_read_image(pp);
  4609. /* Validate the height, width and rowbytes plus ensure that sufficient buffer
  4610. * exists for decoding the image.
  4611. */
  4612. standard_info_part2(dp, pp, pi, nImages);
  4613. }
  4614. static void PNGCBAPI
  4615. standard_info(png_structp pp, png_infop pi)
  4616. {
  4617. standard_display *dp = voidcast(standard_display*,
  4618. png_get_progressive_ptr(pp));
  4619. /* Call with nImages==1 because the progressive reader can only produce one
  4620. * image.
  4621. */
  4622. standard_info_imp(dp, pp, pi, 1 /*only one image*/);
  4623. }
  4624. static void PNGCBAPI
  4625. progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass)
  4626. {
  4627. png_const_structp pp = ppIn;
  4628. const standard_display *dp = voidcast(standard_display*,
  4629. png_get_progressive_ptr(pp));
  4630. /* When handling interlacing some rows will be absent in each pass, the
  4631. * callback still gets called, but with a NULL pointer. This is checked
  4632. * in the 'else' clause below. We need our own 'cbRow', but we can't call
  4633. * png_get_rowbytes because we got no info structure.
  4634. */
  4635. if (new_row != NULL)
  4636. {
  4637. png_bytep row;
  4638. /* In the case where the reader doesn't do the interlace it gives
  4639. * us the y in the sub-image:
  4640. */
  4641. if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7)
  4642. {
  4643. #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED
  4644. /* Use this opportunity to validate the png 'current' APIs: */
  4645. if (y != png_get_current_row_number(pp))
  4646. png_error(pp, "png_get_current_row_number is broken");
  4647. if (pass != png_get_current_pass_number(pp))
  4648. png_error(pp, "png_get_current_pass_number is broken");
  4649. #endif /* USER_TRANSFORM_INFO */
  4650. y = PNG_ROW_FROM_PASS_ROW(y, pass);
  4651. }
  4652. /* Validate this just in case. */
  4653. if (y >= dp->h)
  4654. png_error(pp, "invalid y to progressive row callback");
  4655. row = store_image_row(dp->ps, pp, 0, y);
  4656. /* Combine the new row into the old: */
  4657. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4658. if (dp->do_interlace)
  4659. #endif /* READ_INTERLACING */
  4660. {
  4661. if (dp->interlace_type == PNG_INTERLACE_ADAM7)
  4662. deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass,
  4663. dp->littleendian);
  4664. else
  4665. row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian);
  4666. }
  4667. #ifdef PNG_READ_INTERLACING_SUPPORTED
  4668. else
  4669. png_progressive_combine_row(pp, row, new_row);
  4670. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  4671. }
  4672. else if (dp->interlace_type == PNG_INTERLACE_ADAM7 &&
  4673. PNG_ROW_IN_INTERLACE_PASS(y, pass) &&
  4674. PNG_PASS_COLS(dp->w, pass) > 0)
  4675. png_error(pp, "missing row in progressive de-interlacing");
  4676. }
  4677. static void
  4678. sequential_row(standard_display *dp, png_structp pp, png_infop pi,
  4679. int iImage, int iDisplay)
  4680. {
  4681. int npasses = dp->npasses;
  4682. int do_interlace = dp->do_interlace &&
  4683. dp->interlace_type == PNG_INTERLACE_ADAM7;
  4684. png_uint_32 height = standard_height(pp, dp->id);
  4685. png_uint_32 width = standard_width(pp, dp->id);
  4686. const png_store* ps = dp->ps;
  4687. int pass;
  4688. for (pass=0; pass<npasses; ++pass)
  4689. {
  4690. png_uint_32 y;
  4691. png_uint_32 wPass = PNG_PASS_COLS(width, pass);
  4692. for (y=0; y<height; ++y)
  4693. {
  4694. if (do_interlace)
  4695. {
  4696. /* wPass may be zero or this row may not be in this pass.
  4697. * png_read_row must not be called in either case.
  4698. */
  4699. if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
  4700. {
  4701. /* Read the row into a pair of temporary buffers, then do the
  4702. * merge here into the output rows.
  4703. */
  4704. png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
  4705. /* The following aids (to some extent) error detection - we can
  4706. * see where png_read_row wrote. Use opposite values in row and
  4707. * display to make this easier. Don't use 0xff (which is used in
  4708. * the image write code to fill unused bits) or 0 (which is a
  4709. * likely value to overwrite unused bits with).
  4710. */
  4711. memset(row, 0xc5, sizeof row);
  4712. memset(display, 0x5c, sizeof display);
  4713. png_read_row(pp, row, display);
  4714. if (iImage >= 0)
  4715. deinterlace_row(store_image_row(ps, pp, iImage, y), row,
  4716. dp->pixel_size, dp->w, pass, dp->littleendian);
  4717. if (iDisplay >= 0)
  4718. deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
  4719. dp->pixel_size, dp->w, pass, dp->littleendian);
  4720. }
  4721. }
  4722. else
  4723. png_read_row(pp,
  4724. iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
  4725. iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
  4726. }
  4727. }
  4728. /* And finish the read operation (only really necessary if the caller wants
  4729. * to find additional data in png_info from chunks after the last IDAT.)
  4730. */
  4731. png_read_end(pp, pi);
  4732. }
  4733. #ifdef PNG_TEXT_SUPPORTED
  4734. static void
  4735. standard_check_text(png_const_structp pp, png_const_textp tp,
  4736. png_const_charp keyword, png_const_charp text)
  4737. {
  4738. char msg[1024];
  4739. size_t pos = safecat(msg, sizeof msg, 0, "text: ");
  4740. size_t ok;
  4741. pos = safecat(msg, sizeof msg, pos, keyword);
  4742. pos = safecat(msg, sizeof msg, pos, ": ");
  4743. ok = pos;
  4744. if (tp->compression != TEXT_COMPRESSION)
  4745. {
  4746. char buf[64];
  4747. sprintf(buf, "compression [%d->%d], ", TEXT_COMPRESSION,
  4748. tp->compression);
  4749. pos = safecat(msg, sizeof msg, pos, buf);
  4750. }
  4751. if (tp->key == NULL || strcmp(tp->key, keyword) != 0)
  4752. {
  4753. pos = safecat(msg, sizeof msg, pos, "keyword \"");
  4754. if (tp->key != NULL)
  4755. {
  4756. pos = safecat(msg, sizeof msg, pos, tp->key);
  4757. pos = safecat(msg, sizeof msg, pos, "\", ");
  4758. }
  4759. else
  4760. pos = safecat(msg, sizeof msg, pos, "null, ");
  4761. }
  4762. if (tp->text == NULL)
  4763. pos = safecat(msg, sizeof msg, pos, "text lost, ");
  4764. else
  4765. {
  4766. if (tp->text_length != strlen(text))
  4767. {
  4768. char buf[64];
  4769. sprintf(buf, "text length changed[%lu->%lu], ",
  4770. (unsigned long)strlen(text), (unsigned long)tp->text_length);
  4771. pos = safecat(msg, sizeof msg, pos, buf);
  4772. }
  4773. if (strcmp(tp->text, text) != 0)
  4774. {
  4775. pos = safecat(msg, sizeof msg, pos, "text becomes \"");
  4776. pos = safecat(msg, sizeof msg, pos, tp->text);
  4777. pos = safecat(msg, sizeof msg, pos, "\" (was \"");
  4778. pos = safecat(msg, sizeof msg, pos, text);
  4779. pos = safecat(msg, sizeof msg, pos, "\"), ");
  4780. }
  4781. }
  4782. if (tp->itxt_length != 0)
  4783. pos = safecat(msg, sizeof msg, pos, "iTXt length set, ");
  4784. if (tp->lang != NULL)
  4785. {
  4786. pos = safecat(msg, sizeof msg, pos, "iTXt language \"");
  4787. pos = safecat(msg, sizeof msg, pos, tp->lang);
  4788. pos = safecat(msg, sizeof msg, pos, "\", ");
  4789. }
  4790. if (tp->lang_key != NULL)
  4791. {
  4792. pos = safecat(msg, sizeof msg, pos, "iTXt keyword \"");
  4793. pos = safecat(msg, sizeof msg, pos, tp->lang_key);
  4794. pos = safecat(msg, sizeof msg, pos, "\", ");
  4795. }
  4796. if (pos > ok)
  4797. {
  4798. msg[pos-2] = '\0'; /* Remove the ", " at the end */
  4799. png_error(pp, msg);
  4800. }
  4801. }
  4802. static void
  4803. standard_text_validate(standard_display *dp, png_const_structp pp,
  4804. png_infop pi, int check_end)
  4805. {
  4806. png_textp tp = NULL;
  4807. png_uint_32 num_text = png_get_text(pp, pi, &tp, NULL);
  4808. if (num_text == 2 && tp != NULL)
  4809. {
  4810. standard_check_text(pp, tp, "image name", dp->ps->current->name);
  4811. /* This exists because prior to 1.5.18 the progressive reader left the
  4812. * png_struct z_stream unreset at the end of the image, so subsequent
  4813. * attempts to use it simply returns Z_STREAM_END.
  4814. */
  4815. if (check_end)
  4816. standard_check_text(pp, tp+1, "end marker", "end");
  4817. }
  4818. else
  4819. {
  4820. char msg[64];
  4821. sprintf(msg, "expected two text items, got %lu",
  4822. (unsigned long)num_text);
  4823. png_error(pp, msg);
  4824. }
  4825. }
  4826. #else
  4827. # define standard_text_validate(dp,pp,pi,check_end) ((void)0)
  4828. #endif
  4829. static void
  4830. standard_row_validate(standard_display *dp, png_const_structp pp,
  4831. int iImage, int iDisplay, png_uint_32 y)
  4832. {
  4833. int where;
  4834. png_byte std[STANDARD_ROWMAX];
  4835. /* The row must be pre-initialized to the magic number here for the size
  4836. * tests to pass:
  4837. */
  4838. memset(std, 178, sizeof std);
  4839. standard_row(pp, std, dp->id, y);
  4840. /* At the end both the 'row' and 'display' arrays should end up identical.
  4841. * In earlier passes 'row' will be partially filled in, with only the pixels
  4842. * that have been read so far, but 'display' will have those pixels
  4843. * replicated to fill the unread pixels while reading an interlaced image.
  4844. */
  4845. if (iImage >= 0 &&
  4846. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
  4847. dp->bit_width)) != 0)
  4848. {
  4849. char msg[64];
  4850. sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
  4851. (unsigned long)y, where-1, std[where-1],
  4852. store_image_row(dp->ps, pp, iImage, y)[where-1]);
  4853. png_error(pp, msg);
  4854. }
  4855. if (iDisplay >= 0 &&
  4856. (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
  4857. dp->bit_width)) != 0)
  4858. {
  4859. char msg[64];
  4860. sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
  4861. (unsigned long)y, where-1, std[where-1],
  4862. store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
  4863. png_error(pp, msg);
  4864. }
  4865. }
  4866. static void
  4867. standard_image_validate(standard_display *dp, png_const_structp pp, int iImage,
  4868. int iDisplay)
  4869. {
  4870. png_uint_32 y;
  4871. if (iImage >= 0)
  4872. store_image_check(dp->ps, pp, iImage);
  4873. if (iDisplay >= 0)
  4874. store_image_check(dp->ps, pp, iDisplay);
  4875. for (y=0; y<dp->h; ++y)
  4876. standard_row_validate(dp, pp, iImage, iDisplay, y);
  4877. /* This avoids false positives if the validation code is never called! */
  4878. dp->ps->validated = 1;
  4879. }
  4880. static void PNGCBAPI
  4881. standard_end(png_structp ppIn, png_infop pi)
  4882. {
  4883. png_const_structp pp = ppIn;
  4884. standard_display *dp = voidcast(standard_display*,
  4885. png_get_progressive_ptr(pp));
  4886. UNUSED(pi)
  4887. /* Validate the image - progressive reading only produces one variant for
  4888. * interlaced images.
  4889. */
  4890. standard_text_validate(dp, pp, pi,
  4891. PNG_LIBPNG_VER >= 10518/*check_end: see comments above*/);
  4892. standard_image_validate(dp, pp, 0, -1);
  4893. }
  4894. /* A single test run checking the standard image to ensure it is not damaged. */
  4895. static void
  4896. standard_test(png_store* const psIn, png_uint_32 const id,
  4897. int do_interlace, int use_update_info)
  4898. {
  4899. standard_display d;
  4900. context(psIn, fault);
  4901. /* Set up the display (stack frame) variables from the arguments to the
  4902. * function and initialize the locals that are filled in later.
  4903. */
  4904. standard_display_init(&d, psIn, id, do_interlace, use_update_info);
  4905. /* Everything is protected by a Try/Catch. The functions called also
  4906. * typically have local Try/Catch blocks.
  4907. */
  4908. Try
  4909. {
  4910. png_structp pp;
  4911. png_infop pi;
  4912. /* Get a png_struct for reading the image. This will throw an error if it
  4913. * fails, so we don't need to check the result.
  4914. */
  4915. pp = set_store_for_read(d.ps, &pi, d.id,
  4916. d.do_interlace ? (d.ps->progressive ?
  4917. "pngvalid progressive deinterlacer" :
  4918. "pngvalid sequential deinterlacer") : (d.ps->progressive ?
  4919. "progressive reader" : "sequential reader"));
  4920. /* Initialize the palette correctly from the png_store_file. */
  4921. standard_palette_init(&d);
  4922. /* Introduce the correct read function. */
  4923. if (d.ps->progressive)
  4924. {
  4925. png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
  4926. standard_end);
  4927. /* Now feed data into the reader until we reach the end: */
  4928. store_progressive_read(d.ps, pp, pi);
  4929. }
  4930. else
  4931. {
  4932. /* Note that this takes the store, not the display. */
  4933. png_set_read_fn(pp, d.ps, store_read);
  4934. /* Check the header values: */
  4935. png_read_info(pp, pi);
  4936. /* The code tests both versions of the images that the sequential
  4937. * reader can produce.
  4938. */
  4939. standard_info_imp(&d, pp, pi, 2 /*images*/);
  4940. /* Need the total bytes in the image below; we can't get to this point
  4941. * unless the PNG file values have been checked against the expected
  4942. * values.
  4943. */
  4944. {
  4945. sequential_row(&d, pp, pi, 0, 1);
  4946. /* After the last pass loop over the rows again to check that the
  4947. * image is correct.
  4948. */
  4949. if (!d.speed)
  4950. {
  4951. standard_text_validate(&d, pp, pi, 1/*check_end*/);
  4952. standard_image_validate(&d, pp, 0, 1);
  4953. }
  4954. else
  4955. d.ps->validated = 1;
  4956. }
  4957. }
  4958. /* Check for validation. */
  4959. if (!d.ps->validated)
  4960. png_error(pp, "image read failed silently");
  4961. /* Successful completion. */
  4962. }
  4963. Catch(fault)
  4964. d.ps = fault; /* make sure this hasn't been clobbered. */
  4965. /* In either case clean up the store. */
  4966. store_read_reset(d.ps);
  4967. }
  4968. static int
  4969. test_standard(png_modifier* const pm, png_byte const colour_type,
  4970. int bdlo, int const bdhi)
  4971. {
  4972. for (; bdlo <= bdhi; ++bdlo)
  4973. {
  4974. int interlace_type;
  4975. for (interlace_type = PNG_INTERLACE_NONE;
  4976. interlace_type < INTERLACE_LAST; ++interlace_type)
  4977. {
  4978. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  4979. interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info);
  4980. if (fail(pm))
  4981. return 0;
  4982. }
  4983. }
  4984. return 1; /* keep going */
  4985. }
  4986. static void
  4987. perform_standard_test(png_modifier *pm)
  4988. {
  4989. /* Test each colour type over the valid range of bit depths (expressed as
  4990. * log2(bit_depth) in turn, stop as soon as any error is detected.
  4991. */
  4992. if (!test_standard(pm, 0, 0, READ_BDHI))
  4993. return;
  4994. if (!test_standard(pm, 2, 3, READ_BDHI))
  4995. return;
  4996. if (!test_standard(pm, 3, 0, 3))
  4997. return;
  4998. if (!test_standard(pm, 4, 3, READ_BDHI))
  4999. return;
  5000. if (!test_standard(pm, 6, 3, READ_BDHI))
  5001. return;
  5002. }
  5003. /********************************** SIZE TESTS ********************************/
  5004. static int
  5005. test_size(png_modifier* const pm, png_byte const colour_type,
  5006. int bdlo, int const bdhi)
  5007. {
  5008. /* Run the tests on each combination.
  5009. *
  5010. * NOTE: on my 32 bit x86 each of the following blocks takes
  5011. * a total of 3.5 seconds if done across every combo of bit depth
  5012. * width and height. This is a waste of time in practice, hence the
  5013. * hinc and winc stuff:
  5014. */
  5015. static const png_byte hinc[] = {1, 3, 11, 1, 5};
  5016. static const png_byte winc[] = {1, 9, 5, 7, 1};
  5017. int save_bdlo = bdlo;
  5018. for (; bdlo <= bdhi; ++bdlo)
  5019. {
  5020. png_uint_32 h, w;
  5021. for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
  5022. {
  5023. /* First test all the 'size' images against the sequential
  5024. * reader using libpng to deinterlace (where required.) This
  5025. * validates the write side of libpng. There are four possibilities
  5026. * to validate.
  5027. */
  5028. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  5029. PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
  5030. pm->use_update_info);
  5031. if (fail(pm))
  5032. return 0;
  5033. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  5034. PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
  5035. pm->use_update_info);
  5036. if (fail(pm))
  5037. return 0;
  5038. /* Now validate the interlaced read side - do_interlace true,
  5039. * in the progressive case this does actually make a difference
  5040. * to the code used in the non-interlaced case too.
  5041. */
  5042. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  5043. PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
  5044. pm->use_update_info);
  5045. if (fail(pm))
  5046. return 0;
  5047. # if CAN_WRITE_INTERLACE
  5048. /* Validate the pngvalid code itself: */
  5049. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  5050. PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
  5051. pm->use_update_info);
  5052. if (fail(pm))
  5053. return 0;
  5054. # endif
  5055. }
  5056. }
  5057. /* Now do the tests of libpng interlace handling, after we have made sure
  5058. * that the pngvalid version works:
  5059. */
  5060. for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
  5061. {
  5062. png_uint_32 h, w;
  5063. for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
  5064. {
  5065. # ifdef PNG_READ_INTERLACING_SUPPORTED
  5066. /* Test with pngvalid generated interlaced images first; we have
  5067. * already verify these are ok (unless pngvalid has self-consistent
  5068. * read/write errors, which is unlikely), so this detects errors in the
  5069. * read side first:
  5070. */
  5071. # if CAN_WRITE_INTERLACE
  5072. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  5073. PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
  5074. pm->use_update_info);
  5075. if (fail(pm))
  5076. return 0;
  5077. # endif
  5078. # endif /* READ_INTERLACING */
  5079. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  5080. /* Test the libpng write side against the pngvalid read side: */
  5081. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  5082. PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
  5083. pm->use_update_info);
  5084. if (fail(pm))
  5085. return 0;
  5086. # endif
  5087. # ifdef PNG_READ_INTERLACING_SUPPORTED
  5088. # ifdef PNG_WRITE_INTERLACING_SUPPORTED
  5089. /* Test both together: */
  5090. standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
  5091. PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
  5092. pm->use_update_info);
  5093. if (fail(pm))
  5094. return 0;
  5095. # endif
  5096. # endif /* READ_INTERLACING */
  5097. }
  5098. }
  5099. return 1; /* keep going */
  5100. }
  5101. static void
  5102. perform_size_test(png_modifier *pm)
  5103. {
  5104. /* Test each colour type over the valid range of bit depths (expressed as
  5105. * log2(bit_depth) in turn, stop as soon as any error is detected.
  5106. */
  5107. if (!test_size(pm, 0, 0, READ_BDHI))
  5108. return;
  5109. if (!test_size(pm, 2, 3, READ_BDHI))
  5110. return;
  5111. /* For the moment don't do the palette test - it's a waste of time when
  5112. * compared to the grayscale test.
  5113. */
  5114. #if 0
  5115. if (!test_size(pm, 3, 0, 3))
  5116. return;
  5117. #endif
  5118. if (!test_size(pm, 4, 3, READ_BDHI))
  5119. return;
  5120. if (!test_size(pm, 6, 3, READ_BDHI))
  5121. return;
  5122. }
  5123. /******************************* TRANSFORM TESTS ******************************/
  5124. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  5125. /* A set of tests to validate libpng image transforms. The possibilities here
  5126. * are legion because the transforms can be combined in a combinatorial
  5127. * fashion. To deal with this some measure of restraint is required, otherwise
  5128. * the tests would take forever.
  5129. */
  5130. typedef struct image_pixel
  5131. {
  5132. /* A local (pngvalid) representation of a PNG pixel, in all its
  5133. * various forms.
  5134. */
  5135. unsigned int red, green, blue, alpha; /* For non-palette images. */
  5136. unsigned int palette_index; /* For a palette image. */
  5137. png_byte colour_type; /* As in the spec. */
  5138. png_byte bit_depth; /* Defines bit size in row */
  5139. png_byte sample_depth; /* Scale of samples */
  5140. unsigned int have_tRNS :1; /* tRNS chunk may need processing */
  5141. unsigned int swap_rgb :1; /* RGB swapped to BGR */
  5142. unsigned int alpha_first :1; /* Alpha at start, not end */
  5143. unsigned int alpha_inverted :1; /* Alpha channel inverted */
  5144. unsigned int mono_inverted :1; /* Gray channel inverted */
  5145. unsigned int swap16 :1; /* Byte swap 16-bit components */
  5146. unsigned int littleendian :1; /* High bits on right */
  5147. unsigned int sig_bits :1; /* Pixel shifted (sig bits only) */
  5148. /* For checking the code calculates double precision floating point values
  5149. * along with an error value, accumulated from the transforms. Because an
  5150. * sBIT setting allows larger error bounds (indeed, by the spec, apparently
  5151. * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each
  5152. * channel is stored. This sBIT value is folded in to the stored error value
  5153. * at the end of the application of the transforms to the pixel.
  5154. *
  5155. * If sig_bits is set above the red, green, blue and alpha values have been
  5156. * scaled so they only contain the significant bits of the component values.
  5157. */
  5158. double redf, greenf, bluef, alphaf;
  5159. double rede, greene, bluee, alphae;
  5160. png_byte red_sBIT, green_sBIT, blue_sBIT, alpha_sBIT;
  5161. } image_pixel;
  5162. /* Shared utility function, see below. */
  5163. static void
  5164. image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax,
  5165. unsigned int bMax, unsigned int aMax)
  5166. {
  5167. this->redf = this->red / (double)rMax;
  5168. this->greenf = this->green / (double)gMax;
  5169. this->bluef = this->blue / (double)bMax;
  5170. this->alphaf = this->alpha / (double)aMax;
  5171. if (this->red < rMax)
  5172. this->rede = this->redf * DBL_EPSILON;
  5173. else
  5174. this->rede = 0;
  5175. if (this->green < gMax)
  5176. this->greene = this->greenf * DBL_EPSILON;
  5177. else
  5178. this->greene = 0;
  5179. if (this->blue < bMax)
  5180. this->bluee = this->bluef * DBL_EPSILON;
  5181. else
  5182. this->bluee = 0;
  5183. if (this->alpha < aMax)
  5184. this->alphae = this->alphaf * DBL_EPSILON;
  5185. else
  5186. this->alphae = 0;
  5187. }
  5188. /* Initialize the structure for the next pixel - call this before doing any
  5189. * transforms and call it for each pixel since all the fields may need to be
  5190. * reset.
  5191. */
  5192. static void
  5193. image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
  5194. png_byte bit_depth, png_uint_32 x, store_palette palette,
  5195. const image_pixel *format /*from pngvalid transform of input*/)
  5196. {
  5197. png_byte sample_depth =
  5198. (png_byte)(colour_type == PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
  5199. unsigned int max = (1U<<sample_depth)-1;
  5200. int swap16 = (format != 0 && format->swap16);
  5201. int littleendian = (format != 0 && format->littleendian);
  5202. int sig_bits = (format != 0 && format->sig_bits);
  5203. /* Initially just set everything to the same number and the alpha to opaque.
  5204. * Note that this currently assumes a simple palette where entry x has colour
  5205. * rgb(x,x,x)!
  5206. */
  5207. this->palette_index = this->red = this->green = this->blue =
  5208. sample(row, colour_type, bit_depth, x, 0, swap16, littleendian);
  5209. this->alpha = max;
  5210. this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
  5211. sample_depth;
  5212. /* Then override as appropriate: */
  5213. if (colour_type == 3) /* palette */
  5214. {
  5215. /* This permits the caller to default to the sample value. */
  5216. if (palette != 0)
  5217. {
  5218. unsigned int i = this->palette_index;
  5219. this->red = palette[i].red;
  5220. this->green = palette[i].green;
  5221. this->blue = palette[i].blue;
  5222. this->alpha = palette[i].alpha;
  5223. }
  5224. }
  5225. else /* not palette */
  5226. {
  5227. unsigned int i = 0;
  5228. if ((colour_type & 4) != 0 && format != 0 && format->alpha_first)
  5229. {
  5230. this->alpha = this->red;
  5231. /* This handles the gray case for 'AG' pixels */
  5232. this->palette_index = this->red = this->green = this->blue =
  5233. sample(row, colour_type, bit_depth, x, 1, swap16, littleendian);
  5234. i = 1;
  5235. }
  5236. if (colour_type & 2)
  5237. {
  5238. /* Green is second for both BGR and RGB: */
  5239. this->green = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5240. littleendian);
  5241. if (format != 0 && format->swap_rgb) /* BGR */
  5242. this->red = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5243. littleendian);
  5244. else
  5245. this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5246. littleendian);
  5247. }
  5248. else /* grayscale */ if (format != 0 && format->mono_inverted)
  5249. this->red = this->green = this->blue = this->red ^ max;
  5250. if ((colour_type & 4) != 0) /* alpha */
  5251. {
  5252. if (format == 0 || !format->alpha_first)
  5253. this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16,
  5254. littleendian);
  5255. if (format != 0 && format->alpha_inverted)
  5256. this->alpha ^= max;
  5257. }
  5258. }
  5259. /* Calculate the scaled values, these are simply the values divided by
  5260. * 'max' and the error is initialized to the double precision epsilon value
  5261. * from the header file.
  5262. */
  5263. image_pixel_setf(this,
  5264. sig_bits ? (1U << format->red_sBIT)-1 : max,
  5265. sig_bits ? (1U << format->green_sBIT)-1 : max,
  5266. sig_bits ? (1U << format->blue_sBIT)-1 : max,
  5267. sig_bits ? (1U << format->alpha_sBIT)-1 : max);
  5268. /* Store the input information for use in the transforms - these will
  5269. * modify the information.
  5270. */
  5271. this->colour_type = colour_type;
  5272. this->bit_depth = bit_depth;
  5273. this->sample_depth = sample_depth;
  5274. this->have_tRNS = 0;
  5275. this->swap_rgb = 0;
  5276. this->alpha_first = 0;
  5277. this->alpha_inverted = 0;
  5278. this->mono_inverted = 0;
  5279. this->swap16 = 0;
  5280. this->littleendian = 0;
  5281. this->sig_bits = 0;
  5282. }
  5283. #if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\
  5284. || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\
  5285. || defined PNG_READ_BACKGROUND_SUPPORTED
  5286. /* Convert a palette image to an rgb image. This necessarily converts the tRNS
  5287. * chunk at the same time, because the tRNS will be in palette form. The way
  5288. * palette validation works means that the original palette is never updated,
  5289. * instead the image_pixel value from the row contains the RGB of the
  5290. * corresponding palette entry and *this* is updated. Consequently this routine
  5291. * only needs to change the colour type information.
  5292. */
  5293. static void
  5294. image_pixel_convert_PLTE(image_pixel *this)
  5295. {
  5296. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  5297. {
  5298. if (this->have_tRNS)
  5299. {
  5300. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  5301. this->have_tRNS = 0;
  5302. }
  5303. else
  5304. this->colour_type = PNG_COLOR_TYPE_RGB;
  5305. /* The bit depth of the row changes at this point too (notice that this is
  5306. * the row format, not the sample depth, which is separate.)
  5307. */
  5308. this->bit_depth = 8;
  5309. }
  5310. }
  5311. /* Add an alpha channel; this will import the tRNS information because tRNS is
  5312. * not valid in an alpha image. The bit depth will invariably be set to at
  5313. * least 8 prior to 1.7.0. Palette images will be converted to alpha (using
  5314. * the above API). With png_set_background the alpha channel is never expanded
  5315. * but this routine is used by pngvalid to simplify code; 'for_background'
  5316. * records this.
  5317. */
  5318. static void
  5319. image_pixel_add_alpha(image_pixel *this, const standard_display *display,
  5320. int for_background)
  5321. {
  5322. if (this->colour_type == PNG_COLOR_TYPE_PALETTE)
  5323. image_pixel_convert_PLTE(this);
  5324. if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
  5325. {
  5326. if (this->colour_type == PNG_COLOR_TYPE_GRAY)
  5327. {
  5328. # if PNG_LIBPNG_VER < 10700
  5329. if (!for_background && this->bit_depth < 8)
  5330. this->bit_depth = this->sample_depth = 8;
  5331. # endif
  5332. if (this->have_tRNS)
  5333. {
  5334. /* After 1.7 the expansion of bit depth only happens if there is a
  5335. * tRNS chunk to expand at this point.
  5336. */
  5337. # if PNG_LIBPNG_VER >= 10700
  5338. if (!for_background && this->bit_depth < 8)
  5339. this->bit_depth = this->sample_depth = 8;
  5340. # endif
  5341. this->have_tRNS = 0;
  5342. /* Check the input, original, channel value here against the
  5343. * original tRNS gray chunk valie.
  5344. */
  5345. if (this->red == display->transparent.red)
  5346. this->alphaf = 0;
  5347. else
  5348. this->alphaf = 1;
  5349. }
  5350. else
  5351. this->alphaf = 1;
  5352. this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  5353. }
  5354. else if (this->colour_type == PNG_COLOR_TYPE_RGB)
  5355. {
  5356. if (this->have_tRNS)
  5357. {
  5358. this->have_tRNS = 0;
  5359. /* Again, check the exact input values, not the current transformed
  5360. * value!
  5361. */
  5362. if (this->red == display->transparent.red &&
  5363. this->green == display->transparent.green &&
  5364. this->blue == display->transparent.blue)
  5365. this->alphaf = 0;
  5366. else
  5367. this->alphaf = 1;
  5368. }
  5369. else
  5370. this->alphaf = 1;
  5371. this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  5372. }
  5373. /* The error in the alpha is zero and the sBIT value comes from the
  5374. * original sBIT data (actually it will always be the original bit depth).
  5375. */
  5376. this->alphae = 0;
  5377. this->alpha_sBIT = display->alpha_sBIT;
  5378. }
  5379. }
  5380. #endif /* transforms that need image_pixel_add_alpha */
  5381. struct transform_display;
  5382. typedef struct image_transform
  5383. {
  5384. /* The name of this transform: a string. */
  5385. const char *name;
  5386. /* Each transform can be disabled from the command line: */
  5387. int enable;
  5388. /* The global list of transforms; read only. */
  5389. struct image_transform *const list;
  5390. /* The global count of the number of times this transform has been set on an
  5391. * image.
  5392. */
  5393. unsigned int global_use;
  5394. /* The local count of the number of times this transform has been set. */
  5395. unsigned int local_use;
  5396. /* The next transform in the list, each transform must call its own next
  5397. * transform after it has processed the pixel successfully.
  5398. */
  5399. const struct image_transform *next;
  5400. /* A single transform for the image, expressed as a series of function
  5401. * callbacks and some space for values.
  5402. *
  5403. * First a callback to add any required modifications to the png_modifier;
  5404. * this gets called just before the modifier is set up for read.
  5405. */
  5406. void (*ini)(const struct image_transform *this,
  5407. struct transform_display *that);
  5408. /* And a callback to set the transform on the current png_read_struct:
  5409. */
  5410. void (*set)(const struct image_transform *this,
  5411. struct transform_display *that, png_structp pp, png_infop pi);
  5412. /* Then a transform that takes an input pixel in one PNG format or another
  5413. * and modifies it by a pngvalid implementation of the transform (thus
  5414. * duplicating the libpng intent without, we hope, duplicating the bugs
  5415. * in the libpng implementation!) The png_structp is solely to allow error
  5416. * reporting via png_error and png_warning.
  5417. */
  5418. void (*mod)(const struct image_transform *this, image_pixel *that,
  5419. png_const_structp pp, const struct transform_display *display);
  5420. /* Add this transform to the list and return true if the transform is
  5421. * meaningful for this colour type and bit depth - if false then the
  5422. * transform should have no effect on the image so there's not a lot of
  5423. * point running it.
  5424. */
  5425. int (*add)(struct image_transform *this,
  5426. const struct image_transform **that, png_byte colour_type,
  5427. png_byte bit_depth);
  5428. } image_transform;
  5429. typedef struct transform_display
  5430. {
  5431. standard_display this;
  5432. /* Parameters */
  5433. png_modifier* pm;
  5434. const image_transform* transform_list;
  5435. unsigned int max_gamma_8;
  5436. /* Local variables */
  5437. png_byte output_colour_type;
  5438. png_byte output_bit_depth;
  5439. png_byte unpacked;
  5440. /* Modifications (not necessarily used.) */
  5441. gama_modification gama_mod;
  5442. chrm_modification chrm_mod;
  5443. srgb_modification srgb_mod;
  5444. } transform_display;
  5445. /* Set sRGB, cHRM and gAMA transforms as required by the current encoding. */
  5446. static void
  5447. transform_set_encoding(transform_display *this)
  5448. {
  5449. /* Set up the png_modifier '_current' fields then use these to determine how
  5450. * to add appropriate chunks.
  5451. */
  5452. png_modifier *pm = this->pm;
  5453. modifier_set_encoding(pm);
  5454. if (modifier_color_encoding_is_set(pm))
  5455. {
  5456. if (modifier_color_encoding_is_sRGB(pm))
  5457. srgb_modification_init(&this->srgb_mod, pm, PNG_sRGB_INTENT_ABSOLUTE);
  5458. else
  5459. {
  5460. /* Set gAMA and cHRM separately. */
  5461. gama_modification_init(&this->gama_mod, pm, pm->current_gamma);
  5462. if (pm->current_encoding != 0)
  5463. chrm_modification_init(&this->chrm_mod, pm, pm->current_encoding);
  5464. }
  5465. }
  5466. }
  5467. /* Three functions to end the list: */
  5468. static void
  5469. image_transform_ini_end(const image_transform *this,
  5470. transform_display *that)
  5471. {
  5472. UNUSED(this)
  5473. UNUSED(that)
  5474. }
  5475. static void
  5476. image_transform_set_end(const image_transform *this,
  5477. transform_display *that, png_structp pp, png_infop pi)
  5478. {
  5479. UNUSED(this)
  5480. UNUSED(that)
  5481. UNUSED(pp)
  5482. UNUSED(pi)
  5483. }
  5484. /* At the end of the list recalculate the output image pixel value from the
  5485. * double precision values set up by the preceding 'mod' calls:
  5486. */
  5487. static unsigned int
  5488. sample_scale(double sample_value, unsigned int scale)
  5489. {
  5490. sample_value = floor(sample_value * scale + .5);
  5491. /* Return NaN as 0: */
  5492. if (!(sample_value > 0))
  5493. sample_value = 0;
  5494. else if (sample_value > scale)
  5495. sample_value = scale;
  5496. return (unsigned int)sample_value;
  5497. }
  5498. static void
  5499. image_transform_mod_end(const image_transform *this, image_pixel *that,
  5500. png_const_structp pp, const transform_display *display)
  5501. {
  5502. unsigned int scale = (1U<<that->sample_depth)-1;
  5503. int sig_bits = that->sig_bits;
  5504. UNUSED(this)
  5505. UNUSED(pp)
  5506. UNUSED(display)
  5507. /* At the end recalculate the digitized red green and blue values according
  5508. * to the current sample_depth of the pixel.
  5509. *
  5510. * The sample value is simply scaled to the maximum, checking for over
  5511. * and underflow (which can both happen for some image transforms,
  5512. * including simple size scaling, though libpng doesn't do that at present.
  5513. */
  5514. that->red = sample_scale(that->redf, scale);
  5515. /* This is a bit bogus; really the above calculation should use the red_sBIT
  5516. * value, not sample_depth, but because libpng does png_set_shift by just
  5517. * shifting the bits we get errors if we don't do it the same way.
  5518. */
  5519. if (sig_bits && that->red_sBIT < that->sample_depth)
  5520. that->red >>= that->sample_depth - that->red_sBIT;
  5521. /* The error value is increased, at the end, according to the lowest sBIT
  5522. * value seen. Common sense tells us that the intermediate integer
  5523. * representations are no more accurate than +/- 0.5 in the integral values,
  5524. * the sBIT allows the implementation to be worse than this. In addition the
  5525. * PNG specification actually permits any error within the range (-1..+1),
  5526. * but that is ignored here. Instead the final digitized value is compared,
  5527. * below to the digitized value of the error limits - this has the net effect
  5528. * of allowing (almost) +/-1 in the output value. It's difficult to see how
  5529. * any algorithm that digitizes intermediate results can be more accurate.
  5530. */
  5531. that->rede += 1./(2*((1U<<that->red_sBIT)-1));
  5532. if (that->colour_type & PNG_COLOR_MASK_COLOR)
  5533. {
  5534. that->green = sample_scale(that->greenf, scale);
  5535. if (sig_bits && that->green_sBIT < that->sample_depth)
  5536. that->green >>= that->sample_depth - that->green_sBIT;
  5537. that->blue = sample_scale(that->bluef, scale);
  5538. if (sig_bits && that->blue_sBIT < that->sample_depth)
  5539. that->blue >>= that->sample_depth - that->blue_sBIT;
  5540. that->greene += 1./(2*((1U<<that->green_sBIT)-1));
  5541. that->bluee += 1./(2*((1U<<that->blue_sBIT)-1));
  5542. }
  5543. else
  5544. {
  5545. that->blue = that->green = that->red;
  5546. that->bluef = that->greenf = that->redf;
  5547. that->bluee = that->greene = that->rede;
  5548. }
  5549. if ((that->colour_type & PNG_COLOR_MASK_ALPHA) ||
  5550. that->colour_type == PNG_COLOR_TYPE_PALETTE)
  5551. {
  5552. that->alpha = sample_scale(that->alphaf, scale);
  5553. that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1));
  5554. }
  5555. else
  5556. {
  5557. that->alpha = scale; /* opaque */
  5558. that->alphaf = 1; /* Override this. */
  5559. that->alphae = 0; /* It's exact ;-) */
  5560. }
  5561. if (sig_bits && that->alpha_sBIT < that->sample_depth)
  5562. that->alpha >>= that->sample_depth - that->alpha_sBIT;
  5563. }
  5564. /* Static 'end' structure: */
  5565. static image_transform image_transform_end =
  5566. {
  5567. "(end)", /* name */
  5568. 1, /* enable */
  5569. 0, /* list */
  5570. 0, /* global_use */
  5571. 0, /* local_use */
  5572. 0, /* next */
  5573. image_transform_ini_end,
  5574. image_transform_set_end,
  5575. image_transform_mod_end,
  5576. 0 /* never called, I want it to crash if it is! */
  5577. };
  5578. /* Reader callbacks and implementations, where they differ from the standard
  5579. * ones.
  5580. */
  5581. static void
  5582. transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id,
  5583. const image_transform *transform_list)
  5584. {
  5585. memset(dp, 0, sizeof *dp);
  5586. /* Standard fields */
  5587. standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
  5588. pm->use_update_info);
  5589. /* Parameter fields */
  5590. dp->pm = pm;
  5591. dp->transform_list = transform_list;
  5592. dp->max_gamma_8 = 16;
  5593. /* Local variable fields */
  5594. dp->output_colour_type = 255; /* invalid */
  5595. dp->output_bit_depth = 255; /* invalid */
  5596. dp->unpacked = 0; /* not unpacked */
  5597. }
  5598. static void
  5599. transform_info_imp(transform_display *dp, png_structp pp, png_infop pi)
  5600. {
  5601. /* Reuse the standard stuff as appropriate. */
  5602. standard_info_part1(&dp->this, pp, pi);
  5603. /* Now set the list of transforms. */
  5604. dp->transform_list->set(dp->transform_list, dp, pp, pi);
  5605. /* Update the info structure for these transforms: */
  5606. {
  5607. int i = dp->this.use_update_info;
  5608. /* Always do one call, even if use_update_info is 0. */
  5609. do
  5610. png_read_update_info(pp, pi);
  5611. while (--i > 0);
  5612. }
  5613. /* And get the output information into the standard_display */
  5614. standard_info_part2(&dp->this, pp, pi, 1/*images*/);
  5615. /* Plus the extra stuff we need for the transform tests: */
  5616. dp->output_colour_type = png_get_color_type(pp, pi);
  5617. dp->output_bit_depth = png_get_bit_depth(pp, pi);
  5618. /* If png_set_filler is in action then fake the output color type to include
  5619. * an alpha channel where appropriate.
  5620. */
  5621. if (dp->output_bit_depth >= 8 &&
  5622. (dp->output_colour_type == PNG_COLOR_TYPE_RGB ||
  5623. dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler)
  5624. dp->output_colour_type |= 4;
  5625. /* Validate the combination of colour type and bit depth that we are getting
  5626. * out of libpng; the semantics of something not in the PNG spec are, at
  5627. * best, unclear.
  5628. */
  5629. switch (dp->output_colour_type)
  5630. {
  5631. case PNG_COLOR_TYPE_PALETTE:
  5632. if (dp->output_bit_depth > 8) goto error;
  5633. /* FALLTHROUGH */
  5634. case PNG_COLOR_TYPE_GRAY:
  5635. if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 ||
  5636. dp->output_bit_depth == 4)
  5637. break;
  5638. /* FALLTHROUGH */
  5639. default:
  5640. if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16)
  5641. break;
  5642. /* FALLTHROUGH */
  5643. error:
  5644. {
  5645. char message[128];
  5646. size_t pos;
  5647. pos = safecat(message, sizeof message, 0,
  5648. "invalid final bit depth: colour type(");
  5649. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  5650. pos = safecat(message, sizeof message, pos, ") with bit depth: ");
  5651. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5652. png_error(pp, message);
  5653. }
  5654. }
  5655. /* Use a test pixel to check that the output agrees with what we expect -
  5656. * this avoids running the whole test if the output is unexpected. This also
  5657. * checks for internal errors.
  5658. */
  5659. {
  5660. image_pixel test_pixel;
  5661. memset(&test_pixel, 0, sizeof test_pixel);
  5662. test_pixel.colour_type = dp->this.colour_type; /* input */
  5663. test_pixel.bit_depth = dp->this.bit_depth;
  5664. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE)
  5665. test_pixel.sample_depth = 8;
  5666. else
  5667. test_pixel.sample_depth = test_pixel.bit_depth;
  5668. /* Don't need sBIT here, but it must be set to non-zero to avoid
  5669. * arithmetic overflows.
  5670. */
  5671. test_pixel.have_tRNS = dp->this.is_transparent != 0;
  5672. test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT =
  5673. test_pixel.alpha_sBIT = test_pixel.sample_depth;
  5674. dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp);
  5675. if (test_pixel.colour_type != dp->output_colour_type)
  5676. {
  5677. char message[128];
  5678. size_t pos = safecat(message, sizeof message, 0, "colour type ");
  5679. pos = safecatn(message, sizeof message, pos, dp->output_colour_type);
  5680. pos = safecat(message, sizeof message, pos, " expected ");
  5681. pos = safecatn(message, sizeof message, pos, test_pixel.colour_type);
  5682. png_error(pp, message);
  5683. }
  5684. if (test_pixel.bit_depth != dp->output_bit_depth)
  5685. {
  5686. char message[128];
  5687. size_t pos = safecat(message, sizeof message, 0, "bit depth ");
  5688. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5689. pos = safecat(message, sizeof message, pos, " expected ");
  5690. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5691. png_error(pp, message);
  5692. }
  5693. /* If both bit depth and colour type are correct check the sample depth.
  5694. */
  5695. if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE &&
  5696. test_pixel.sample_depth != 8) /* oops - internal error! */
  5697. png_error(pp, "pngvalid: internal: palette sample depth not 8");
  5698. else if (dp->unpacked && test_pixel.bit_depth != 8)
  5699. png_error(pp, "pngvalid: internal: bad unpacked pixel depth");
  5700. else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE
  5701. && test_pixel.bit_depth != test_pixel.sample_depth)
  5702. {
  5703. char message[128];
  5704. size_t pos = safecat(message, sizeof message, 0,
  5705. "internal: sample depth ");
  5706. /* Because unless something has set 'unpacked' or the image is palette
  5707. * mapped we expect the transform to keep sample depth and bit depth
  5708. * the same.
  5709. */
  5710. pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth);
  5711. pos = safecat(message, sizeof message, pos, " expected ");
  5712. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5713. png_error(pp, message);
  5714. }
  5715. else if (test_pixel.bit_depth != dp->output_bit_depth)
  5716. {
  5717. /* This could be a libpng error too; libpng has not produced what we
  5718. * expect for the output bit depth.
  5719. */
  5720. char message[128];
  5721. size_t pos = safecat(message, sizeof message, 0,
  5722. "internal: bit depth ");
  5723. pos = safecatn(message, sizeof message, pos, dp->output_bit_depth);
  5724. pos = safecat(message, sizeof message, pos, " expected ");
  5725. pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth);
  5726. png_error(pp, message);
  5727. }
  5728. }
  5729. }
  5730. static void PNGCBAPI
  5731. transform_info(png_structp pp, png_infop pi)
  5732. {
  5733. transform_info_imp(voidcast(transform_display*, png_get_progressive_ptr(pp)),
  5734. pp, pi);
  5735. }
  5736. static void
  5737. transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
  5738. unsigned int b, unsigned int a, unsigned int in_digitized, double in,
  5739. unsigned int out, png_byte sample_depth, double err, double limit,
  5740. const char *name, double digitization_error)
  5741. {
  5742. /* Compare the scaled, digitzed, values of our local calculation (in+-err)
  5743. * with the digitized values libpng produced; 'sample_depth' is the actual
  5744. * digitization depth of the libpng output colors (the bit depth except for
  5745. * palette images where it is always 8.) The check on 'err' is to detect
  5746. * internal errors in pngvalid itself.
  5747. */
  5748. unsigned int max = (1U<<sample_depth)-1;
  5749. double in_min = ceil((in-err)*max - digitization_error);
  5750. double in_max = floor((in+err)*max + digitization_error);
  5751. if (debugonly(err > limit ||) !(out >= in_min && out <= in_max))
  5752. {
  5753. char message[256];
  5754. size_t pos;
  5755. pos = safecat(message, sizeof message, 0, name);
  5756. pos = safecat(message, sizeof message, pos, " output value error: rgba(");
  5757. pos = safecatn(message, sizeof message, pos, r);
  5758. pos = safecat(message, sizeof message, pos, ",");
  5759. pos = safecatn(message, sizeof message, pos, g);
  5760. pos = safecat(message, sizeof message, pos, ",");
  5761. pos = safecatn(message, sizeof message, pos, b);
  5762. pos = safecat(message, sizeof message, pos, ",");
  5763. pos = safecatn(message, sizeof message, pos, a);
  5764. pos = safecat(message, sizeof message, pos, "): ");
  5765. pos = safecatn(message, sizeof message, pos, out);
  5766. pos = safecat(message, sizeof message, pos, " expected: ");
  5767. pos = safecatn(message, sizeof message, pos, in_digitized);
  5768. pos = safecat(message, sizeof message, pos, " (");
  5769. pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
  5770. pos = safecat(message, sizeof message, pos, "..");
  5771. pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
  5772. pos = safecat(message, sizeof message, pos, ")");
  5773. png_error(pp, message);
  5774. }
  5775. UNUSED(limit)
  5776. }
  5777. static void
  5778. transform_image_validate(transform_display *dp, png_const_structp pp,
  5779. png_infop pi)
  5780. {
  5781. /* Constants for the loop below: */
  5782. const png_store* const ps = dp->this.ps;
  5783. png_byte in_ct = dp->this.colour_type;
  5784. png_byte in_bd = dp->this.bit_depth;
  5785. png_uint_32 w = dp->this.w;
  5786. png_uint_32 h = dp->this.h;
  5787. png_byte out_ct = dp->output_colour_type;
  5788. png_byte out_bd = dp->output_bit_depth;
  5789. png_byte sample_depth =
  5790. (png_byte)(out_ct == PNG_COLOR_TYPE_PALETTE ? 8 : out_bd);
  5791. png_byte red_sBIT = dp->this.red_sBIT;
  5792. png_byte green_sBIT = dp->this.green_sBIT;
  5793. png_byte blue_sBIT = dp->this.blue_sBIT;
  5794. png_byte alpha_sBIT = dp->this.alpha_sBIT;
  5795. int have_tRNS = dp->this.is_transparent;
  5796. double digitization_error;
  5797. store_palette out_palette;
  5798. png_uint_32 y;
  5799. UNUSED(pi)
  5800. /* Check for row overwrite errors */
  5801. store_image_check(dp->this.ps, pp, 0);
  5802. /* Read the palette corresponding to the output if the output colour type
  5803. * indicates a palette, otherwise set out_palette to garbage.
  5804. */
  5805. if (out_ct == PNG_COLOR_TYPE_PALETTE)
  5806. {
  5807. /* Validate that the palette count itself has not changed - this is not
  5808. * expected.
  5809. */
  5810. int npalette = (-1);
  5811. (void)read_palette(out_palette, &npalette, pp, pi);
  5812. if (npalette != dp->this.npalette)
  5813. png_error(pp, "unexpected change in palette size");
  5814. digitization_error = .5;
  5815. }
  5816. else
  5817. {
  5818. png_byte in_sample_depth;
  5819. memset(out_palette, 0x5e, sizeof out_palette);
  5820. /* use-input-precision means assume that if the input has 8 bit (or less)
  5821. * samples and the output has 16 bit samples the calculations will be done
  5822. * with 8 bit precision, not 16.
  5823. */
  5824. if (in_ct == PNG_COLOR_TYPE_PALETTE || in_bd < 16)
  5825. in_sample_depth = 8;
  5826. else
  5827. in_sample_depth = in_bd;
  5828. if (sample_depth != 16 || in_sample_depth > 8 ||
  5829. !dp->pm->calculations_use_input_precision)
  5830. digitization_error = .5;
  5831. /* Else calculations are at 8 bit precision, and the output actually
  5832. * consists of scaled 8-bit values, so scale .5 in 8 bits to the 16 bits:
  5833. */
  5834. else
  5835. digitization_error = .5 * 257;
  5836. }
  5837. for (y=0; y<h; ++y)
  5838. {
  5839. png_const_bytep const pRow = store_image_row(ps, pp, 0, y);
  5840. png_uint_32 x;
  5841. /* The original, standard, row pre-transforms. */
  5842. png_byte std[STANDARD_ROWMAX];
  5843. transform_row(pp, std, in_ct, in_bd, y);
  5844. /* Go through each original pixel transforming it and comparing with what
  5845. * libpng did to the same pixel.
  5846. */
  5847. for (x=0; x<w; ++x)
  5848. {
  5849. image_pixel in_pixel, out_pixel;
  5850. unsigned int r, g, b, a;
  5851. /* Find out what we think the pixel should be: */
  5852. image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette,
  5853. NULL);
  5854. in_pixel.red_sBIT = red_sBIT;
  5855. in_pixel.green_sBIT = green_sBIT;
  5856. in_pixel.blue_sBIT = blue_sBIT;
  5857. in_pixel.alpha_sBIT = alpha_sBIT;
  5858. in_pixel.have_tRNS = have_tRNS != 0;
  5859. /* For error detection, below. */
  5860. r = in_pixel.red;
  5861. g = in_pixel.green;
  5862. b = in_pixel.blue;
  5863. a = in_pixel.alpha;
  5864. /* This applies the transforms to the input data, including output
  5865. * format operations which must be used when reading the output
  5866. * pixel that libpng produces.
  5867. */
  5868. dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp);
  5869. /* Read the output pixel and compare it to what we got, we don't
  5870. * use the error field here, so no need to update sBIT. in_pixel
  5871. * says whether we expect libpng to change the output format.
  5872. */
  5873. image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette,
  5874. &in_pixel);
  5875. /* We don't expect changes to the index here even if the bit depth is
  5876. * changed.
  5877. */
  5878. if (in_ct == PNG_COLOR_TYPE_PALETTE &&
  5879. out_ct == PNG_COLOR_TYPE_PALETTE)
  5880. {
  5881. if (in_pixel.palette_index != out_pixel.palette_index)
  5882. png_error(pp, "unexpected transformed palette index");
  5883. }
  5884. /* Check the colours for palette images too - in fact the palette could
  5885. * be separately verified itself in most cases.
  5886. */
  5887. if (in_pixel.red != out_pixel.red)
  5888. transform_range_check(pp, r, g, b, a, in_pixel.red, in_pixel.redf,
  5889. out_pixel.red, sample_depth, in_pixel.rede,
  5890. dp->pm->limit + 1./(2*((1U<<in_pixel.red_sBIT)-1)), "red/gray",
  5891. digitization_error);
  5892. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5893. in_pixel.green != out_pixel.green)
  5894. transform_range_check(pp, r, g, b, a, in_pixel.green,
  5895. in_pixel.greenf, out_pixel.green, sample_depth, in_pixel.greene,
  5896. dp->pm->limit + 1./(2*((1U<<in_pixel.green_sBIT)-1)), "green",
  5897. digitization_error);
  5898. if ((out_ct & PNG_COLOR_MASK_COLOR) != 0 &&
  5899. in_pixel.blue != out_pixel.blue)
  5900. transform_range_check(pp, r, g, b, a, in_pixel.blue, in_pixel.bluef,
  5901. out_pixel.blue, sample_depth, in_pixel.bluee,
  5902. dp->pm->limit + 1./(2*((1U<<in_pixel.blue_sBIT)-1)), "blue",
  5903. digitization_error);
  5904. if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0 &&
  5905. in_pixel.alpha != out_pixel.alpha)
  5906. transform_range_check(pp, r, g, b, a, in_pixel.alpha,
  5907. in_pixel.alphaf, out_pixel.alpha, sample_depth, in_pixel.alphae,
  5908. dp->pm->limit + 1./(2*((1U<<in_pixel.alpha_sBIT)-1)), "alpha",
  5909. digitization_error);
  5910. } /* pixel (x) loop */
  5911. } /* row (y) loop */
  5912. /* Record that something was actually checked to avoid a false positive. */
  5913. dp->this.ps->validated = 1;
  5914. }
  5915. static void PNGCBAPI
  5916. transform_end(png_structp ppIn, png_infop pi)
  5917. {
  5918. png_const_structp pp = ppIn;
  5919. transform_display *dp = voidcast(transform_display*,
  5920. png_get_progressive_ptr(pp));
  5921. if (!dp->this.speed)
  5922. transform_image_validate(dp, pp, pi);
  5923. else
  5924. dp->this.ps->validated = 1;
  5925. }
  5926. /* A single test run. */
  5927. static void
  5928. transform_test(png_modifier *pmIn, png_uint_32 idIn,
  5929. const image_transform* transform_listIn, const char * const name)
  5930. {
  5931. transform_display d;
  5932. context(&pmIn->this, fault);
  5933. transform_display_init(&d, pmIn, idIn, transform_listIn);
  5934. Try
  5935. {
  5936. size_t pos = 0;
  5937. png_structp pp;
  5938. png_infop pi;
  5939. char full_name[256];
  5940. /* Make sure the encoding fields are correct and enter the required
  5941. * modifications.
  5942. */
  5943. transform_set_encoding(&d);
  5944. /* Add any modifications required by the transform list. */
  5945. d.transform_list->ini(d.transform_list, &d);
  5946. /* Add the color space information, if any, to the name. */
  5947. pos = safecat(full_name, sizeof full_name, pos, name);
  5948. pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
  5949. /* Get a png_struct for reading the image. */
  5950. pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
  5951. standard_palette_init(&d.this);
  5952. # if 0
  5953. /* Logging (debugging only) */
  5954. {
  5955. char buffer[256];
  5956. (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
  5957. "running test");
  5958. fprintf(stderr, "%s\n", buffer);
  5959. }
  5960. # endif
  5961. /* Introduce the correct read function. */
  5962. if (d.pm->this.progressive)
  5963. {
  5964. /* Share the row function with the standard implementation. */
  5965. png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
  5966. transform_end);
  5967. /* Now feed data into the reader until we reach the end: */
  5968. modifier_progressive_read(d.pm, pp, pi);
  5969. }
  5970. else
  5971. {
  5972. /* modifier_read expects a png_modifier* */
  5973. png_set_read_fn(pp, d.pm, modifier_read);
  5974. /* Check the header values: */
  5975. png_read_info(pp, pi);
  5976. /* Process the 'info' requirements. Only one image is generated */
  5977. transform_info_imp(&d, pp, pi);
  5978. sequential_row(&d.this, pp, pi, -1, 0);
  5979. if (!d.this.speed)
  5980. transform_image_validate(&d, pp, pi);
  5981. else
  5982. d.this.ps->validated = 1;
  5983. }
  5984. modifier_reset(d.pm);
  5985. }
  5986. Catch(fault)
  5987. {
  5988. modifier_reset(voidcast(png_modifier*,(void*)fault));
  5989. }
  5990. }
  5991. /* The transforms: */
  5992. #define ITSTRUCT(name) image_transform_##name
  5993. #define ITDATA(name) image_transform_data_##name
  5994. #define image_transform_ini image_transform_default_ini
  5995. #define IT(name)\
  5996. static image_transform ITSTRUCT(name) =\
  5997. {\
  5998. #name,\
  5999. 1, /*enable*/\
  6000. &PT, /*list*/\
  6001. 0, /*global_use*/\
  6002. 0, /*local_use*/\
  6003. 0, /*next*/\
  6004. image_transform_ini,\
  6005. image_transform_png_set_##name##_set,\
  6006. image_transform_png_set_##name##_mod,\
  6007. image_transform_png_set_##name##_add\
  6008. }
  6009. #define PT ITSTRUCT(end) /* stores the previous transform */
  6010. /* To save code: */
  6011. extern void image_transform_default_ini(const image_transform *this,
  6012. transform_display *that); /* silence GCC warnings */
  6013. void /* private, but almost always needed */
  6014. image_transform_default_ini(const image_transform *this,
  6015. transform_display *that)
  6016. {
  6017. this->next->ini(this->next, that);
  6018. }
  6019. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  6020. static int
  6021. image_transform_default_add(image_transform *this,
  6022. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6023. {
  6024. UNUSED(colour_type)
  6025. UNUSED(bit_depth)
  6026. this->next = *that;
  6027. *that = this;
  6028. return 1;
  6029. }
  6030. #endif
  6031. #ifdef PNG_READ_EXPAND_SUPPORTED
  6032. /* png_set_palette_to_rgb */
  6033. static void
  6034. image_transform_png_set_palette_to_rgb_set(const image_transform *this,
  6035. transform_display *that, png_structp pp, png_infop pi)
  6036. {
  6037. png_set_palette_to_rgb(pp);
  6038. this->next->set(this->next, that, pp, pi);
  6039. }
  6040. static void
  6041. image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
  6042. image_pixel *that, png_const_structp pp,
  6043. const transform_display *display)
  6044. {
  6045. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6046. image_pixel_convert_PLTE(that);
  6047. this->next->mod(this->next, that, pp, display);
  6048. }
  6049. static int
  6050. image_transform_png_set_palette_to_rgb_add(image_transform *this,
  6051. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6052. {
  6053. UNUSED(bit_depth)
  6054. this->next = *that;
  6055. *that = this;
  6056. return colour_type == PNG_COLOR_TYPE_PALETTE;
  6057. }
  6058. IT(palette_to_rgb);
  6059. #undef PT
  6060. #define PT ITSTRUCT(palette_to_rgb)
  6061. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6062. #ifdef PNG_READ_EXPAND_SUPPORTED
  6063. /* png_set_tRNS_to_alpha */
  6064. static void
  6065. image_transform_png_set_tRNS_to_alpha_set(const image_transform *this,
  6066. transform_display *that, png_structp pp, png_infop pi)
  6067. {
  6068. png_set_tRNS_to_alpha(pp);
  6069. /* If there was a tRNS chunk that would get expanded and add an alpha
  6070. * channel is_transparent must be updated:
  6071. */
  6072. if (that->this.has_tRNS)
  6073. that->this.is_transparent = 1;
  6074. this->next->set(this->next, that, pp, pi);
  6075. }
  6076. static void
  6077. image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this,
  6078. image_pixel *that, png_const_structp pp,
  6079. const transform_display *display)
  6080. {
  6081. #if PNG_LIBPNG_VER < 10700
  6082. /* LIBPNG BUG: this always forces palette images to RGB. */
  6083. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6084. image_pixel_convert_PLTE(that);
  6085. #endif
  6086. /* This effectively does an 'expand' only if there is some transparency to
  6087. * convert to an alpha channel.
  6088. */
  6089. if (that->have_tRNS)
  6090. # if PNG_LIBPNG_VER >= 10700
  6091. if (that->colour_type != PNG_COLOR_TYPE_PALETTE &&
  6092. (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0)
  6093. # endif
  6094. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6095. #if PNG_LIBPNG_VER < 10700
  6096. /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */
  6097. else
  6098. {
  6099. if (that->bit_depth < 8)
  6100. that->bit_depth =8;
  6101. if (that->sample_depth < 8)
  6102. that->sample_depth = 8;
  6103. }
  6104. #endif
  6105. this->next->mod(this->next, that, pp, display);
  6106. }
  6107. static int
  6108. image_transform_png_set_tRNS_to_alpha_add(image_transform *this,
  6109. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6110. {
  6111. UNUSED(bit_depth)
  6112. this->next = *that;
  6113. *that = this;
  6114. /* We don't know yet whether there will be a tRNS chunk, but we know that
  6115. * this transformation should do nothing if there already is an alpha
  6116. * channel. In addition, after the bug fix in 1.7.0, there is no longer
  6117. * any action on a palette image.
  6118. */
  6119. return
  6120. # if PNG_LIBPNG_VER >= 10700
  6121. colour_type != PNG_COLOR_TYPE_PALETTE &&
  6122. # endif
  6123. (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  6124. }
  6125. IT(tRNS_to_alpha);
  6126. #undef PT
  6127. #define PT ITSTRUCT(tRNS_to_alpha)
  6128. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6129. #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
  6130. /* png_set_gray_to_rgb */
  6131. static void
  6132. image_transform_png_set_gray_to_rgb_set(const image_transform *this,
  6133. transform_display *that, png_structp pp, png_infop pi)
  6134. {
  6135. png_set_gray_to_rgb(pp);
  6136. /* NOTE: this doesn't result in tRNS expansion. */
  6137. this->next->set(this->next, that, pp, pi);
  6138. }
  6139. static void
  6140. image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
  6141. image_pixel *that, png_const_structp pp,
  6142. const transform_display *display)
  6143. {
  6144. /* NOTE: we can actually pend the tRNS processing at this point because we
  6145. * can correctly recognize the original pixel value even though we have
  6146. * mapped the one gray channel to the three RGB ones, but in fact libpng
  6147. * doesn't do this, so we don't either.
  6148. */
  6149. if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
  6150. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6151. /* Simply expand the bit depth and alter the colour type as required. */
  6152. if (that->colour_type == PNG_COLOR_TYPE_GRAY)
  6153. {
  6154. /* RGB images have a bit depth at least equal to '8' */
  6155. if (that->bit_depth < 8)
  6156. that->sample_depth = that->bit_depth = 8;
  6157. /* And just changing the colour type works here because the green and blue
  6158. * channels are being maintained in lock-step with the red/gray:
  6159. */
  6160. that->colour_type = PNG_COLOR_TYPE_RGB;
  6161. }
  6162. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  6163. that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
  6164. this->next->mod(this->next, that, pp, display);
  6165. }
  6166. static int
  6167. image_transform_png_set_gray_to_rgb_add(image_transform *this,
  6168. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6169. {
  6170. UNUSED(bit_depth)
  6171. this->next = *that;
  6172. *that = this;
  6173. return (colour_type & PNG_COLOR_MASK_COLOR) == 0;
  6174. }
  6175. IT(gray_to_rgb);
  6176. #undef PT
  6177. #define PT ITSTRUCT(gray_to_rgb)
  6178. #endif /* PNG_READ_GRAY_TO_RGB_SUPPORTED */
  6179. #ifdef PNG_READ_EXPAND_SUPPORTED
  6180. /* png_set_expand */
  6181. static void
  6182. image_transform_png_set_expand_set(const image_transform *this,
  6183. transform_display *that, png_structp pp, png_infop pi)
  6184. {
  6185. png_set_expand(pp);
  6186. if (that->this.has_tRNS)
  6187. that->this.is_transparent = 1;
  6188. this->next->set(this->next, that, pp, pi);
  6189. }
  6190. static void
  6191. image_transform_png_set_expand_mod(const image_transform *this,
  6192. image_pixel *that, png_const_structp pp,
  6193. const transform_display *display)
  6194. {
  6195. /* The general expand case depends on what the colour type is: */
  6196. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6197. image_pixel_convert_PLTE(that);
  6198. else if (that->bit_depth < 8) /* grayscale */
  6199. that->sample_depth = that->bit_depth = 8;
  6200. if (that->have_tRNS)
  6201. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6202. this->next->mod(this->next, that, pp, display);
  6203. }
  6204. static int
  6205. image_transform_png_set_expand_add(image_transform *this,
  6206. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6207. {
  6208. UNUSED(bit_depth)
  6209. this->next = *that;
  6210. *that = this;
  6211. /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit
  6212. * depth is at least 8 already.
  6213. */
  6214. return (colour_type & PNG_COLOR_MASK_ALPHA) == 0;
  6215. }
  6216. IT(expand);
  6217. #undef PT
  6218. #define PT ITSTRUCT(expand)
  6219. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6220. #ifdef PNG_READ_EXPAND_SUPPORTED
  6221. /* png_set_expand_gray_1_2_4_to_8
  6222. * Pre 1.7.0 LIBPNG BUG: this just does an 'expand'
  6223. */
  6224. static void
  6225. image_transform_png_set_expand_gray_1_2_4_to_8_set(
  6226. const image_transform *this, transform_display *that, png_structp pp,
  6227. png_infop pi)
  6228. {
  6229. png_set_expand_gray_1_2_4_to_8(pp);
  6230. /* NOTE: don't expect this to expand tRNS */
  6231. this->next->set(this->next, that, pp, pi);
  6232. }
  6233. static void
  6234. image_transform_png_set_expand_gray_1_2_4_to_8_mod(
  6235. const image_transform *this, image_pixel *that, png_const_structp pp,
  6236. const transform_display *display)
  6237. {
  6238. #if PNG_LIBPNG_VER < 10700
  6239. image_transform_png_set_expand_mod(this, that, pp, display);
  6240. #else
  6241. /* Only expand grayscale of bit depth less than 8: */
  6242. if (that->colour_type == PNG_COLOR_TYPE_GRAY &&
  6243. that->bit_depth < 8)
  6244. that->sample_depth = that->bit_depth = 8;
  6245. this->next->mod(this->next, that, pp, display);
  6246. #endif /* 1.7 or later */
  6247. }
  6248. static int
  6249. image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this,
  6250. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6251. {
  6252. #if PNG_LIBPNG_VER < 10700
  6253. return image_transform_png_set_expand_add(this, that, colour_type,
  6254. bit_depth);
  6255. #else
  6256. UNUSED(bit_depth)
  6257. this->next = *that;
  6258. *that = this;
  6259. /* This should do nothing unless the color type is gray and the bit depth is
  6260. * less than 8:
  6261. */
  6262. return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8;
  6263. #endif /* 1.7 or later */
  6264. }
  6265. IT(expand_gray_1_2_4_to_8);
  6266. #undef PT
  6267. #define PT ITSTRUCT(expand_gray_1_2_4_to_8)
  6268. #endif /* PNG_READ_EXPAND_SUPPORTED */
  6269. #ifdef PNG_READ_EXPAND_16_SUPPORTED
  6270. /* png_set_expand_16 */
  6271. static void
  6272. image_transform_png_set_expand_16_set(const image_transform *this,
  6273. transform_display *that, png_structp pp, png_infop pi)
  6274. {
  6275. png_set_expand_16(pp);
  6276. /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */
  6277. # if PNG_LIBPNG_VER < 10700
  6278. if (that->this.has_tRNS)
  6279. that->this.is_transparent = 1;
  6280. # endif
  6281. this->next->set(this->next, that, pp, pi);
  6282. }
  6283. static void
  6284. image_transform_png_set_expand_16_mod(const image_transform *this,
  6285. image_pixel *that, png_const_structp pp,
  6286. const transform_display *display)
  6287. {
  6288. /* Expect expand_16 to expand everything to 16 bits as a result of also
  6289. * causing 'expand' to happen.
  6290. */
  6291. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6292. image_pixel_convert_PLTE(that);
  6293. if (that->have_tRNS)
  6294. image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
  6295. if (that->bit_depth < 16)
  6296. that->sample_depth = that->bit_depth = 16;
  6297. this->next->mod(this->next, that, pp, display);
  6298. }
  6299. static int
  6300. image_transform_png_set_expand_16_add(image_transform *this,
  6301. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6302. {
  6303. UNUSED(colour_type)
  6304. this->next = *that;
  6305. *that = this;
  6306. /* expand_16 does something unless the bit depth is already 16. */
  6307. return bit_depth < 16;
  6308. }
  6309. IT(expand_16);
  6310. #undef PT
  6311. #define PT ITSTRUCT(expand_16)
  6312. #endif /* PNG_READ_EXPAND_16_SUPPORTED */
  6313. #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */
  6314. /* png_set_scale_16 */
  6315. static void
  6316. image_transform_png_set_scale_16_set(const image_transform *this,
  6317. transform_display *that, png_structp pp, png_infop pi)
  6318. {
  6319. png_set_scale_16(pp);
  6320. # if PNG_LIBPNG_VER < 10700
  6321. /* libpng will limit the gamma table size: */
  6322. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  6323. # endif
  6324. this->next->set(this->next, that, pp, pi);
  6325. }
  6326. static void
  6327. image_transform_png_set_scale_16_mod(const image_transform *this,
  6328. image_pixel *that, png_const_structp pp,
  6329. const transform_display *display)
  6330. {
  6331. if (that->bit_depth == 16)
  6332. {
  6333. that->sample_depth = that->bit_depth = 8;
  6334. if (that->red_sBIT > 8) that->red_sBIT = 8;
  6335. if (that->green_sBIT > 8) that->green_sBIT = 8;
  6336. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  6337. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  6338. }
  6339. this->next->mod(this->next, that, pp, display);
  6340. }
  6341. static int
  6342. image_transform_png_set_scale_16_add(image_transform *this,
  6343. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6344. {
  6345. UNUSED(colour_type)
  6346. this->next = *that;
  6347. *that = this;
  6348. return bit_depth > 8;
  6349. }
  6350. IT(scale_16);
  6351. #undef PT
  6352. #define PT ITSTRUCT(scale_16)
  6353. #endif /* PNG_READ_SCALE_16_TO_8_SUPPORTED (1.5.4 on) */
  6354. #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */
  6355. /* png_set_strip_16 */
  6356. static void
  6357. image_transform_png_set_strip_16_set(const image_transform *this,
  6358. transform_display *that, png_structp pp, png_infop pi)
  6359. {
  6360. png_set_strip_16(pp);
  6361. # if PNG_LIBPNG_VER < 10700
  6362. /* libpng will limit the gamma table size: */
  6363. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  6364. # endif
  6365. this->next->set(this->next, that, pp, pi);
  6366. }
  6367. static void
  6368. image_transform_png_set_strip_16_mod(const image_transform *this,
  6369. image_pixel *that, png_const_structp pp,
  6370. const transform_display *display)
  6371. {
  6372. if (that->bit_depth == 16)
  6373. {
  6374. that->sample_depth = that->bit_depth = 8;
  6375. if (that->red_sBIT > 8) that->red_sBIT = 8;
  6376. if (that->green_sBIT > 8) that->green_sBIT = 8;
  6377. if (that->blue_sBIT > 8) that->blue_sBIT = 8;
  6378. if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
  6379. /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
  6380. * configuration option is set. From 1.5.4 the flag is never set and the
  6381. * 'scale' API (above) must be used.
  6382. */
  6383. # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
  6384. # if PNG_LIBPNG_VER >= 10504
  6385. # error PNG_READ_ACCURATE_SCALE should not be set
  6386. # endif
  6387. /* The strip 16 algorithm drops the low 8 bits rather than calculating
  6388. * 1/257, so we need to adjust the permitted errors appropriately:
  6389. * Notice that this is only relevant prior to the addition of the
  6390. * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
  6391. */
  6392. {
  6393. const double d = (255-128.5)/65535;
  6394. that->rede += d;
  6395. that->greene += d;
  6396. that->bluee += d;
  6397. that->alphae += d;
  6398. }
  6399. # endif
  6400. }
  6401. this->next->mod(this->next, that, pp, display);
  6402. }
  6403. static int
  6404. image_transform_png_set_strip_16_add(image_transform *this,
  6405. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6406. {
  6407. UNUSED(colour_type)
  6408. this->next = *that;
  6409. *that = this;
  6410. return bit_depth > 8;
  6411. }
  6412. IT(strip_16);
  6413. #undef PT
  6414. #define PT ITSTRUCT(strip_16)
  6415. #endif /* PNG_READ_16_TO_8_SUPPORTED */
  6416. #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
  6417. /* png_set_strip_alpha */
  6418. static void
  6419. image_transform_png_set_strip_alpha_set(const image_transform *this,
  6420. transform_display *that, png_structp pp, png_infop pi)
  6421. {
  6422. png_set_strip_alpha(pp);
  6423. this->next->set(this->next, that, pp, pi);
  6424. }
  6425. static void
  6426. image_transform_png_set_strip_alpha_mod(const image_transform *this,
  6427. image_pixel *that, png_const_structp pp,
  6428. const transform_display *display)
  6429. {
  6430. if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  6431. that->colour_type = PNG_COLOR_TYPE_GRAY;
  6432. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  6433. that->colour_type = PNG_COLOR_TYPE_RGB;
  6434. that->have_tRNS = 0;
  6435. that->alphaf = 1;
  6436. this->next->mod(this->next, that, pp, display);
  6437. }
  6438. static int
  6439. image_transform_png_set_strip_alpha_add(image_transform *this,
  6440. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  6441. {
  6442. UNUSED(bit_depth)
  6443. this->next = *that;
  6444. *that = this;
  6445. return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
  6446. }
  6447. IT(strip_alpha);
  6448. #undef PT
  6449. #define PT ITSTRUCT(strip_alpha)
  6450. #endif /* PNG_READ_STRIP_ALPHA_SUPPORTED */
  6451. #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
  6452. /* png_set_rgb_to_gray(png_structp, int err_action, double red, double green)
  6453. * png_set_rgb_to_gray_fixed(png_structp, int err_action, png_fixed_point red,
  6454. * png_fixed_point green)
  6455. * png_get_rgb_to_gray_status
  6456. *
  6457. * The 'default' test here uses values known to be used inside libpng prior to
  6458. * 1.7.0:
  6459. *
  6460. * red: 6968
  6461. * green: 23434
  6462. * blue: 2366
  6463. *
  6464. * These values are being retained for compatibility, along with the somewhat
  6465. * broken truncation calculation in the fast-and-inaccurate code path. Older
  6466. * versions of libpng will fail the accuracy tests below because they use the
  6467. * truncation algorithm everywhere.
  6468. */
  6469. #define data ITDATA(rgb_to_gray)
  6470. static struct
  6471. {
  6472. double gamma; /* File gamma to use in processing */
  6473. /* The following are the parameters for png_set_rgb_to_gray: */
  6474. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6475. double red_to_set;
  6476. double green_to_set;
  6477. # else
  6478. png_fixed_point red_to_set;
  6479. png_fixed_point green_to_set;
  6480. # endif
  6481. /* The actual coefficients: */
  6482. double red_coefficient;
  6483. double green_coefficient;
  6484. double blue_coefficient;
  6485. /* Set if the coeefficients have been overridden. */
  6486. int coefficients_overridden;
  6487. } data;
  6488. #undef image_transform_ini
  6489. #define image_transform_ini image_transform_png_set_rgb_to_gray_ini
  6490. static void
  6491. image_transform_png_set_rgb_to_gray_ini(const image_transform *this,
  6492. transform_display *that)
  6493. {
  6494. png_modifier *pm = that->pm;
  6495. const color_encoding *e = pm->current_encoding;
  6496. UNUSED(this)
  6497. /* Since we check the encoding this flag must be set: */
  6498. pm->test_uses_encoding = 1;
  6499. /* If 'e' is not NULL chromaticity information is present and either a cHRM
  6500. * or an sRGB chunk will be inserted.
  6501. */
  6502. if (e != 0)
  6503. {
  6504. /* Coefficients come from the encoding, but may need to be normalized to a
  6505. * white point Y of 1.0
  6506. */
  6507. const double whiteY = e->red.Y + e->green.Y + e->blue.Y;
  6508. data.red_coefficient = e->red.Y;
  6509. data.green_coefficient = e->green.Y;
  6510. data.blue_coefficient = e->blue.Y;
  6511. if (whiteY != 1)
  6512. {
  6513. data.red_coefficient /= whiteY;
  6514. data.green_coefficient /= whiteY;
  6515. data.blue_coefficient /= whiteY;
  6516. }
  6517. }
  6518. else
  6519. {
  6520. /* The default (built in) coeffcients, as above: */
  6521. # if PNG_LIBPNG_VER < 10700
  6522. data.red_coefficient = 6968 / 32768.;
  6523. data.green_coefficient = 23434 / 32768.;
  6524. data.blue_coefficient = 2366 / 32768.;
  6525. # else
  6526. data.red_coefficient = .2126;
  6527. data.green_coefficient = .7152;
  6528. data.blue_coefficient = .0722;
  6529. # endif
  6530. }
  6531. data.gamma = pm->current_gamma;
  6532. /* If not set then the calculations assume linear encoding (implicitly): */
  6533. if (data.gamma == 0)
  6534. data.gamma = 1;
  6535. /* The arguments to png_set_rgb_to_gray can override the coefficients implied
  6536. * by the color space encoding. If doing exhaustive checks do the override
  6537. * in each case, otherwise do it randomly.
  6538. */
  6539. if (pm->test_exhaustive)
  6540. {
  6541. /* First time in coefficients_overridden is 0, the following sets it to 1,
  6542. * so repeat if it is set. If a test fails this may mean we subsequently
  6543. * skip a non-override test, ignore that.
  6544. */
  6545. data.coefficients_overridden = !data.coefficients_overridden;
  6546. pm->repeat = data.coefficients_overridden != 0;
  6547. }
  6548. else
  6549. data.coefficients_overridden = random_choice();
  6550. if (data.coefficients_overridden)
  6551. {
  6552. /* These values override the color encoding defaults, simply use random
  6553. * numbers.
  6554. */
  6555. png_uint_32 ru;
  6556. double total;
  6557. ru = random_u32();
  6558. data.green_coefficient = total = (ru & 0xffff) / 65535.;
  6559. ru >>= 16;
  6560. data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.;
  6561. total += data.red_coefficient;
  6562. data.blue_coefficient = 1 - total;
  6563. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6564. data.red_to_set = data.red_coefficient;
  6565. data.green_to_set = data.green_coefficient;
  6566. # else
  6567. data.red_to_set = fix(data.red_coefficient);
  6568. data.green_to_set = fix(data.green_coefficient);
  6569. # endif
  6570. /* The following just changes the error messages: */
  6571. pm->encoding_ignored = 1;
  6572. }
  6573. else
  6574. {
  6575. data.red_to_set = -1;
  6576. data.green_to_set = -1;
  6577. }
  6578. /* Adjust the error limit in the png_modifier because of the larger errors
  6579. * produced in the digitization during the gamma handling.
  6580. */
  6581. if (data.gamma != 1) /* Use gamma tables */
  6582. {
  6583. if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations)
  6584. {
  6585. /* The computations have the form:
  6586. *
  6587. * r * rc + g * gc + b * bc
  6588. *
  6589. * Each component of which is +/-1/65535 from the gamma_to_1 table
  6590. * lookup, resulting in a base error of +/-6. The gamma_from_1
  6591. * conversion adds another +/-2 in the 16-bit case and
  6592. * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case.
  6593. */
  6594. # if PNG_LIBPNG_VER < 10700
  6595. if (that->this.bit_depth < 16)
  6596. that->max_gamma_8 = PNG_MAX_GAMMA_8;
  6597. # endif
  6598. that->pm->limit += pow(
  6599. (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ?
  6600. 8. :
  6601. 6. + (1<<(15-that->max_gamma_8))
  6602. )/65535, data.gamma);
  6603. }
  6604. else
  6605. {
  6606. /* Rounding to 8 bits in the linear space causes massive errors which
  6607. * will trigger the error check in transform_range_check. Fix that
  6608. * here by taking the gamma encoding into account.
  6609. *
  6610. * When DIGITIZE is set because a pre-1.7 version of libpng is being
  6611. * tested allow a bigger slack.
  6612. *
  6613. * NOTE: this number only affects the internal limit check in pngvalid,
  6614. * it has no effect on the limits applied to the libpng values.
  6615. */
  6616. #if DIGITIZE
  6617. that->pm->limit += pow( 2.0/255, data.gamma);
  6618. #else
  6619. that->pm->limit += pow( 1.0/255, data.gamma);
  6620. #endif
  6621. }
  6622. }
  6623. else
  6624. {
  6625. /* With no gamma correction a large error comes from the truncation of the
  6626. * calculation in the 8 bit case, allow for that here.
  6627. */
  6628. if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations)
  6629. that->pm->limit += 4E-3;
  6630. }
  6631. }
  6632. static void
  6633. image_transform_png_set_rgb_to_gray_set(const image_transform *this,
  6634. transform_display *that, png_structp pp, png_infop pi)
  6635. {
  6636. int error_action = 1; /* no error, no defines in png.h */
  6637. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6638. png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set);
  6639. # else
  6640. png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set,
  6641. data.green_to_set);
  6642. # endif
  6643. # ifdef PNG_READ_cHRM_SUPPORTED
  6644. if (that->pm->current_encoding != 0)
  6645. {
  6646. /* We have an encoding so a cHRM chunk may have been set; if so then
  6647. * check that the libpng APIs give the correct (X,Y,Z) values within
  6648. * some margin of error for the round trip through the chromaticity
  6649. * form.
  6650. */
  6651. # ifdef PNG_FLOATING_POINT_SUPPORTED
  6652. # define API_function png_get_cHRM_XYZ
  6653. # define API_form "FP"
  6654. # define API_type double
  6655. # define API_cvt(x) (x)
  6656. # else
  6657. # define API_function png_get_cHRM_XYZ_fixed
  6658. # define API_form "fixed"
  6659. # define API_type png_fixed_point
  6660. # define API_cvt(x) ((double)(x)/PNG_FP_1)
  6661. # endif
  6662. API_type rX, gX, bX;
  6663. API_type rY, gY, bY;
  6664. API_type rZ, gZ, bZ;
  6665. if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ)
  6666. & PNG_INFO_cHRM) != 0)
  6667. {
  6668. double maxe;
  6669. const char *el;
  6670. color_encoding e, o;
  6671. /* Expect libpng to return a normalized result, but the original
  6672. * color space encoding may not be normalized.
  6673. */
  6674. modifier_current_encoding(that->pm, &o);
  6675. normalize_color_encoding(&o);
  6676. /* Sanity check the pngvalid code - the coefficients should match
  6677. * the normalized Y values of the encoding unless they were
  6678. * overridden.
  6679. */
  6680. if (data.red_to_set == -1 && data.green_to_set == -1 &&
  6681. (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON ||
  6682. fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON ||
  6683. fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON))
  6684. png_error(pp, "internal pngvalid cHRM coefficient error");
  6685. /* Generate a colour space encoding. */
  6686. e.gamma = o.gamma; /* not used */
  6687. e.red.X = API_cvt(rX);
  6688. e.red.Y = API_cvt(rY);
  6689. e.red.Z = API_cvt(rZ);
  6690. e.green.X = API_cvt(gX);
  6691. e.green.Y = API_cvt(gY);
  6692. e.green.Z = API_cvt(gZ);
  6693. e.blue.X = API_cvt(bX);
  6694. e.blue.Y = API_cvt(bY);
  6695. e.blue.Z = API_cvt(bZ);
  6696. /* This should match the original one from the png_modifier, within
  6697. * the range permitted by the libpng fixed point representation.
  6698. */
  6699. maxe = 0;
  6700. el = "-"; /* Set to element name with error */
  6701. # define CHECK(col,x)\
  6702. {\
  6703. double err = fabs(o.col.x - e.col.x);\
  6704. if (err > maxe)\
  6705. {\
  6706. maxe = err;\
  6707. el = #col "(" #x ")";\
  6708. }\
  6709. }
  6710. CHECK(red,X)
  6711. CHECK(red,Y)
  6712. CHECK(red,Z)
  6713. CHECK(green,X)
  6714. CHECK(green,Y)
  6715. CHECK(green,Z)
  6716. CHECK(blue,X)
  6717. CHECK(blue,Y)
  6718. CHECK(blue,Z)
  6719. /* Here in both fixed and floating cases to check the values read
  6720. * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so
  6721. * we can't expect better than +/-.5E-5 on the result, allow 1E-5.
  6722. */
  6723. if (maxe >= 1E-5)
  6724. {
  6725. size_t pos = 0;
  6726. char buffer[256];
  6727. pos = safecat(buffer, sizeof buffer, pos, API_form);
  6728. pos = safecat(buffer, sizeof buffer, pos, " cHRM ");
  6729. pos = safecat(buffer, sizeof buffer, pos, el);
  6730. pos = safecat(buffer, sizeof buffer, pos, " error: ");
  6731. pos = safecatd(buffer, sizeof buffer, pos, maxe, 7);
  6732. pos = safecat(buffer, sizeof buffer, pos, " ");
  6733. /* Print the color space without the gamma value: */
  6734. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0);
  6735. pos = safecat(buffer, sizeof buffer, pos, " -> ");
  6736. pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0);
  6737. png_error(pp, buffer);
  6738. }
  6739. }
  6740. }
  6741. # endif /* READ_cHRM */
  6742. this->next->set(this->next, that, pp, pi);
  6743. }
  6744. static void
  6745. image_transform_png_set_rgb_to_gray_mod(const image_transform *this,
  6746. image_pixel *that, png_const_structp pp,
  6747. const transform_display *display)
  6748. {
  6749. if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0)
  6750. {
  6751. double gray, err;
  6752. # if PNG_LIBPNG_VER < 10700
  6753. if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
  6754. image_pixel_convert_PLTE(that);
  6755. # endif
  6756. /* Image now has RGB channels... */
  6757. # if DIGITIZE
  6758. {
  6759. png_modifier *pm = display->pm;
  6760. unsigned int sample_depth = that->sample_depth;
  6761. unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 :
  6762. sample_depth);
  6763. unsigned int gamma_depth =
  6764. (sample_depth == 16 ?
  6765. display->max_gamma_8 :
  6766. (pm->assume_16_bit_calculations ?
  6767. display->max_gamma_8 :
  6768. sample_depth));
  6769. int isgray;
  6770. double r, g, b;
  6771. double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi;
  6772. /* Do this using interval arithmetic, otherwise it is too difficult to
  6773. * handle the errors correctly.
  6774. *
  6775. * To handle the gamma correction work out the upper and lower bounds
  6776. * of the digitized value. Assume rounding here - normally the values
  6777. * will be identical after this operation if there is only one
  6778. * transform, feel free to delete the png_error checks on this below in
  6779. * the future (this is just me trying to ensure it works!)
  6780. *
  6781. * Interval arithmetic is exact, but to implement it it must be
  6782. * possible to control the floating point implementation rounding mode.
  6783. * This cannot be done in ANSI-C, so instead I reduce the 'lo' values
  6784. * by DBL_EPSILON and increase the 'hi' values by the same.
  6785. */
  6786. # define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON))
  6787. # define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON))
  6788. r = rlo = rhi = that->redf;
  6789. rlo -= that->rede;
  6790. rlo = DD(rlo, calc_depth, 1/*round*/);
  6791. rhi += that->rede;
  6792. rhi = DU(rhi, calc_depth, 1/*round*/);
  6793. g = glo = ghi = that->greenf;
  6794. glo -= that->greene;
  6795. glo = DD(glo, calc_depth, 1/*round*/);
  6796. ghi += that->greene;
  6797. ghi = DU(ghi, calc_depth, 1/*round*/);
  6798. b = blo = bhi = that->bluef;
  6799. blo -= that->bluee;
  6800. blo = DD(blo, calc_depth, 1/*round*/);
  6801. bhi += that->bluee;
  6802. bhi = DU(bhi, calc_depth, 1/*round*/);
  6803. isgray = r==g && g==b;
  6804. if (data.gamma != 1)
  6805. {
  6806. const double power = 1/data.gamma;
  6807. const double abse = .5/(sample_depth == 16 ? 65535 : 255);
  6808. /* If a gamma calculation is done it is done using lookup tables of
  6809. * precision gamma_depth, so the already digitized value above may
  6810. * need to be further digitized here.
  6811. */
  6812. if (gamma_depth != calc_depth)
  6813. {
  6814. rlo = DD(rlo, gamma_depth, 0/*truncate*/);
  6815. rhi = DU(rhi, gamma_depth, 0/*truncate*/);
  6816. glo = DD(glo, gamma_depth, 0/*truncate*/);
  6817. ghi = DU(ghi, gamma_depth, 0/*truncate*/);
  6818. blo = DD(blo, gamma_depth, 0/*truncate*/);
  6819. bhi = DU(bhi, gamma_depth, 0/*truncate*/);
  6820. }
  6821. /* 'abse' is the error in the gamma table calculation itself. */
  6822. r = pow(r, power);
  6823. rlo = DD(pow(rlo, power)-abse, calc_depth, 1);
  6824. rhi = DU(pow(rhi, power)+abse, calc_depth, 1);
  6825. g = pow(g, power);
  6826. glo = DD(pow(glo, power)-abse, calc_depth, 1);
  6827. ghi = DU(pow(ghi, power)+abse, calc_depth, 1);
  6828. b = pow(b, power);
  6829. blo = DD(pow(blo, power)-abse, calc_depth, 1);
  6830. bhi = DU(pow(bhi, power)+abse, calc_depth, 1);
  6831. }
  6832. /* Now calculate the actual gray values. Although the error in the
  6833. * coefficients depends on whether they were specified on the command
  6834. * line (in which case truncation to 15 bits happened) or not (rounding
  6835. * was used) the maximum error in an individual coefficient is always
  6836. * 2/32768, because even in the rounding case the requirement that
  6837. * coefficients add up to 32768 can cause a larger rounding error.
  6838. *
  6839. * The only time when rounding doesn't occur in 1.5.5 and later is when
  6840. * the non-gamma code path is used for less than 16 bit data.
  6841. */
  6842. gray = r * data.red_coefficient + g * data.green_coefficient +
  6843. b * data.blue_coefficient;
  6844. {
  6845. int do_round = data.gamma != 1 || calc_depth == 16;
  6846. const double ce = 2. / 32768;
  6847. graylo = DD(rlo * (data.red_coefficient-ce) +
  6848. glo * (data.green_coefficient-ce) +
  6849. blo * (data.blue_coefficient-ce), calc_depth, do_round);
  6850. if (graylo > gray) /* always accept the right answer */
  6851. graylo = gray;
  6852. grayhi = DU(rhi * (data.red_coefficient+ce) +
  6853. ghi * (data.green_coefficient+ce) +
  6854. bhi * (data.blue_coefficient+ce), calc_depth, do_round);
  6855. if (grayhi < gray)
  6856. grayhi = gray;
  6857. }
  6858. /* And invert the gamma. */
  6859. if (data.gamma != 1)
  6860. {
  6861. const double power = data.gamma;
  6862. /* And this happens yet again, shifting the values once more. */
  6863. if (gamma_depth != sample_depth)
  6864. {
  6865. rlo = DD(rlo, gamma_depth, 0/*truncate*/);
  6866. rhi = DU(rhi, gamma_depth, 0/*truncate*/);
  6867. glo = DD(glo, gamma_depth, 0/*truncate*/);
  6868. ghi = DU(ghi, gamma_depth, 0/*truncate*/);
  6869. blo = DD(blo, gamma_depth, 0/*truncate*/);
  6870. bhi = DU(bhi, gamma_depth, 0/*truncate*/);
  6871. }
  6872. gray = pow(gray, power);
  6873. graylo = DD(pow(graylo, power), sample_depth, 1);
  6874. grayhi = DU(pow(grayhi, power), sample_depth, 1);
  6875. }
  6876. # undef DD
  6877. # undef DU
  6878. /* Now the error can be calculated.
  6879. *
  6880. * If r==g==b because there is no overall gamma correction libpng
  6881. * currently preserves the original value.
  6882. */
  6883. if (isgray)
  6884. err = (that->rede + that->greene + that->bluee)/3;
  6885. else
  6886. {
  6887. err = fabs(grayhi-gray);
  6888. if (fabs(gray - graylo) > err)
  6889. err = fabs(graylo-gray);
  6890. #if !RELEASE_BUILD
  6891. /* Check that this worked: */
  6892. if (err > pm->limit)
  6893. {
  6894. size_t pos = 0;
  6895. char buffer[128];
  6896. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  6897. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  6898. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  6899. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  6900. png_warning(pp, buffer);
  6901. pm->limit = err;
  6902. }
  6903. #endif /* !RELEASE_BUILD */
  6904. }
  6905. }
  6906. # else /* !DIGITIZE */
  6907. {
  6908. double r = that->redf;
  6909. double re = that->rede;
  6910. double g = that->greenf;
  6911. double ge = that->greene;
  6912. double b = that->bluef;
  6913. double be = that->bluee;
  6914. # if PNG_LIBPNG_VER < 10700
  6915. /* The true gray case involves no math in earlier versions (not
  6916. * true, there was some if gamma correction was happening too.)
  6917. */
  6918. if (r == g && r == b)
  6919. {
  6920. gray = r;
  6921. err = re;
  6922. if (err < ge) err = ge;
  6923. if (err < be) err = be;
  6924. }
  6925. else
  6926. # endif /* before 1.7 */
  6927. if (data.gamma == 1)
  6928. {
  6929. /* There is no need to do the conversions to and from linear space,
  6930. * so the calculation should be a lot more accurate. There is a
  6931. * built in error in the coefficients because they only have 15 bits
  6932. * and are adjusted to make sure they add up to 32768. This
  6933. * involves a integer calculation with truncation of the form:
  6934. *
  6935. * ((int)(coefficient * 100000) * 32768)/100000
  6936. *
  6937. * This is done to the red and green coefficients (the ones
  6938. * provided to the API) then blue is calculated from them so the
  6939. * result adds up to 32768. In the worst case this can result in
  6940. * a -1 error in red and green and a +2 error in blue. Consequently
  6941. * the worst case in the calculation below is 2/32768 error.
  6942. *
  6943. * TODO: consider fixing this in libpng by rounding the calculation
  6944. * limiting the error to 1/32768.
  6945. *
  6946. * Handling this by adding 2/32768 here avoids needing to increase
  6947. * the global error limits to take this into account.)
  6948. */
  6949. gray = r * data.red_coefficient + g * data.green_coefficient +
  6950. b * data.blue_coefficient;
  6951. err = re * data.red_coefficient + ge * data.green_coefficient +
  6952. be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON;
  6953. }
  6954. else
  6955. {
  6956. /* The calculation happens in linear space, and this produces much
  6957. * wider errors in the encoded space. These are handled here by
  6958. * factoring the errors in to the calculation. There are two table
  6959. * lookups in the calculation and each introduces a quantization
  6960. * error defined by the table size.
  6961. */
  6962. png_modifier *pm = display->pm;
  6963. double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255);
  6964. double out_qe = (that->sample_depth > 8 ? .5/65535 :
  6965. (pm->assume_16_bit_calculations ? .5/(1<<display->max_gamma_8) :
  6966. .5/255));
  6967. double rhi, ghi, bhi, grayhi;
  6968. double g1 = 1/data.gamma;
  6969. rhi = r + re + in_qe; if (rhi > 1) rhi = 1;
  6970. r -= re + in_qe; if (r < 0) r = 0;
  6971. ghi = g + ge + in_qe; if (ghi > 1) ghi = 1;
  6972. g -= ge + in_qe; if (g < 0) g = 0;
  6973. bhi = b + be + in_qe; if (bhi > 1) bhi = 1;
  6974. b -= be + in_qe; if (b < 0) b = 0;
  6975. r = pow(r, g1)*(1-DBL_EPSILON); rhi = pow(rhi, g1)*(1+DBL_EPSILON);
  6976. g = pow(g, g1)*(1-DBL_EPSILON); ghi = pow(ghi, g1)*(1+DBL_EPSILON);
  6977. b = pow(b, g1)*(1-DBL_EPSILON); bhi = pow(bhi, g1)*(1+DBL_EPSILON);
  6978. /* Work out the lower and upper bounds for the gray value in the
  6979. * encoded space, then work out an average and error. Remove the
  6980. * previously added input quantization error at this point.
  6981. */
  6982. gray = r * data.red_coefficient + g * data.green_coefficient +
  6983. b * data.blue_coefficient - 2./32768 - out_qe;
  6984. if (gray <= 0)
  6985. gray = 0;
  6986. else
  6987. {
  6988. gray *= (1 - 6 * DBL_EPSILON);
  6989. gray = pow(gray, data.gamma) * (1-DBL_EPSILON);
  6990. }
  6991. grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient +
  6992. bhi * data.blue_coefficient + 2./32768 + out_qe;
  6993. grayhi *= (1 + 6 * DBL_EPSILON);
  6994. if (grayhi >= 1)
  6995. grayhi = 1;
  6996. else
  6997. grayhi = pow(grayhi, data.gamma) * (1+DBL_EPSILON);
  6998. err = (grayhi - gray) / 2;
  6999. gray = (grayhi + gray) / 2;
  7000. if (err <= in_qe)
  7001. err = gray * DBL_EPSILON;
  7002. else
  7003. err -= in_qe;
  7004. #if !RELEASE_BUILD
  7005. /* Validate that the error is within limits (this has caused
  7006. * problems before, it's much easier to detect them here.)
  7007. */
  7008. if (err > pm->limit)
  7009. {
  7010. size_t pos = 0;
  7011. char buffer[128];
  7012. pos = safecat(buffer, sizeof buffer, pos, "rgb_to_gray error ");
  7013. pos = safecatd(buffer, sizeof buffer, pos, err, 6);
  7014. pos = safecat(buffer, sizeof buffer, pos, " exceeds limit ");
  7015. pos = safecatd(buffer, sizeof buffer, pos, pm->limit, 6);
  7016. png_warning(pp, buffer);
  7017. pm->limit = err;
  7018. }
  7019. #endif /* !RELEASE_BUILD */
  7020. }
  7021. }
  7022. # endif /* !DIGITIZE */
  7023. that->bluef = that->greenf = that->redf = gray;
  7024. that->bluee = that->greene = that->rede = err;
  7025. /* The sBIT is the minimum of the three colour channel sBITs. */
  7026. if (that->red_sBIT > that->green_sBIT)
  7027. that->red_sBIT = that->green_sBIT;
  7028. if (that->red_sBIT > that->blue_sBIT)
  7029. that->red_sBIT = that->blue_sBIT;
  7030. that->blue_sBIT = that->green_sBIT = that->red_sBIT;
  7031. /* And remove the colour bit in the type: */
  7032. if (that->colour_type == PNG_COLOR_TYPE_RGB)
  7033. that->colour_type = PNG_COLOR_TYPE_GRAY;
  7034. else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  7035. that->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  7036. }
  7037. this->next->mod(this->next, that, pp, display);
  7038. }
  7039. static int
  7040. image_transform_png_set_rgb_to_gray_add(image_transform *this,
  7041. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7042. {
  7043. UNUSED(bit_depth)
  7044. this->next = *that;
  7045. *that = this;
  7046. return (colour_type & PNG_COLOR_MASK_COLOR) != 0;
  7047. }
  7048. #undef data
  7049. IT(rgb_to_gray);
  7050. #undef PT
  7051. #define PT ITSTRUCT(rgb_to_gray)
  7052. #undef image_transform_ini
  7053. #define image_transform_ini image_transform_default_ini
  7054. #endif /* PNG_READ_RGB_TO_GRAY_SUPPORTED */
  7055. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  7056. /* png_set_background(png_structp, png_const_color_16p background_color,
  7057. * int background_gamma_code, int need_expand, double background_gamma)
  7058. * png_set_background_fixed(png_structp, png_const_color_16p background_color,
  7059. * int background_gamma_code, int need_expand,
  7060. * png_fixed_point background_gamma)
  7061. *
  7062. * This ignores the gamma (at present.)
  7063. */
  7064. #define data ITDATA(background)
  7065. static image_pixel data;
  7066. static void
  7067. image_transform_png_set_background_set(const image_transform *this,
  7068. transform_display *that, png_structp pp, png_infop pi)
  7069. {
  7070. png_byte colour_type, bit_depth;
  7071. png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
  7072. int expand;
  7073. png_color_16 back;
  7074. /* We need a background colour, because we don't know exactly what transforms
  7075. * have been set we have to supply the colour in the original file format and
  7076. * so we need to know what that is! The background colour is stored in the
  7077. * transform_display.
  7078. */
  7079. R8(random_bytes);
  7080. /* Read the random value, for colour type 3 the background colour is actually
  7081. * expressed as a 24bit rgb, not an index.
  7082. */
  7083. colour_type = that->this.colour_type;
  7084. if (colour_type == 3)
  7085. {
  7086. colour_type = PNG_COLOR_TYPE_RGB;
  7087. bit_depth = 8;
  7088. expand = 0; /* passing in an RGB not a pixel index */
  7089. }
  7090. else
  7091. {
  7092. if (that->this.has_tRNS)
  7093. that->this.is_transparent = 1;
  7094. bit_depth = that->this.bit_depth;
  7095. expand = 1;
  7096. }
  7097. image_pixel_init(&data, random_bytes, colour_type,
  7098. bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
  7099. /* Extract the background colour from this image_pixel, but make sure the
  7100. * unused fields of 'back' are garbage.
  7101. */
  7102. R8(back);
  7103. if (colour_type & PNG_COLOR_MASK_COLOR)
  7104. {
  7105. back.red = (png_uint_16)data.red;
  7106. back.green = (png_uint_16)data.green;
  7107. back.blue = (png_uint_16)data.blue;
  7108. }
  7109. else
  7110. back.gray = (png_uint_16)data.red;
  7111. #ifdef PNG_FLOATING_POINT_SUPPORTED
  7112. png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  7113. #else
  7114. png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
  7115. #endif
  7116. this->next->set(this->next, that, pp, pi);
  7117. }
  7118. static void
  7119. image_transform_png_set_background_mod(const image_transform *this,
  7120. image_pixel *that, png_const_structp pp,
  7121. const transform_display *display)
  7122. {
  7123. /* Check for tRNS first: */
  7124. if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE)
  7125. image_pixel_add_alpha(that, &display->this, 1/*for background*/);
  7126. /* This is only necessary if the alpha value is less than 1. */
  7127. if (that->alphaf < 1)
  7128. {
  7129. /* Now we do the background calculation without any gamma correction. */
  7130. if (that->alphaf <= 0)
  7131. {
  7132. that->redf = data.redf;
  7133. that->greenf = data.greenf;
  7134. that->bluef = data.bluef;
  7135. that->rede = data.rede;
  7136. that->greene = data.greene;
  7137. that->bluee = data.bluee;
  7138. that->red_sBIT= data.red_sBIT;
  7139. that->green_sBIT= data.green_sBIT;
  7140. that->blue_sBIT= data.blue_sBIT;
  7141. }
  7142. else /* 0 < alpha < 1 */
  7143. {
  7144. double alf = 1 - that->alphaf;
  7145. that->redf = that->redf * that->alphaf + data.redf * alf;
  7146. that->rede = that->rede * that->alphaf + data.rede * alf +
  7147. DBL_EPSILON;
  7148. that->greenf = that->greenf * that->alphaf + data.greenf * alf;
  7149. that->greene = that->greene * that->alphaf + data.greene * alf +
  7150. DBL_EPSILON;
  7151. that->bluef = that->bluef * that->alphaf + data.bluef * alf;
  7152. that->bluee = that->bluee * that->alphaf + data.bluee * alf +
  7153. DBL_EPSILON;
  7154. }
  7155. /* Remove the alpha type and set the alpha (not in that order.) */
  7156. that->alphaf = 1;
  7157. that->alphae = 0;
  7158. }
  7159. if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
  7160. that->colour_type = PNG_COLOR_TYPE_RGB;
  7161. else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  7162. that->colour_type = PNG_COLOR_TYPE_GRAY;
  7163. /* PNG_COLOR_TYPE_PALETTE is not changed */
  7164. this->next->mod(this->next, that, pp, display);
  7165. }
  7166. #define image_transform_png_set_background_add image_transform_default_add
  7167. #undef data
  7168. IT(background);
  7169. #undef PT
  7170. #define PT ITSTRUCT(background)
  7171. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  7172. /* png_set_quantize(png_structp, png_colorp palette, int num_palette,
  7173. * int maximum_colors, png_const_uint_16p histogram, int full_quantize)
  7174. *
  7175. * Very difficult to validate this!
  7176. */
  7177. /*NOTE: TBD NYI */
  7178. /* The data layout transforms are handled by swapping our own channel data,
  7179. * necessarily these need to happen at the end of the transform list because the
  7180. * semantic of the channels changes after these are executed. Some of these,
  7181. * like set_shift and set_packing, can't be done at present because they change
  7182. * the layout of the data at the sub-sample level so sample() won't get the
  7183. * right answer.
  7184. */
  7185. /* png_set_invert_alpha */
  7186. #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
  7187. /* Invert the alpha channel
  7188. *
  7189. * png_set_invert_alpha(png_structrp png_ptr)
  7190. */
  7191. static void
  7192. image_transform_png_set_invert_alpha_set(const image_transform *this,
  7193. transform_display *that, png_structp pp, png_infop pi)
  7194. {
  7195. png_set_invert_alpha(pp);
  7196. this->next->set(this->next, that, pp, pi);
  7197. }
  7198. static void
  7199. image_transform_png_set_invert_alpha_mod(const image_transform *this,
  7200. image_pixel *that, png_const_structp pp,
  7201. const transform_display *display)
  7202. {
  7203. if (that->colour_type & 4)
  7204. that->alpha_inverted = 1;
  7205. this->next->mod(this->next, that, pp, display);
  7206. }
  7207. static int
  7208. image_transform_png_set_invert_alpha_add(image_transform *this,
  7209. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7210. {
  7211. UNUSED(bit_depth)
  7212. this->next = *that;
  7213. *that = this;
  7214. /* Only has an effect on pixels with alpha: */
  7215. return (colour_type & 4) != 0;
  7216. }
  7217. IT(invert_alpha);
  7218. #undef PT
  7219. #define PT ITSTRUCT(invert_alpha)
  7220. #endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
  7221. /* png_set_bgr */
  7222. #ifdef PNG_READ_BGR_SUPPORTED
  7223. /* Swap R,G,B channels to order B,G,R.
  7224. *
  7225. * png_set_bgr(png_structrp png_ptr)
  7226. *
  7227. * This only has an effect on RGB and RGBA pixels.
  7228. */
  7229. static void
  7230. image_transform_png_set_bgr_set(const image_transform *this,
  7231. transform_display *that, png_structp pp, png_infop pi)
  7232. {
  7233. png_set_bgr(pp);
  7234. this->next->set(this->next, that, pp, pi);
  7235. }
  7236. static void
  7237. image_transform_png_set_bgr_mod(const image_transform *this,
  7238. image_pixel *that, png_const_structp pp,
  7239. const transform_display *display)
  7240. {
  7241. if (that->colour_type == PNG_COLOR_TYPE_RGB ||
  7242. that->colour_type == PNG_COLOR_TYPE_RGBA)
  7243. that->swap_rgb = 1;
  7244. this->next->mod(this->next, that, pp, display);
  7245. }
  7246. static int
  7247. image_transform_png_set_bgr_add(image_transform *this,
  7248. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7249. {
  7250. UNUSED(bit_depth)
  7251. this->next = *that;
  7252. *that = this;
  7253. return colour_type == PNG_COLOR_TYPE_RGB ||
  7254. colour_type == PNG_COLOR_TYPE_RGBA;
  7255. }
  7256. IT(bgr);
  7257. #undef PT
  7258. #define PT ITSTRUCT(bgr)
  7259. #endif /* PNG_READ_BGR_SUPPORTED */
  7260. /* png_set_swap_alpha */
  7261. #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
  7262. /* Put the alpha channel first.
  7263. *
  7264. * png_set_swap_alpha(png_structrp png_ptr)
  7265. *
  7266. * This only has an effect on GA and RGBA pixels.
  7267. */
  7268. static void
  7269. image_transform_png_set_swap_alpha_set(const image_transform *this,
  7270. transform_display *that, png_structp pp, png_infop pi)
  7271. {
  7272. png_set_swap_alpha(pp);
  7273. this->next->set(this->next, that, pp, pi);
  7274. }
  7275. static void
  7276. image_transform_png_set_swap_alpha_mod(const image_transform *this,
  7277. image_pixel *that, png_const_structp pp,
  7278. const transform_display *display)
  7279. {
  7280. if (that->colour_type == PNG_COLOR_TYPE_GA ||
  7281. that->colour_type == PNG_COLOR_TYPE_RGBA)
  7282. that->alpha_first = 1;
  7283. this->next->mod(this->next, that, pp, display);
  7284. }
  7285. static int
  7286. image_transform_png_set_swap_alpha_add(image_transform *this,
  7287. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7288. {
  7289. UNUSED(bit_depth)
  7290. this->next = *that;
  7291. *that = this;
  7292. return colour_type == PNG_COLOR_TYPE_GA ||
  7293. colour_type == PNG_COLOR_TYPE_RGBA;
  7294. }
  7295. IT(swap_alpha);
  7296. #undef PT
  7297. #define PT ITSTRUCT(swap_alpha)
  7298. #endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
  7299. /* png_set_swap */
  7300. #ifdef PNG_READ_SWAP_SUPPORTED
  7301. /* Byte swap 16-bit components.
  7302. *
  7303. * png_set_swap(png_structrp png_ptr)
  7304. */
  7305. static void
  7306. image_transform_png_set_swap_set(const image_transform *this,
  7307. transform_display *that, png_structp pp, png_infop pi)
  7308. {
  7309. png_set_swap(pp);
  7310. this->next->set(this->next, that, pp, pi);
  7311. }
  7312. static void
  7313. image_transform_png_set_swap_mod(const image_transform *this,
  7314. image_pixel *that, png_const_structp pp,
  7315. const transform_display *display)
  7316. {
  7317. if (that->bit_depth == 16)
  7318. that->swap16 = 1;
  7319. this->next->mod(this->next, that, pp, display);
  7320. }
  7321. static int
  7322. image_transform_png_set_swap_add(image_transform *this,
  7323. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7324. {
  7325. UNUSED(colour_type)
  7326. this->next = *that;
  7327. *that = this;
  7328. return bit_depth == 16;
  7329. }
  7330. IT(swap);
  7331. #undef PT
  7332. #define PT ITSTRUCT(swap)
  7333. #endif /* PNG_READ_SWAP_SUPPORTED */
  7334. #ifdef PNG_READ_FILLER_SUPPORTED
  7335. /* Add a filler byte to 8-bit Gray or 24-bit RGB images.
  7336. *
  7337. * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
  7338. *
  7339. * Flags:
  7340. *
  7341. * PNG_FILLER_BEFORE
  7342. * PNG_FILLER_AFTER
  7343. */
  7344. #define data ITDATA(filler)
  7345. static struct
  7346. {
  7347. png_uint_32 filler;
  7348. int flags;
  7349. } data;
  7350. static void
  7351. image_transform_png_set_filler_set(const image_transform *this,
  7352. transform_display *that, png_structp pp, png_infop pi)
  7353. {
  7354. /* Need a random choice for 'before' and 'after' as well as for the
  7355. * filler. The 'filler' value has all 32 bits set, but only bit_depth
  7356. * will be used. At this point we don't know bit_depth.
  7357. */
  7358. data.filler = random_u32();
  7359. data.flags = random_choice();
  7360. png_set_filler(pp, data.filler, data.flags);
  7361. /* The standard display handling stuff also needs to know that
  7362. * there is a filler, so set that here.
  7363. */
  7364. that->this.filler = 1;
  7365. this->next->set(this->next, that, pp, pi);
  7366. }
  7367. static void
  7368. image_transform_png_set_filler_mod(const image_transform *this,
  7369. image_pixel *that, png_const_structp pp,
  7370. const transform_display *display)
  7371. {
  7372. if (that->bit_depth >= 8 &&
  7373. (that->colour_type == PNG_COLOR_TYPE_RGB ||
  7374. that->colour_type == PNG_COLOR_TYPE_GRAY))
  7375. {
  7376. unsigned int max = (1U << that->bit_depth)-1;
  7377. that->alpha = data.filler & max;
  7378. that->alphaf = ((double)that->alpha) / max;
  7379. that->alphae = 0;
  7380. /* The filler has been stored in the alpha channel, we must record
  7381. * that this has been done for the checking later on, the color
  7382. * type is faked to have an alpha channel, but libpng won't report
  7383. * this; the app has to know the extra channel is there and this
  7384. * was recording in standard_display::filler above.
  7385. */
  7386. that->colour_type |= 4; /* alpha added */
  7387. that->alpha_first = data.flags == PNG_FILLER_BEFORE;
  7388. }
  7389. this->next->mod(this->next, that, pp, display);
  7390. }
  7391. static int
  7392. image_transform_png_set_filler_add(image_transform *this,
  7393. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7394. {
  7395. this->next = *that;
  7396. *that = this;
  7397. return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
  7398. colour_type == PNG_COLOR_TYPE_GRAY);
  7399. }
  7400. #undef data
  7401. IT(filler);
  7402. #undef PT
  7403. #define PT ITSTRUCT(filler)
  7404. /* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
  7405. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  7406. #define data ITDATA(add_alpha)
  7407. static struct
  7408. {
  7409. png_uint_32 filler;
  7410. int flags;
  7411. } data;
  7412. static void
  7413. image_transform_png_set_add_alpha_set(const image_transform *this,
  7414. transform_display *that, png_structp pp, png_infop pi)
  7415. {
  7416. /* Need a random choice for 'before' and 'after' as well as for the
  7417. * filler. The 'filler' value has all 32 bits set, but only bit_depth
  7418. * will be used. At this point we don't know bit_depth.
  7419. */
  7420. data.filler = random_u32();
  7421. data.flags = random_choice();
  7422. png_set_add_alpha(pp, data.filler, data.flags);
  7423. this->next->set(this->next, that, pp, pi);
  7424. }
  7425. static void
  7426. image_transform_png_set_add_alpha_mod(const image_transform *this,
  7427. image_pixel *that, png_const_structp pp,
  7428. const transform_display *display)
  7429. {
  7430. if (that->bit_depth >= 8 &&
  7431. (that->colour_type == PNG_COLOR_TYPE_RGB ||
  7432. that->colour_type == PNG_COLOR_TYPE_GRAY))
  7433. {
  7434. unsigned int max = (1U << that->bit_depth)-1;
  7435. that->alpha = data.filler & max;
  7436. that->alphaf = ((double)that->alpha) / max;
  7437. that->alphae = 0;
  7438. that->colour_type |= 4; /* alpha added */
  7439. that->alpha_first = data.flags == PNG_FILLER_BEFORE;
  7440. }
  7441. this->next->mod(this->next, that, pp, display);
  7442. }
  7443. static int
  7444. image_transform_png_set_add_alpha_add(image_transform *this,
  7445. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7446. {
  7447. this->next = *that;
  7448. *that = this;
  7449. return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
  7450. colour_type == PNG_COLOR_TYPE_GRAY);
  7451. }
  7452. #undef data
  7453. IT(add_alpha);
  7454. #undef PT
  7455. #define PT ITSTRUCT(add_alpha)
  7456. #endif /* PNG_READ_FILLER_SUPPORTED */
  7457. /* png_set_packing */
  7458. #ifdef PNG_READ_PACK_SUPPORTED
  7459. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
  7460. *
  7461. * png_set_packing(png_structrp png_ptr)
  7462. *
  7463. * This should only affect grayscale and palette images with less than 8 bits
  7464. * per pixel.
  7465. */
  7466. static void
  7467. image_transform_png_set_packing_set(const image_transform *this,
  7468. transform_display *that, png_structp pp, png_infop pi)
  7469. {
  7470. png_set_packing(pp);
  7471. that->unpacked = 1;
  7472. this->next->set(this->next, that, pp, pi);
  7473. }
  7474. static void
  7475. image_transform_png_set_packing_mod(const image_transform *this,
  7476. image_pixel *that, png_const_structp pp,
  7477. const transform_display *display)
  7478. {
  7479. /* The general expand case depends on what the colour type is,
  7480. * low bit-depth pixel values are unpacked into bytes without
  7481. * scaling, so sample_depth is not changed.
  7482. */
  7483. if (that->bit_depth < 8) /* grayscale or palette */
  7484. that->bit_depth = 8;
  7485. this->next->mod(this->next, that, pp, display);
  7486. }
  7487. static int
  7488. image_transform_png_set_packing_add(image_transform *this,
  7489. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7490. {
  7491. UNUSED(colour_type)
  7492. this->next = *that;
  7493. *that = this;
  7494. /* Nothing should happen unless the bit depth is less than 8: */
  7495. return bit_depth < 8;
  7496. }
  7497. IT(packing);
  7498. #undef PT
  7499. #define PT ITSTRUCT(packing)
  7500. #endif /* PNG_READ_PACK_SUPPORTED */
  7501. /* png_set_packswap */
  7502. #ifdef PNG_READ_PACKSWAP_SUPPORTED
  7503. /* Swap pixels packed into bytes; reverses the order on screen so that
  7504. * the high order bits correspond to the rightmost pixels.
  7505. *
  7506. * png_set_packswap(png_structrp png_ptr)
  7507. */
  7508. static void
  7509. image_transform_png_set_packswap_set(const image_transform *this,
  7510. transform_display *that, png_structp pp, png_infop pi)
  7511. {
  7512. png_set_packswap(pp);
  7513. that->this.littleendian = 1;
  7514. this->next->set(this->next, that, pp, pi);
  7515. }
  7516. static void
  7517. image_transform_png_set_packswap_mod(const image_transform *this,
  7518. image_pixel *that, png_const_structp pp,
  7519. const transform_display *display)
  7520. {
  7521. if (that->bit_depth < 8)
  7522. that->littleendian = 1;
  7523. this->next->mod(this->next, that, pp, display);
  7524. }
  7525. static int
  7526. image_transform_png_set_packswap_add(image_transform *this,
  7527. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7528. {
  7529. UNUSED(colour_type)
  7530. this->next = *that;
  7531. *that = this;
  7532. return bit_depth < 8;
  7533. }
  7534. IT(packswap);
  7535. #undef PT
  7536. #define PT ITSTRUCT(packswap)
  7537. #endif /* PNG_READ_PACKSWAP_SUPPORTED */
  7538. /* png_set_invert_mono */
  7539. #ifdef PNG_READ_INVERT_MONO_SUPPORTED
  7540. /* Invert the gray channel
  7541. *
  7542. * png_set_invert_mono(png_structrp png_ptr)
  7543. */
  7544. static void
  7545. image_transform_png_set_invert_mono_set(const image_transform *this,
  7546. transform_display *that, png_structp pp, png_infop pi)
  7547. {
  7548. png_set_invert_mono(pp);
  7549. this->next->set(this->next, that, pp, pi);
  7550. }
  7551. static void
  7552. image_transform_png_set_invert_mono_mod(const image_transform *this,
  7553. image_pixel *that, png_const_structp pp,
  7554. const transform_display *display)
  7555. {
  7556. if (that->colour_type & 4)
  7557. that->mono_inverted = 1;
  7558. this->next->mod(this->next, that, pp, display);
  7559. }
  7560. static int
  7561. image_transform_png_set_invert_mono_add(image_transform *this,
  7562. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7563. {
  7564. UNUSED(bit_depth)
  7565. this->next = *that;
  7566. *that = this;
  7567. /* Only has an effect on pixels with no colour: */
  7568. return (colour_type & 2) == 0;
  7569. }
  7570. IT(invert_mono);
  7571. #undef PT
  7572. #define PT ITSTRUCT(invert_mono)
  7573. #endif /* PNG_READ_INVERT_MONO_SUPPORTED */
  7574. #ifdef PNG_READ_SHIFT_SUPPORTED
  7575. /* png_set_shift(png_structp, png_const_color_8p true_bits)
  7576. *
  7577. * The output pixels will be shifted by the given true_bits
  7578. * values.
  7579. */
  7580. #define data ITDATA(shift)
  7581. static png_color_8 data;
  7582. static void
  7583. image_transform_png_set_shift_set(const image_transform *this,
  7584. transform_display *that, png_structp pp, png_infop pi)
  7585. {
  7586. /* Get a random set of shifts. The shifts need to do something
  7587. * to test the transform, so they are limited to the bit depth
  7588. * of the input image. Notice that in the following the 'gray'
  7589. * field is randomized independently. This acts as a check that
  7590. * libpng does use the correct field.
  7591. */
  7592. unsigned int depth = that->this.bit_depth;
  7593. data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7594. data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7595. data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7596. data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7597. data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
  7598. png_set_shift(pp, &data);
  7599. this->next->set(this->next, that, pp, pi);
  7600. }
  7601. static void
  7602. image_transform_png_set_shift_mod(const image_transform *this,
  7603. image_pixel *that, png_const_structp pp,
  7604. const transform_display *display)
  7605. {
  7606. /* Copy the correct values into the sBIT fields, libpng does not do
  7607. * anything to palette data:
  7608. */
  7609. if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
  7610. {
  7611. that->sig_bits = 1;
  7612. /* The sBIT fields are reset to the values previously sent to
  7613. * png_set_shift according to the colour type.
  7614. * does.
  7615. */
  7616. if (that->colour_type & 2) /* RGB channels */
  7617. {
  7618. that->red_sBIT = data.red;
  7619. that->green_sBIT = data.green;
  7620. that->blue_sBIT = data.blue;
  7621. }
  7622. else /* One grey channel */
  7623. that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
  7624. that->alpha_sBIT = data.alpha;
  7625. }
  7626. this->next->mod(this->next, that, pp, display);
  7627. }
  7628. static int
  7629. image_transform_png_set_shift_add(image_transform *this,
  7630. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7631. {
  7632. UNUSED(bit_depth)
  7633. this->next = *that;
  7634. *that = this;
  7635. return colour_type != PNG_COLOR_TYPE_PALETTE;
  7636. }
  7637. IT(shift);
  7638. #undef PT
  7639. #define PT ITSTRUCT(shift)
  7640. #endif /* PNG_READ_SHIFT_SUPPORTED */
  7641. #ifdef THIS_IS_THE_PROFORMA
  7642. static void
  7643. image_transform_png_set_@_set(const image_transform *this,
  7644. transform_display *that, png_structp pp, png_infop pi)
  7645. {
  7646. png_set_@(pp);
  7647. this->next->set(this->next, that, pp, pi);
  7648. }
  7649. static void
  7650. image_transform_png_set_@_mod(const image_transform *this,
  7651. image_pixel *that, png_const_structp pp,
  7652. const transform_display *display)
  7653. {
  7654. this->next->mod(this->next, that, pp, display);
  7655. }
  7656. static int
  7657. image_transform_png_set_@_add(image_transform *this,
  7658. const image_transform **that, png_byte colour_type, png_byte bit_depth)
  7659. {
  7660. this->next = *that;
  7661. *that = this;
  7662. return 1;
  7663. }
  7664. IT(@);
  7665. #endif
  7666. /* This may just be 'end' if all the transforms are disabled! */
  7667. static image_transform *const image_transform_first = &PT;
  7668. static void
  7669. transform_enable(const char *name)
  7670. {
  7671. /* Everything starts out enabled, so if we see an 'enable' disabled
  7672. * everything else the first time round.
  7673. */
  7674. static int all_disabled = 0;
  7675. int found_it = 0;
  7676. image_transform *list = image_transform_first;
  7677. while (list != &image_transform_end)
  7678. {
  7679. if (strcmp(list->name, name) == 0)
  7680. {
  7681. list->enable = 1;
  7682. found_it = 1;
  7683. }
  7684. else if (!all_disabled)
  7685. list->enable = 0;
  7686. list = list->list;
  7687. }
  7688. all_disabled = 1;
  7689. if (!found_it)
  7690. {
  7691. fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
  7692. name);
  7693. exit(99);
  7694. }
  7695. }
  7696. static void
  7697. transform_disable(const char *name)
  7698. {
  7699. image_transform *list = image_transform_first;
  7700. while (list != &image_transform_end)
  7701. {
  7702. if (strcmp(list->name, name) == 0)
  7703. {
  7704. list->enable = 0;
  7705. return;
  7706. }
  7707. list = list->list;
  7708. }
  7709. fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
  7710. name);
  7711. exit(99);
  7712. }
  7713. static void
  7714. image_transform_reset_count(void)
  7715. {
  7716. image_transform *next = image_transform_first;
  7717. int count = 0;
  7718. while (next != &image_transform_end)
  7719. {
  7720. next->local_use = 0;
  7721. next->next = 0;
  7722. next = next->list;
  7723. ++count;
  7724. }
  7725. /* This can only happen if we every have more than 32 transforms (excluding
  7726. * the end) in the list.
  7727. */
  7728. if (count > 32) abort();
  7729. }
  7730. static int
  7731. image_transform_test_counter(png_uint_32 counter, unsigned int max)
  7732. {
  7733. /* Test the list to see if there is any point contining, given a current
  7734. * counter and a 'max' value.
  7735. */
  7736. image_transform *next = image_transform_first;
  7737. while (next != &image_transform_end)
  7738. {
  7739. /* For max 0 or 1 continue until the counter overflows: */
  7740. counter >>= 1;
  7741. /* Continue if any entry hasn't reacked the max. */
  7742. if (max > 1 && next->local_use < max)
  7743. return 1;
  7744. next = next->list;
  7745. }
  7746. return max <= 1 && counter == 0;
  7747. }
  7748. static png_uint_32
  7749. image_transform_add(const image_transform **this, unsigned int max,
  7750. png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
  7751. png_byte colour_type, png_byte bit_depth)
  7752. {
  7753. for (;;) /* until we manage to add something */
  7754. {
  7755. png_uint_32 mask;
  7756. image_transform *list;
  7757. /* Find the next counter value, if the counter is zero this is the start
  7758. * of the list. This routine always returns the current counter (not the
  7759. * next) so it returns 0 at the end and expects 0 at the beginning.
  7760. */
  7761. if (counter == 0) /* first time */
  7762. {
  7763. image_transform_reset_count();
  7764. if (max <= 1)
  7765. counter = 1;
  7766. else
  7767. counter = random_32();
  7768. }
  7769. else /* advance the counter */
  7770. {
  7771. switch (max)
  7772. {
  7773. case 0: ++counter; break;
  7774. case 1: counter <<= 1; break;
  7775. default: counter = random_32(); break;
  7776. }
  7777. }
  7778. /* Now add all these items, if possible */
  7779. *this = &image_transform_end;
  7780. list = image_transform_first;
  7781. mask = 1;
  7782. /* Go through the whole list adding anything that the counter selects: */
  7783. while (list != &image_transform_end)
  7784. {
  7785. if ((counter & mask) != 0 && list->enable &&
  7786. (max == 0 || list->local_use < max))
  7787. {
  7788. /* Candidate to add: */
  7789. if (list->add(list, this, colour_type, bit_depth) || max == 0)
  7790. {
  7791. /* Added, so add to the name too. */
  7792. *pos = safecat(name, sizeof_name, *pos, " +");
  7793. *pos = safecat(name, sizeof_name, *pos, list->name);
  7794. }
  7795. else
  7796. {
  7797. /* Not useful and max>0, so remove it from *this: */
  7798. *this = list->next;
  7799. list->next = 0;
  7800. /* And, since we know it isn't useful, stop it being added again
  7801. * in this run:
  7802. */
  7803. list->local_use = max;
  7804. }
  7805. }
  7806. mask <<= 1;
  7807. list = list->list;
  7808. }
  7809. /* Now if anything was added we have something to do. */
  7810. if (*this != &image_transform_end)
  7811. return counter;
  7812. /* Nothing added, but was there anything in there to add? */
  7813. if (!image_transform_test_counter(counter, max))
  7814. return 0;
  7815. }
  7816. }
  7817. static void
  7818. perform_transform_test(png_modifier *pm)
  7819. {
  7820. png_byte colour_type = 0;
  7821. png_byte bit_depth = 0;
  7822. unsigned int palette_number = 0;
  7823. while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
  7824. pm->test_tRNS))
  7825. {
  7826. png_uint_32 counter = 0;
  7827. size_t base_pos;
  7828. char name[64];
  7829. base_pos = safecat(name, sizeof name, 0, "transform:");
  7830. for (;;)
  7831. {
  7832. size_t pos = base_pos;
  7833. const image_transform *list = 0;
  7834. /* 'max' is currently hardwired to '1'; this should be settable on the
  7835. * command line.
  7836. */
  7837. counter = image_transform_add(&list, 1/*max*/, counter,
  7838. name, sizeof name, &pos, colour_type, bit_depth);
  7839. if (counter == 0)
  7840. break;
  7841. /* The command line can change this to checking interlaced images. */
  7842. do
  7843. {
  7844. pm->repeat = 0;
  7845. transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
  7846. pm->interlace_type, 0, 0, 0), list, name);
  7847. if (fail(pm))
  7848. return;
  7849. }
  7850. while (pm->repeat);
  7851. }
  7852. }
  7853. }
  7854. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  7855. /********************************* GAMMA TESTS ********************************/
  7856. #ifdef PNG_READ_GAMMA_SUPPORTED
  7857. /* Reader callbacks and implementations, where they differ from the standard
  7858. * ones.
  7859. */
  7860. typedef struct gamma_display
  7861. {
  7862. standard_display this;
  7863. /* Parameters */
  7864. png_modifier* pm;
  7865. double file_gamma;
  7866. double screen_gamma;
  7867. double background_gamma;
  7868. png_byte sbit;
  7869. int threshold_test;
  7870. int use_input_precision;
  7871. int scale16;
  7872. int expand16;
  7873. int do_background;
  7874. png_color_16 background_color;
  7875. /* Local variables */
  7876. double maxerrout;
  7877. double maxerrpc;
  7878. double maxerrabs;
  7879. } gamma_display;
  7880. #define ALPHA_MODE_OFFSET 4
  7881. static void
  7882. gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
  7883. double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
  7884. int use_input_precision, int scale16, int expand16,
  7885. int do_background, const png_color_16 *pointer_to_the_background_color,
  7886. double background_gamma)
  7887. {
  7888. /* Standard fields */
  7889. standard_display_init(&dp->this, &pm->this, id, do_read_interlace,
  7890. pm->use_update_info);
  7891. /* Parameter fields */
  7892. dp->pm = pm;
  7893. dp->file_gamma = file_gamma;
  7894. dp->screen_gamma = screen_gamma;
  7895. dp->background_gamma = background_gamma;
  7896. dp->sbit = sbit;
  7897. dp->threshold_test = threshold_test;
  7898. dp->use_input_precision = use_input_precision;
  7899. dp->scale16 = scale16;
  7900. dp->expand16 = expand16;
  7901. dp->do_background = do_background;
  7902. if (do_background && pointer_to_the_background_color != 0)
  7903. dp->background_color = *pointer_to_the_background_color;
  7904. else
  7905. memset(&dp->background_color, 0, sizeof dp->background_color);
  7906. /* Local variable fields */
  7907. dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
  7908. }
  7909. static void
  7910. gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
  7911. {
  7912. /* Reuse the standard stuff as appropriate. */
  7913. standard_info_part1(&dp->this, pp, pi);
  7914. /* If requested strip 16 to 8 bits - this is handled automagically below
  7915. * because the output bit depth is read from the library. Note that there
  7916. * are interactions with sBIT but, internally, libpng makes sbit at most
  7917. * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following.
  7918. */
  7919. if (dp->scale16)
  7920. # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
  7921. png_set_scale_16(pp);
  7922. # else
  7923. /* The following works both in 1.5.4 and earlier versions: */
  7924. # ifdef PNG_READ_16_TO_8_SUPPORTED
  7925. png_set_strip_16(pp);
  7926. # else
  7927. png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
  7928. # endif
  7929. # endif
  7930. if (dp->expand16)
  7931. # ifdef PNG_READ_EXPAND_16_SUPPORTED
  7932. png_set_expand_16(pp);
  7933. # else
  7934. png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
  7935. # endif
  7936. if (dp->do_background >= ALPHA_MODE_OFFSET)
  7937. {
  7938. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  7939. {
  7940. /* This tests the alpha mode handling, if supported. */
  7941. int mode = dp->do_background - ALPHA_MODE_OFFSET;
  7942. /* The gamma value is the output gamma, and is in the standard,
  7943. * non-inverted, representation. It provides a default for the PNG file
  7944. * gamma, but since the file has a gAMA chunk this does not matter.
  7945. */
  7946. const double sg = dp->screen_gamma;
  7947. # ifndef PNG_FLOATING_POINT_SUPPORTED
  7948. png_fixed_point g = fix(sg);
  7949. # endif
  7950. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7951. png_set_alpha_mode(pp, mode, sg);
  7952. # else
  7953. png_set_alpha_mode_fixed(pp, mode, g);
  7954. # endif
  7955. /* However, for the standard Porter-Duff algorithm the output defaults
  7956. * to be linear, so if the test requires non-linear output it must be
  7957. * corrected here.
  7958. */
  7959. if (mode == PNG_ALPHA_STANDARD && sg != 1)
  7960. {
  7961. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7962. png_set_gamma(pp, sg, dp->file_gamma);
  7963. # else
  7964. png_fixed_point f = fix(dp->file_gamma);
  7965. png_set_gamma_fixed(pp, g, f);
  7966. # endif
  7967. }
  7968. }
  7969. # else
  7970. png_error(pp, "alpha mode handling not supported");
  7971. # endif
  7972. }
  7973. else
  7974. {
  7975. /* Set up gamma processing. */
  7976. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7977. png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
  7978. # else
  7979. {
  7980. png_fixed_point s = fix(dp->screen_gamma);
  7981. png_fixed_point f = fix(dp->file_gamma);
  7982. png_set_gamma_fixed(pp, s, f);
  7983. }
  7984. # endif
  7985. if (dp->do_background)
  7986. {
  7987. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  7988. /* NOTE: this assumes the caller provided the correct background gamma!
  7989. */
  7990. const double bg = dp->background_gamma;
  7991. # ifndef PNG_FLOATING_POINT_SUPPORTED
  7992. png_fixed_point g = fix(bg);
  7993. # endif
  7994. # ifdef PNG_FLOATING_POINT_SUPPORTED
  7995. png_set_background(pp, &dp->background_color, dp->do_background,
  7996. 0/*need_expand*/, bg);
  7997. # else
  7998. png_set_background_fixed(pp, &dp->background_color,
  7999. dp->do_background, 0/*need_expand*/, g);
  8000. # endif
  8001. # else
  8002. png_error(pp, "png_set_background not supported");
  8003. # endif
  8004. }
  8005. }
  8006. {
  8007. int i = dp->this.use_update_info;
  8008. /* Always do one call, even if use_update_info is 0. */
  8009. do
  8010. png_read_update_info(pp, pi);
  8011. while (--i > 0);
  8012. }
  8013. /* Now we may get a different cbRow: */
  8014. standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
  8015. }
  8016. static void PNGCBAPI
  8017. gamma_info(png_structp pp, png_infop pi)
  8018. {
  8019. gamma_info_imp(voidcast(gamma_display*, png_get_progressive_ptr(pp)), pp,
  8020. pi);
  8021. }
  8022. /* Validate a single component value - the routine gets the input and output
  8023. * sample values as unscaled PNG component values along with a cache of all the
  8024. * information required to validate the values.
  8025. */
  8026. typedef struct validate_info
  8027. {
  8028. png_const_structp pp;
  8029. gamma_display *dp;
  8030. png_byte sbit;
  8031. int use_input_precision;
  8032. int do_background;
  8033. int scale16;
  8034. unsigned int sbit_max;
  8035. unsigned int isbit_shift;
  8036. unsigned int outmax;
  8037. double gamma_correction; /* Overall correction required. */
  8038. double file_inverse; /* Inverse of file gamma. */
  8039. double screen_gamma;
  8040. double screen_inverse; /* Inverse of screen gamma. */
  8041. double background_red; /* Linear background value, red or gray. */
  8042. double background_green;
  8043. double background_blue;
  8044. double maxabs;
  8045. double maxpc;
  8046. double maxcalc;
  8047. double maxout;
  8048. double maxout_total; /* Total including quantization error */
  8049. double outlog;
  8050. int outquant;
  8051. }
  8052. validate_info;
  8053. static void
  8054. init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
  8055. int in_depth, int out_depth)
  8056. {
  8057. unsigned int outmax = (1U<<out_depth)-1;
  8058. vi->pp = pp;
  8059. vi->dp = dp;
  8060. if (dp->sbit > 0 && dp->sbit < in_depth)
  8061. {
  8062. vi->sbit = dp->sbit;
  8063. vi->isbit_shift = in_depth - dp->sbit;
  8064. }
  8065. else
  8066. {
  8067. vi->sbit = (png_byte)in_depth;
  8068. vi->isbit_shift = 0;
  8069. }
  8070. vi->sbit_max = (1U << vi->sbit)-1;
  8071. /* This mimics the libpng threshold test, '0' is used to prevent gamma
  8072. * correction in the validation test.
  8073. */
  8074. vi->screen_gamma = dp->screen_gamma;
  8075. if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
  8076. vi->screen_gamma = vi->screen_inverse = 0;
  8077. else
  8078. vi->screen_inverse = 1/vi->screen_gamma;
  8079. vi->use_input_precision = dp->use_input_precision;
  8080. vi->outmax = outmax;
  8081. vi->maxabs = abserr(dp->pm, in_depth, out_depth);
  8082. vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
  8083. vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
  8084. vi->maxout = outerr(dp->pm, in_depth, out_depth);
  8085. vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
  8086. vi->maxout_total = vi->maxout + vi->outquant * .5;
  8087. vi->outlog = outlog(dp->pm, in_depth, out_depth);
  8088. if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
  8089. (dp->this.colour_type == 3 && dp->this.is_transparent) ||
  8090. ((dp->this.colour_type == 0 || dp->this.colour_type == 2) &&
  8091. dp->this.has_tRNS))
  8092. {
  8093. vi->do_background = dp->do_background;
  8094. if (vi->do_background != 0)
  8095. {
  8096. const double bg_inverse = 1/dp->background_gamma;
  8097. double r, g, b;
  8098. /* Caller must at least put the gray value into the red channel */
  8099. r = dp->background_color.red; r /= outmax;
  8100. g = dp->background_color.green; g /= outmax;
  8101. b = dp->background_color.blue; b /= outmax;
  8102. # if 0
  8103. /* libpng doesn't do this optimization, if we do pngvalid will fail.
  8104. */
  8105. if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
  8106. # endif
  8107. {
  8108. r = pow(r, bg_inverse);
  8109. g = pow(g, bg_inverse);
  8110. b = pow(b, bg_inverse);
  8111. }
  8112. vi->background_red = r;
  8113. vi->background_green = g;
  8114. vi->background_blue = b;
  8115. }
  8116. }
  8117. else /* Do not expect any background processing */
  8118. vi->do_background = 0;
  8119. if (vi->do_background == 0)
  8120. vi->background_red = vi->background_green = vi->background_blue = 0;
  8121. vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
  8122. if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
  8123. vi->gamma_correction = 0;
  8124. vi->file_inverse = 1/dp->file_gamma;
  8125. if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
  8126. vi->file_inverse = 0;
  8127. vi->scale16 = dp->scale16;
  8128. }
  8129. /* This function handles composition of a single non-alpha component. The
  8130. * argument is the input sample value, in the range 0..1, and the alpha value.
  8131. * The result is the composed, linear, input sample. If alpha is less than zero
  8132. * this is the alpha component and the function should not be called!
  8133. */
  8134. static double
  8135. gamma_component_compose(int do_background, double input_sample, double alpha,
  8136. double background, int *compose)
  8137. {
  8138. switch (do_background)
  8139. {
  8140. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  8141. case PNG_BACKGROUND_GAMMA_SCREEN:
  8142. case PNG_BACKGROUND_GAMMA_FILE:
  8143. case PNG_BACKGROUND_GAMMA_UNIQUE:
  8144. /* Standard PNG background processing. */
  8145. if (alpha < 1)
  8146. {
  8147. if (alpha > 0)
  8148. {
  8149. input_sample = input_sample * alpha + background * (1-alpha);
  8150. if (compose != NULL)
  8151. *compose = 1;
  8152. }
  8153. else
  8154. input_sample = background;
  8155. }
  8156. break;
  8157. #endif
  8158. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8159. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  8160. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  8161. /* The components are premultiplied in either case and the output is
  8162. * gamma encoded (to get standard Porter-Duff we expect the output
  8163. * gamma to be set to 1.0!)
  8164. */
  8165. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  8166. /* The optimization is that the partial-alpha entries are linear
  8167. * while the opaque pixels are gamma encoded, but this only affects the
  8168. * output encoding.
  8169. */
  8170. if (alpha < 1)
  8171. {
  8172. if (alpha > 0)
  8173. {
  8174. input_sample *= alpha;
  8175. if (compose != NULL)
  8176. *compose = 1;
  8177. }
  8178. else
  8179. input_sample = 0;
  8180. }
  8181. break;
  8182. #endif
  8183. default:
  8184. /* Standard cases where no compositing is done (so the component
  8185. * value is already correct.)
  8186. */
  8187. UNUSED(alpha)
  8188. UNUSED(background)
  8189. UNUSED(compose)
  8190. break;
  8191. }
  8192. return input_sample;
  8193. }
  8194. /* This API returns the encoded *input* component, in the range 0..1 */
  8195. static double
  8196. gamma_component_validate(const char *name, const validate_info *vi,
  8197. unsigned int id, unsigned int od,
  8198. const double alpha /* <0 for the alpha channel itself */,
  8199. const double background /* component background value */)
  8200. {
  8201. unsigned int isbit = id >> vi->isbit_shift;
  8202. unsigned int sbit_max = vi->sbit_max;
  8203. unsigned int outmax = vi->outmax;
  8204. int do_background = vi->do_background;
  8205. double i;
  8206. /* First check on the 'perfect' result obtained from the digitized input
  8207. * value, id, and compare this against the actual digitized result, 'od'.
  8208. * 'i' is the input result in the range 0..1:
  8209. */
  8210. i = isbit; i /= sbit_max;
  8211. /* Check for the fast route: if we don't do any background composition or if
  8212. * this is the alpha channel ('alpha' < 0) or if the pixel is opaque then
  8213. * just use the gamma_correction field to correct to the final output gamma.
  8214. */
  8215. if (alpha == 1 /* opaque pixel component */ || !do_background
  8216. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8217. || do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_PNG
  8218. #endif
  8219. || (alpha < 0 /* alpha channel */
  8220. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8221. && do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN
  8222. #endif
  8223. ))
  8224. {
  8225. /* Then get the gamma corrected version of 'i' and compare to 'od', any
  8226. * error less than .5 is insignificant - just quantization of the output
  8227. * value to the nearest digital value (nevertheless the error is still
  8228. * recorded - it's interesting ;-)
  8229. */
  8230. double encoded_sample = i;
  8231. double encoded_error;
  8232. /* alpha less than 0 indicates the alpha channel, which is always linear
  8233. */
  8234. if (alpha >= 0 && vi->gamma_correction > 0)
  8235. encoded_sample = pow(encoded_sample, vi->gamma_correction);
  8236. encoded_sample *= outmax;
  8237. encoded_error = fabs(od-encoded_sample);
  8238. if (encoded_error > vi->dp->maxerrout)
  8239. vi->dp->maxerrout = encoded_error;
  8240. if (encoded_error < vi->maxout_total && encoded_error < vi->outlog)
  8241. return i;
  8242. }
  8243. /* The slow route - attempt to do linear calculations. */
  8244. /* There may be an error, or background processing is required, so calculate
  8245. * the actual sample values - unencoded light intensity values. Note that in
  8246. * practice these are not completely unencoded because they include a
  8247. * 'viewing correction' to decrease or (normally) increase the perceptual
  8248. * contrast of the image. There's nothing we can do about this - we don't
  8249. * know what it is - so assume the unencoded value is perceptually linear.
  8250. */
  8251. {
  8252. double input_sample = i; /* In range 0..1 */
  8253. double output, error, encoded_sample, encoded_error;
  8254. double es_lo, es_hi;
  8255. int compose = 0; /* Set to one if composition done */
  8256. int output_is_encoded; /* Set if encoded to screen gamma */
  8257. int log_max_error = 1; /* Check maximum error values */
  8258. png_const_charp pass = 0; /* Reason test passes (or 0 for fail) */
  8259. /* Convert to linear light (with the above caveat.) The alpha channel is
  8260. * already linear.
  8261. */
  8262. if (alpha >= 0)
  8263. {
  8264. int tcompose;
  8265. if (vi->file_inverse > 0)
  8266. input_sample = pow(input_sample, vi->file_inverse);
  8267. /* Handle the compose processing: */
  8268. tcompose = 0;
  8269. input_sample = gamma_component_compose(do_background, input_sample,
  8270. alpha, background, &tcompose);
  8271. if (tcompose)
  8272. compose = 1;
  8273. }
  8274. /* And similarly for the output value, but we need to check the background
  8275. * handling to linearize it correctly.
  8276. */
  8277. output = od;
  8278. output /= outmax;
  8279. output_is_encoded = vi->screen_gamma > 0;
  8280. if (alpha < 0) /* The alpha channel */
  8281. {
  8282. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8283. if (do_background != ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN)
  8284. #endif
  8285. {
  8286. /* In all other cases the output alpha channel is linear already,
  8287. * don't log errors here, they are much larger in linear data.
  8288. */
  8289. output_is_encoded = 0;
  8290. log_max_error = 0;
  8291. }
  8292. }
  8293. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8294. else /* A component */
  8295. {
  8296. if (do_background == ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED &&
  8297. alpha < 1) /* the optimized case - linear output */
  8298. {
  8299. if (alpha > 0) log_max_error = 0;
  8300. output_is_encoded = 0;
  8301. }
  8302. }
  8303. #endif
  8304. if (output_is_encoded)
  8305. output = pow(output, vi->screen_gamma);
  8306. /* Calculate (or recalculate) the encoded_sample value and repeat the
  8307. * check above (unnecessary if we took the fast route, but harmless.)
  8308. */
  8309. encoded_sample = input_sample;
  8310. if (output_is_encoded)
  8311. encoded_sample = pow(encoded_sample, vi->screen_inverse);
  8312. encoded_sample *= outmax;
  8313. encoded_error = fabs(od-encoded_sample);
  8314. /* Don't log errors in the alpha channel, or the 'optimized' case,
  8315. * neither are significant to the overall perception.
  8316. */
  8317. if (log_max_error && encoded_error > vi->dp->maxerrout)
  8318. vi->dp->maxerrout = encoded_error;
  8319. if (encoded_error < vi->maxout_total)
  8320. {
  8321. if (encoded_error < vi->outlog)
  8322. return i;
  8323. /* Test passed but error is bigger than the log limit, record why the
  8324. * test passed:
  8325. */
  8326. pass = "less than maxout:\n";
  8327. }
  8328. /* i: the original input value in the range 0..1
  8329. *
  8330. * pngvalid calculations:
  8331. * input_sample: linear result; i linearized and composed, range 0..1
  8332. * encoded_sample: encoded result; input_sample scaled to output bit depth
  8333. *
  8334. * libpng calculations:
  8335. * output: linear result; od scaled to 0..1 and linearized
  8336. * od: encoded result from libpng
  8337. */
  8338. /* Now we have the numbers for real errors, both absolute values as as a
  8339. * percentage of the correct value (output):
  8340. */
  8341. error = fabs(input_sample-output);
  8342. if (log_max_error && error > vi->dp->maxerrabs)
  8343. vi->dp->maxerrabs = error;
  8344. /* The following is an attempt to ignore the tendency of quantization to
  8345. * dominate the percentage errors for lower result values:
  8346. */
  8347. if (log_max_error && input_sample > .5)
  8348. {
  8349. double percentage_error = error/input_sample;
  8350. if (percentage_error > vi->dp->maxerrpc)
  8351. vi->dp->maxerrpc = percentage_error;
  8352. }
  8353. /* Now calculate the digitization limits for 'encoded_sample' using the
  8354. * 'max' values. Note that maxout is in the encoded space but maxpc and
  8355. * maxabs are in linear light space.
  8356. *
  8357. * First find the maximum error in linear light space, range 0..1:
  8358. */
  8359. {
  8360. double tmp = input_sample * vi->maxpc;
  8361. if (tmp < vi->maxabs) tmp = vi->maxabs;
  8362. /* If 'compose' is true the composition was done in linear space using
  8363. * integer arithmetic. This introduces an extra error of +/- 0.5 (at
  8364. * least) in the integer space used. 'maxcalc' records this, taking
  8365. * into account the possibility that even for 16 bit output 8 bit space
  8366. * may have been used.
  8367. */
  8368. if (compose && tmp < vi->maxcalc) tmp = vi->maxcalc;
  8369. /* The 'maxout' value refers to the encoded result, to compare with
  8370. * this encode input_sample adjusted by the maximum error (tmp) above.
  8371. */
  8372. es_lo = encoded_sample - vi->maxout;
  8373. if (es_lo > 0 && input_sample-tmp > 0)
  8374. {
  8375. double low_value = input_sample-tmp;
  8376. if (output_is_encoded)
  8377. low_value = pow(low_value, vi->screen_inverse);
  8378. low_value *= outmax;
  8379. if (low_value < es_lo) es_lo = low_value;
  8380. /* Quantize this appropriately: */
  8381. es_lo = ceil(es_lo / vi->outquant - .5) * vi->outquant;
  8382. }
  8383. else
  8384. es_lo = 0;
  8385. es_hi = encoded_sample + vi->maxout;
  8386. if (es_hi < outmax && input_sample+tmp < 1)
  8387. {
  8388. double high_value = input_sample+tmp;
  8389. if (output_is_encoded)
  8390. high_value = pow(high_value, vi->screen_inverse);
  8391. high_value *= outmax;
  8392. if (high_value > es_hi) es_hi = high_value;
  8393. es_hi = floor(es_hi / vi->outquant + .5) * vi->outquant;
  8394. }
  8395. else
  8396. es_hi = outmax;
  8397. }
  8398. /* The primary test is that the final encoded value returned by the
  8399. * library should be between the two limits (inclusive) that were
  8400. * calculated above.
  8401. */
  8402. if (od >= es_lo && od <= es_hi)
  8403. {
  8404. /* The value passes, but we may need to log the information anyway. */
  8405. if (encoded_error < vi->outlog)
  8406. return i;
  8407. if (pass == 0)
  8408. pass = "within digitization limits:\n";
  8409. }
  8410. {
  8411. /* There has been an error in processing, or we need to log this
  8412. * value.
  8413. */
  8414. double is_lo, is_hi;
  8415. /* pass is set at this point if either of the tests above would have
  8416. * passed. Don't do these additional tests here - just log the
  8417. * original [es_lo..es_hi] values.
  8418. */
  8419. if (pass == 0 && vi->use_input_precision && vi->dp->sbit)
  8420. {
  8421. /* Ok, something is wrong - this actually happens in current libpng
  8422. * 16-to-8 processing. Assume that the input value (id, adjusted
  8423. * for sbit) can be anywhere between value-.5 and value+.5 - quite a
  8424. * large range if sbit is low.
  8425. *
  8426. * NOTE: at present because the libpng gamma table stuff has been
  8427. * changed to use a rounding algorithm to correct errors in 8-bit
  8428. * calculations the precise sbit calculation (a shift) has been
  8429. * lost. This can result in up to a +/-1 error in the presence of
  8430. * an sbit less than the bit depth.
  8431. */
  8432. # if PNG_LIBPNG_VER < 10700
  8433. # define SBIT_ERROR .5
  8434. # else
  8435. # define SBIT_ERROR 1.
  8436. # endif
  8437. double tmp = (isbit - SBIT_ERROR)/sbit_max;
  8438. if (tmp <= 0)
  8439. tmp = 0;
  8440. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  8441. tmp = pow(tmp, vi->file_inverse);
  8442. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  8443. NULL);
  8444. if (output_is_encoded && tmp > 0 && tmp < 1)
  8445. tmp = pow(tmp, vi->screen_inverse);
  8446. is_lo = ceil(outmax * tmp - vi->maxout_total);
  8447. if (is_lo < 0)
  8448. is_lo = 0;
  8449. tmp = (isbit + SBIT_ERROR)/sbit_max;
  8450. if (tmp >= 1)
  8451. tmp = 1;
  8452. else if (alpha >= 0 && vi->file_inverse > 0 && tmp < 1)
  8453. tmp = pow(tmp, vi->file_inverse);
  8454. tmp = gamma_component_compose(do_background, tmp, alpha, background,
  8455. NULL);
  8456. if (output_is_encoded && tmp > 0 && tmp < 1)
  8457. tmp = pow(tmp, vi->screen_inverse);
  8458. is_hi = floor(outmax * tmp + vi->maxout_total);
  8459. if (is_hi > outmax)
  8460. is_hi = outmax;
  8461. if (!(od < is_lo || od > is_hi))
  8462. {
  8463. if (encoded_error < vi->outlog)
  8464. return i;
  8465. pass = "within input precision limits:\n";
  8466. }
  8467. /* One last chance. If this is an alpha channel and the 16to8
  8468. * option has been used and 'inaccurate' scaling is used then the
  8469. * bit reduction is obtained by simply using the top 8 bits of the
  8470. * value.
  8471. *
  8472. * This is only done for older libpng versions when the 'inaccurate'
  8473. * (chop) method of scaling was used.
  8474. */
  8475. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  8476. # if PNG_LIBPNG_VER < 10504
  8477. /* This may be required for other components in the future,
  8478. * but at present the presence of gamma correction effectively
  8479. * prevents the errors in the component scaling (I don't quite
  8480. * understand why, but since it's better this way I care not
  8481. * to ask, JB 20110419.)
  8482. */
  8483. if (pass == 0 && alpha < 0 && vi->scale16 && vi->sbit > 8 &&
  8484. vi->sbit + vi->isbit_shift == 16)
  8485. {
  8486. tmp = ((id >> 8) - .5)/255;
  8487. if (tmp > 0)
  8488. {
  8489. is_lo = ceil(outmax * tmp - vi->maxout_total);
  8490. if (is_lo < 0) is_lo = 0;
  8491. }
  8492. else
  8493. is_lo = 0;
  8494. tmp = ((id >> 8) + .5)/255;
  8495. if (tmp < 1)
  8496. {
  8497. is_hi = floor(outmax * tmp + vi->maxout_total);
  8498. if (is_hi > outmax) is_hi = outmax;
  8499. }
  8500. else
  8501. is_hi = outmax;
  8502. if (!(od < is_lo || od > is_hi))
  8503. {
  8504. if (encoded_error < vi->outlog)
  8505. return i;
  8506. pass = "within 8 bit limits:\n";
  8507. }
  8508. }
  8509. # endif
  8510. # endif
  8511. }
  8512. else /* !use_input_precision */
  8513. is_lo = es_lo, is_hi = es_hi;
  8514. /* Attempt to output a meaningful error/warning message: the message
  8515. * output depends on the background/composite operation being performed
  8516. * because this changes what parameters were actually used above.
  8517. */
  8518. {
  8519. size_t pos = 0;
  8520. /* Need either 1/255 or 1/65535 precision here; 3 or 6 decimal
  8521. * places. Just use outmax to work out which.
  8522. */
  8523. int precision = (outmax >= 1000 ? 6 : 3);
  8524. int use_input=1, use_background=0, do_compose=0;
  8525. char msg[256];
  8526. if (pass != 0)
  8527. pos = safecat(msg, sizeof msg, pos, "\n\t");
  8528. /* Set up the various flags, the output_is_encoded flag above
  8529. * is also used below. do_compose is just a double check.
  8530. */
  8531. switch (do_background)
  8532. {
  8533. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  8534. case PNG_BACKGROUND_GAMMA_SCREEN:
  8535. case PNG_BACKGROUND_GAMMA_FILE:
  8536. case PNG_BACKGROUND_GAMMA_UNIQUE:
  8537. use_background = (alpha >= 0 && alpha < 1);
  8538. # endif
  8539. # ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  8540. /* FALLTHROUGH */
  8541. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  8542. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  8543. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  8544. # endif /* ALPHA_MODE_SUPPORTED */
  8545. do_compose = (alpha > 0 && alpha < 1);
  8546. use_input = (alpha != 0);
  8547. break;
  8548. default:
  8549. break;
  8550. }
  8551. /* Check the 'compose' flag */
  8552. if (compose != do_compose)
  8553. png_error(vi->pp, "internal error (compose)");
  8554. /* 'name' is the component name */
  8555. pos = safecat(msg, sizeof msg, pos, name);
  8556. pos = safecat(msg, sizeof msg, pos, "(");
  8557. pos = safecatn(msg, sizeof msg, pos, id);
  8558. if (use_input || pass != 0/*logging*/)
  8559. {
  8560. if (isbit != id)
  8561. {
  8562. /* sBIT has reduced the precision of the input: */
  8563. pos = safecat(msg, sizeof msg, pos, ", sbit(");
  8564. pos = safecatn(msg, sizeof msg, pos, vi->sbit);
  8565. pos = safecat(msg, sizeof msg, pos, "): ");
  8566. pos = safecatn(msg, sizeof msg, pos, isbit);
  8567. }
  8568. pos = safecat(msg, sizeof msg, pos, "/");
  8569. /* The output is either "id/max" or "id sbit(sbit): isbit/max" */
  8570. pos = safecatn(msg, sizeof msg, pos, vi->sbit_max);
  8571. }
  8572. pos = safecat(msg, sizeof msg, pos, ")");
  8573. /* A component may have been multiplied (in linear space) by the
  8574. * alpha value, 'compose' says whether this is relevant.
  8575. */
  8576. if (compose || pass != 0)
  8577. {
  8578. /* If any form of composition is being done report our
  8579. * calculated linear value here (the code above doesn't record
  8580. * the input value before composition is performed, so what
  8581. * gets reported is the value after composition.)
  8582. */
  8583. if (use_input || pass != 0)
  8584. {
  8585. if (vi->file_inverse > 0)
  8586. {
  8587. pos = safecat(msg, sizeof msg, pos, "^");
  8588. pos = safecatd(msg, sizeof msg, pos, vi->file_inverse, 2);
  8589. }
  8590. else
  8591. pos = safecat(msg, sizeof msg, pos, "[linear]");
  8592. pos = safecat(msg, sizeof msg, pos, "*(alpha)");
  8593. pos = safecatd(msg, sizeof msg, pos, alpha, precision);
  8594. }
  8595. /* Now record the *linear* background value if it was used
  8596. * (this function is not passed the original, non-linear,
  8597. * value but it is contained in the test name.)
  8598. */
  8599. if (use_background)
  8600. {
  8601. pos = safecat(msg, sizeof msg, pos, use_input ? "+" : " ");
  8602. pos = safecat(msg, sizeof msg, pos, "(background)");
  8603. pos = safecatd(msg, sizeof msg, pos, background, precision);
  8604. pos = safecat(msg, sizeof msg, pos, "*");
  8605. pos = safecatd(msg, sizeof msg, pos, 1-alpha, precision);
  8606. }
  8607. }
  8608. /* Report the calculated value (input_sample) and the linearized
  8609. * libpng value (output) unless this is just a component gamma
  8610. * correction.
  8611. */
  8612. if (compose || alpha < 0 || pass != 0)
  8613. {
  8614. pos = safecat(msg, sizeof msg, pos,
  8615. pass != 0 ? " =\n\t" : " = ");
  8616. pos = safecatd(msg, sizeof msg, pos, input_sample, precision);
  8617. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  8618. pos = safecatd(msg, sizeof msg, pos, output, precision);
  8619. pos = safecat(msg, sizeof msg, pos, ")");
  8620. /* Finally report the output gamma encoding, if any. */
  8621. if (output_is_encoded)
  8622. {
  8623. pos = safecat(msg, sizeof msg, pos, " ^");
  8624. pos = safecatd(msg, sizeof msg, pos, vi->screen_inverse, 2);
  8625. pos = safecat(msg, sizeof msg, pos, "(to screen) =");
  8626. }
  8627. else
  8628. pos = safecat(msg, sizeof msg, pos, " [screen is linear] =");
  8629. }
  8630. if ((!compose && alpha >= 0) || pass != 0)
  8631. {
  8632. if (pass != 0) /* logging */
  8633. pos = safecat(msg, sizeof msg, pos, "\n\t[overall:");
  8634. /* This is the non-composition case, the internal linear
  8635. * values are irrelevant (though the log below will reveal
  8636. * them.) Output a much shorter warning/error message and report
  8637. * the overall gamma correction.
  8638. */
  8639. if (vi->gamma_correction > 0)
  8640. {
  8641. pos = safecat(msg, sizeof msg, pos, " ^");
  8642. pos = safecatd(msg, sizeof msg, pos, vi->gamma_correction, 2);
  8643. pos = safecat(msg, sizeof msg, pos, "(gamma correction) =");
  8644. }
  8645. else
  8646. pos = safecat(msg, sizeof msg, pos,
  8647. " [no gamma correction] =");
  8648. if (pass != 0)
  8649. pos = safecat(msg, sizeof msg, pos, "]");
  8650. }
  8651. /* This is our calculated encoded_sample which should (but does
  8652. * not) match od:
  8653. */
  8654. pos = safecat(msg, sizeof msg, pos, pass != 0 ? "\n\t" : " ");
  8655. pos = safecatd(msg, sizeof msg, pos, is_lo, 1);
  8656. pos = safecat(msg, sizeof msg, pos, " < ");
  8657. pos = safecatd(msg, sizeof msg, pos, encoded_sample, 1);
  8658. pos = safecat(msg, sizeof msg, pos, " (libpng: ");
  8659. pos = safecatn(msg, sizeof msg, pos, od);
  8660. pos = safecat(msg, sizeof msg, pos, ")");
  8661. pos = safecat(msg, sizeof msg, pos, "/");
  8662. pos = safecatn(msg, sizeof msg, pos, outmax);
  8663. pos = safecat(msg, sizeof msg, pos, " < ");
  8664. pos = safecatd(msg, sizeof msg, pos, is_hi, 1);
  8665. if (pass == 0) /* The error condition */
  8666. {
  8667. # ifdef PNG_WARNINGS_SUPPORTED
  8668. png_warning(vi->pp, msg);
  8669. # else
  8670. store_warning(vi->pp, msg);
  8671. # endif
  8672. }
  8673. else /* logging this value */
  8674. store_verbose(&vi->dp->pm->this, vi->pp, pass, msg);
  8675. }
  8676. }
  8677. }
  8678. return i;
  8679. }
  8680. static void
  8681. gamma_image_validate(gamma_display *dp, png_const_structp pp,
  8682. png_infop pi)
  8683. {
  8684. /* Get some constants derived from the input and output file formats: */
  8685. const png_store* const ps = dp->this.ps;
  8686. png_byte in_ct = dp->this.colour_type;
  8687. png_byte in_bd = dp->this.bit_depth;
  8688. png_uint_32 w = dp->this.w;
  8689. png_uint_32 h = dp->this.h;
  8690. const size_t cbRow = dp->this.cbRow;
  8691. png_byte out_ct = png_get_color_type(pp, pi);
  8692. png_byte out_bd = png_get_bit_depth(pp, pi);
  8693. /* There are three sources of error, firstly the quantization in the
  8694. * file encoding, determined by sbit and/or the file depth, secondly
  8695. * the output (screen) gamma and thirdly the output file encoding.
  8696. *
  8697. * Since this API receives the screen and file gamma in double
  8698. * precision it is possible to calculate an exact answer given an input
  8699. * pixel value. Therefore we assume that the *input* value is exact -
  8700. * sample/maxsample - calculate the corresponding gamma corrected
  8701. * output to the limits of double precision arithmetic and compare with
  8702. * what libpng returns.
  8703. *
  8704. * Since the library must quantize the output to 8 or 16 bits there is
  8705. * a fundamental limit on the accuracy of the output of +/-.5 - this
  8706. * quantization limit is included in addition to the other limits
  8707. * specified by the parameters to the API. (Effectively, add .5
  8708. * everywhere.)
  8709. *
  8710. * The behavior of the 'sbit' parameter is defined by section 12.5
  8711. * (sample depth scaling) of the PNG spec. That section forces the
  8712. * decoder to assume that the PNG values have been scaled if sBIT is
  8713. * present:
  8714. *
  8715. * png-sample = floor( input-sample * (max-out/max-in) + .5);
  8716. *
  8717. * This means that only a subset of the possible PNG values should
  8718. * appear in the input. However, the spec allows the encoder to use a
  8719. * variety of approximations to the above and doesn't require any
  8720. * restriction of the values produced.
  8721. *
  8722. * Nevertheless the spec requires that the upper 'sBIT' bits of the
  8723. * value stored in a PNG file be the original sample bits.
  8724. * Consequently the code below simply scales the top sbit bits by
  8725. * (1<<sbit)-1 to obtain an original sample value.
  8726. *
  8727. * Because there is limited precision in the input it is arguable that
  8728. * an acceptable result is any valid result from input-.5 to input+.5.
  8729. * The basic tests below do not do this, however if 'use_input_precision'
  8730. * is set a subsequent test is performed above.
  8731. */
  8732. unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
  8733. int processing;
  8734. png_uint_32 y;
  8735. const store_palette_entry *in_palette = dp->this.palette;
  8736. int in_is_transparent = dp->this.is_transparent;
  8737. int process_tRNS;
  8738. int out_npalette = -1;
  8739. int out_is_transparent = 0; /* Just refers to the palette case */
  8740. store_palette out_palette;
  8741. validate_info vi;
  8742. /* Check for row overwrite errors */
  8743. store_image_check(dp->this.ps, pp, 0);
  8744. /* Supply the input and output sample depths here - 8 for an indexed image,
  8745. * otherwise the bit depth.
  8746. */
  8747. init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
  8748. processing = (vi.gamma_correction > 0 && !dp->threshold_test)
  8749. || in_bd != out_bd || in_ct != out_ct || vi.do_background;
  8750. process_tRNS = dp->this.has_tRNS && vi.do_background;
  8751. /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
  8752. * the palette there is no way of finding out, because libpng fails to
  8753. * update the palette on png_read_update_info. Indeed, libpng doesn't
  8754. * even do the required work until much later, when it doesn't have any
  8755. * info pointer. Oops. For the moment 'processing' is turned off if
  8756. * out_ct is palette.
  8757. */
  8758. if (in_ct == 3 && out_ct == 3)
  8759. processing = 0;
  8760. if (processing && out_ct == 3)
  8761. out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
  8762. for (y=0; y<h; ++y)
  8763. {
  8764. png_const_bytep pRow = store_image_row(ps, pp, 0, y);
  8765. png_byte std[STANDARD_ROWMAX];
  8766. transform_row(pp, std, in_ct, in_bd, y);
  8767. if (processing)
  8768. {
  8769. unsigned int x;
  8770. for (x=0; x<w; ++x)
  8771. {
  8772. double alpha = 1; /* serves as a flag value */
  8773. /* Record the palette index for index images. */
  8774. unsigned int in_index =
  8775. in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256;
  8776. unsigned int out_index =
  8777. out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256;
  8778. /* Handle input alpha - png_set_background will cause the output
  8779. * alpha to disappear so there is nothing to check.
  8780. */
  8781. if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 ||
  8782. (in_ct == 3 && in_is_transparent))
  8783. {
  8784. unsigned int input_alpha = in_ct == 3 ?
  8785. dp->this.palette[in_index].alpha :
  8786. sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0);
  8787. unsigned int output_alpha = 65536 /* as a flag value */;
  8788. if (out_ct == 3)
  8789. {
  8790. if (out_is_transparent)
  8791. output_alpha = out_palette[out_index].alpha;
  8792. }
  8793. else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
  8794. output_alpha = sample(pRow, out_ct, out_bd, x,
  8795. samples_per_pixel, 0, 0);
  8796. if (output_alpha != 65536)
  8797. alpha = gamma_component_validate("alpha", &vi, input_alpha,
  8798. output_alpha, -1/*alpha*/, 0/*background*/);
  8799. else /* no alpha in output */
  8800. {
  8801. /* This is a copy of the calculation of 'i' above in order to
  8802. * have the alpha value to use in the background calculation.
  8803. */
  8804. alpha = input_alpha >> vi.isbit_shift;
  8805. alpha /= vi.sbit_max;
  8806. }
  8807. }
  8808. else if (process_tRNS)
  8809. {
  8810. /* alpha needs to be set appropriately for this pixel, it is
  8811. * currently 1 and needs to be 0 for an input pixel which matches
  8812. * the values in tRNS.
  8813. */
  8814. switch (in_ct)
  8815. {
  8816. case 0: /* gray */
  8817. if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
  8818. dp->this.transparent.red)
  8819. alpha = 0;
  8820. break;
  8821. case 2: /* RGB */
  8822. if (sample(std, in_ct, in_bd, x, 0, 0, 0) ==
  8823. dp->this.transparent.red &&
  8824. sample(std, in_ct, in_bd, x, 1, 0, 0) ==
  8825. dp->this.transparent.green &&
  8826. sample(std, in_ct, in_bd, x, 2, 0, 0) ==
  8827. dp->this.transparent.blue)
  8828. alpha = 0;
  8829. break;
  8830. default:
  8831. break;
  8832. }
  8833. }
  8834. /* Handle grayscale or RGB components. */
  8835. if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
  8836. (void)gamma_component_validate("gray", &vi,
  8837. sample(std, in_ct, in_bd, x, 0, 0, 0),
  8838. sample(pRow, out_ct, out_bd, x, 0, 0, 0),
  8839. alpha/*component*/, vi.background_red);
  8840. else /* RGB or palette */
  8841. {
  8842. (void)gamma_component_validate("red", &vi,
  8843. in_ct == 3 ? in_palette[in_index].red :
  8844. sample(std, in_ct, in_bd, x, 0, 0, 0),
  8845. out_ct == 3 ? out_palette[out_index].red :
  8846. sample(pRow, out_ct, out_bd, x, 0, 0, 0),
  8847. alpha/*component*/, vi.background_red);
  8848. (void)gamma_component_validate("green", &vi,
  8849. in_ct == 3 ? in_palette[in_index].green :
  8850. sample(std, in_ct, in_bd, x, 1, 0, 0),
  8851. out_ct == 3 ? out_palette[out_index].green :
  8852. sample(pRow, out_ct, out_bd, x, 1, 0, 0),
  8853. alpha/*component*/, vi.background_green);
  8854. (void)gamma_component_validate("blue", &vi,
  8855. in_ct == 3 ? in_palette[in_index].blue :
  8856. sample(std, in_ct, in_bd, x, 2, 0, 0),
  8857. out_ct == 3 ? out_palette[out_index].blue :
  8858. sample(pRow, out_ct, out_bd, x, 2, 0, 0),
  8859. alpha/*component*/, vi.background_blue);
  8860. }
  8861. }
  8862. }
  8863. else if (memcmp(std, pRow, cbRow) != 0)
  8864. {
  8865. char msg[64];
  8866. /* No transform is expected on the threshold tests. */
  8867. sprintf(msg, "gamma: below threshold row %lu changed",
  8868. (unsigned long)y);
  8869. png_error(pp, msg);
  8870. }
  8871. } /* row (y) loop */
  8872. dp->this.ps->validated = 1;
  8873. }
  8874. static void PNGCBAPI
  8875. gamma_end(png_structp ppIn, png_infop pi)
  8876. {
  8877. png_const_structp pp = ppIn;
  8878. gamma_display *dp = voidcast(gamma_display*, png_get_progressive_ptr(pp));
  8879. if (!dp->this.speed)
  8880. gamma_image_validate(dp, pp, pi);
  8881. else
  8882. dp->this.ps->validated = 1;
  8883. }
  8884. /* A single test run checking a gamma transformation.
  8885. *
  8886. * maxabs: maximum absolute error as a fraction
  8887. * maxout: maximum output error in the output units
  8888. * maxpc: maximum percentage error (as a percentage)
  8889. */
  8890. static void
  8891. gamma_test(png_modifier *pmIn, png_byte colour_typeIn,
  8892. png_byte bit_depthIn, int palette_numberIn,
  8893. int interlace_typeIn,
  8894. const double file_gammaIn, const double screen_gammaIn,
  8895. png_byte sbitIn, int threshold_testIn,
  8896. const char *name,
  8897. int use_input_precisionIn, int scale16In,
  8898. int expand16In, int do_backgroundIn,
  8899. const png_color_16 *bkgd_colorIn, double bkgd_gammaIn)
  8900. {
  8901. gamma_display d;
  8902. context(&pmIn->this, fault);
  8903. gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn,
  8904. palette_numberIn, interlace_typeIn, 0, 0, 0),
  8905. file_gammaIn, screen_gammaIn, sbitIn,
  8906. threshold_testIn, use_input_precisionIn, scale16In,
  8907. expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn);
  8908. Try
  8909. {
  8910. png_structp pp;
  8911. png_infop pi;
  8912. gama_modification gama_mod;
  8913. srgb_modification srgb_mod;
  8914. sbit_modification sbit_mod;
  8915. /* For the moment don't use the png_modifier support here. */
  8916. d.pm->encoding_counter = 0;
  8917. modifier_set_encoding(d.pm); /* Just resets everything */
  8918. d.pm->current_gamma = d.file_gamma;
  8919. /* Make an appropriate modifier to set the PNG file gamma to the
  8920. * given gamma value and the sBIT chunk to the given precision.
  8921. */
  8922. d.pm->modifications = NULL;
  8923. gama_modification_init(&gama_mod, d.pm, d.file_gamma);
  8924. srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/);
  8925. if (d.sbit > 0)
  8926. sbit_modification_init(&sbit_mod, d.pm, d.sbit);
  8927. modification_reset(d.pm->modifications);
  8928. /* Get a png_struct for reading the image. */
  8929. pp = set_modifier_for_read(d.pm, &pi, d.this.id, name);
  8930. standard_palette_init(&d.this);
  8931. /* Introduce the correct read function. */
  8932. if (d.pm->this.progressive)
  8933. {
  8934. /* Share the row function with the standard implementation. */
  8935. png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row,
  8936. gamma_end);
  8937. /* Now feed data into the reader until we reach the end: */
  8938. modifier_progressive_read(d.pm, pp, pi);
  8939. }
  8940. else
  8941. {
  8942. /* modifier_read expects a png_modifier* */
  8943. png_set_read_fn(pp, d.pm, modifier_read);
  8944. /* Check the header values: */
  8945. png_read_info(pp, pi);
  8946. /* Process the 'info' requirements. Only one image is generated */
  8947. gamma_info_imp(&d, pp, pi);
  8948. sequential_row(&d.this, pp, pi, -1, 0);
  8949. if (!d.this.speed)
  8950. gamma_image_validate(&d, pp, pi);
  8951. else
  8952. d.this.ps->validated = 1;
  8953. }
  8954. modifier_reset(d.pm);
  8955. if (d.pm->log && !d.threshold_test && !d.this.speed)
  8956. fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n",
  8957. d.this.bit_depth, colour_types[d.this.colour_type], name,
  8958. d.maxerrout, d.maxerrabs, 100*d.maxerrpc);
  8959. /* Log the summary values too. */
  8960. if (d.this.colour_type == 0 || d.this.colour_type == 4)
  8961. {
  8962. switch (d.this.bit_depth)
  8963. {
  8964. case 1:
  8965. break;
  8966. case 2:
  8967. if (d.maxerrout > d.pm->error_gray_2)
  8968. d.pm->error_gray_2 = d.maxerrout;
  8969. break;
  8970. case 4:
  8971. if (d.maxerrout > d.pm->error_gray_4)
  8972. d.pm->error_gray_4 = d.maxerrout;
  8973. break;
  8974. case 8:
  8975. if (d.maxerrout > d.pm->error_gray_8)
  8976. d.pm->error_gray_8 = d.maxerrout;
  8977. break;
  8978. case 16:
  8979. if (d.maxerrout > d.pm->error_gray_16)
  8980. d.pm->error_gray_16 = d.maxerrout;
  8981. break;
  8982. default:
  8983. png_error(pp, "bad bit depth (internal: 1)");
  8984. }
  8985. }
  8986. else if (d.this.colour_type == 2 || d.this.colour_type == 6)
  8987. {
  8988. switch (d.this.bit_depth)
  8989. {
  8990. case 8:
  8991. if (d.maxerrout > d.pm->error_color_8)
  8992. d.pm->error_color_8 = d.maxerrout;
  8993. break;
  8994. case 16:
  8995. if (d.maxerrout > d.pm->error_color_16)
  8996. d.pm->error_color_16 = d.maxerrout;
  8997. break;
  8998. default:
  8999. png_error(pp, "bad bit depth (internal: 2)");
  9000. }
  9001. }
  9002. else if (d.this.colour_type == 3)
  9003. {
  9004. if (d.maxerrout > d.pm->error_indexed)
  9005. d.pm->error_indexed = d.maxerrout;
  9006. }
  9007. }
  9008. Catch(fault)
  9009. modifier_reset(voidcast(png_modifier*,(void*)fault));
  9010. }
  9011. static void gamma_threshold_test(png_modifier *pm, png_byte colour_type,
  9012. png_byte bit_depth, int interlace_type, double file_gamma,
  9013. double screen_gamma)
  9014. {
  9015. size_t pos = 0;
  9016. char name[64];
  9017. pos = safecat(name, sizeof name, pos, "threshold ");
  9018. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  9019. pos = safecat(name, sizeof name, pos, "/");
  9020. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  9021. (void)gamma_test(pm, colour_type, bit_depth, 0/*palette*/, interlace_type,
  9022. file_gamma, screen_gamma, 0/*sBIT*/, 1/*threshold test*/, name,
  9023. 0 /*no input precision*/,
  9024. 0 /*no scale16*/, 0 /*no expand16*/, 0 /*no background*/, 0 /*hence*/,
  9025. 0 /*no background gamma*/);
  9026. }
  9027. static void
  9028. perform_gamma_threshold_tests(png_modifier *pm)
  9029. {
  9030. png_byte colour_type = 0;
  9031. png_byte bit_depth = 0;
  9032. unsigned int palette_number = 0;
  9033. /* Don't test more than one instance of each palette - it's pointless, in
  9034. * fact this test is somewhat excessive since libpng doesn't make this
  9035. * decision based on colour type or bit depth!
  9036. *
  9037. * CHANGED: now test two palettes and, as a side effect, images with and
  9038. * without tRNS.
  9039. */
  9040. while (next_format(&colour_type, &bit_depth, &palette_number,
  9041. pm->test_lbg_gamma_threshold, pm->test_tRNS))
  9042. if (palette_number < 2)
  9043. {
  9044. double test_gamma = 1.0;
  9045. while (test_gamma >= .4)
  9046. {
  9047. /* There's little point testing the interlacing vs non-interlacing,
  9048. * but this can be set from the command line.
  9049. */
  9050. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  9051. test_gamma, 1/test_gamma);
  9052. test_gamma *= .95;
  9053. }
  9054. /* And a special test for sRGB */
  9055. gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
  9056. .45455, 2.2);
  9057. if (fail(pm))
  9058. return;
  9059. }
  9060. }
  9061. static void gamma_transform_test(png_modifier *pm,
  9062. png_byte colour_type, png_byte bit_depth,
  9063. int palette_number,
  9064. int interlace_type, const double file_gamma,
  9065. const double screen_gamma, png_byte sbit,
  9066. int use_input_precision, int scale16)
  9067. {
  9068. size_t pos = 0;
  9069. char name[64];
  9070. if (sbit != bit_depth && sbit != 0)
  9071. {
  9072. pos = safecat(name, sizeof name, pos, "sbit(");
  9073. pos = safecatn(name, sizeof name, pos, sbit);
  9074. pos = safecat(name, sizeof name, pos, ") ");
  9075. }
  9076. else
  9077. pos = safecat(name, sizeof name, pos, "gamma ");
  9078. if (scale16)
  9079. pos = safecat(name, sizeof name, pos, "16to8 ");
  9080. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  9081. pos = safecat(name, sizeof name, pos, "->");
  9082. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  9083. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  9084. file_gamma, screen_gamma, sbit, 0, name, use_input_precision,
  9085. scale16, pm->test_gamma_expand16, 0 , 0, 0);
  9086. }
  9087. static void perform_gamma_transform_tests(png_modifier *pm)
  9088. {
  9089. png_byte colour_type = 0;
  9090. png_byte bit_depth = 0;
  9091. unsigned int palette_number = 0;
  9092. while (next_format(&colour_type, &bit_depth, &palette_number,
  9093. pm->test_lbg_gamma_transform, pm->test_tRNS))
  9094. {
  9095. unsigned int i, j;
  9096. for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
  9097. if (i != j)
  9098. {
  9099. gamma_transform_test(pm, colour_type, bit_depth, palette_number,
  9100. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/,
  9101. pm->use_input_precision, 0 /*do not scale16*/);
  9102. if (fail(pm))
  9103. return;
  9104. }
  9105. }
  9106. }
  9107. static void perform_gamma_sbit_tests(png_modifier *pm)
  9108. {
  9109. png_byte sbit;
  9110. /* The only interesting cases are colour and grayscale, alpha is ignored here
  9111. * for overall speed. Only bit depths where sbit is less than the bit depth
  9112. * are tested.
  9113. */
  9114. for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
  9115. {
  9116. png_byte colour_type = 0, bit_depth = 0;
  9117. unsigned int npalette = 0;
  9118. while (next_format(&colour_type, &bit_depth, &npalette,
  9119. pm->test_lbg_gamma_sbit, pm->test_tRNS))
  9120. if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
  9121. ((colour_type == 3 && sbit < 8) ||
  9122. (colour_type != 3 && sbit < bit_depth)))
  9123. {
  9124. unsigned int i;
  9125. for (i=0; i<pm->ngamma_tests; ++i)
  9126. {
  9127. unsigned int j;
  9128. for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
  9129. {
  9130. gamma_transform_test(pm, colour_type, bit_depth, npalette,
  9131. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  9132. sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
  9133. if (fail(pm))
  9134. return;
  9135. }
  9136. }
  9137. }
  9138. }
  9139. }
  9140. /* Note that this requires a 16 bit source image but produces 8 bit output, so
  9141. * we only need the 16bit write support, but the 16 bit images are only
  9142. * generated if DO_16BIT is defined.
  9143. */
  9144. #ifdef DO_16BIT
  9145. static void perform_gamma_scale16_tests(png_modifier *pm)
  9146. {
  9147. # ifndef PNG_MAX_GAMMA_8
  9148. # define PNG_MAX_GAMMA_8 11
  9149. # endif
  9150. # if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700
  9151. # define SBIT_16_TO_8 PNG_MAX_GAMMA_8
  9152. # else
  9153. # define SBIT_16_TO_8 16
  9154. # endif
  9155. /* Include the alpha cases here. Note that sbit matches the internal value
  9156. * used by the library - otherwise we will get spurious errors from the
  9157. * internal sbit style approximation.
  9158. *
  9159. * The threshold test is here because otherwise the 16 to 8 conversion will
  9160. * proceed *without* gamma correction, and the tests above will fail (but not
  9161. * by much) - this could be fixed, it only appears with the -g option.
  9162. */
  9163. unsigned int i, j;
  9164. for (i=0; i<pm->ngamma_tests; ++i)
  9165. {
  9166. for (j=0; j<pm->ngamma_tests; ++j)
  9167. {
  9168. if (i != j &&
  9169. fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD)
  9170. {
  9171. gamma_transform_test(pm, 0, 16, 0, pm->interlace_type,
  9172. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9173. pm->use_input_precision_16to8, 1 /*scale16*/);
  9174. if (fail(pm))
  9175. return;
  9176. gamma_transform_test(pm, 2, 16, 0, pm->interlace_type,
  9177. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9178. pm->use_input_precision_16to8, 1 /*scale16*/);
  9179. if (fail(pm))
  9180. return;
  9181. gamma_transform_test(pm, 4, 16, 0, pm->interlace_type,
  9182. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9183. pm->use_input_precision_16to8, 1 /*scale16*/);
  9184. if (fail(pm))
  9185. return;
  9186. gamma_transform_test(pm, 6, 16, 0, pm->interlace_type,
  9187. 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8,
  9188. pm->use_input_precision_16to8, 1 /*scale16*/);
  9189. if (fail(pm))
  9190. return;
  9191. }
  9192. }
  9193. }
  9194. }
  9195. #endif /* 16 to 8 bit conversion */
  9196. #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\
  9197. defined(PNG_READ_ALPHA_MODE_SUPPORTED)
  9198. static void gamma_composition_test(png_modifier *pm,
  9199. png_byte colour_type, png_byte bit_depth,
  9200. int palette_number,
  9201. int interlace_type, const double file_gamma,
  9202. const double screen_gamma,
  9203. int use_input_precision, int do_background,
  9204. int expand_16)
  9205. {
  9206. size_t pos = 0;
  9207. png_const_charp base;
  9208. double bg;
  9209. char name[128];
  9210. png_color_16 background;
  9211. /* Make up a name and get an appropriate background gamma value. */
  9212. switch (do_background)
  9213. {
  9214. default:
  9215. base = "";
  9216. bg = 4; /* should not be used */
  9217. break;
  9218. case PNG_BACKGROUND_GAMMA_SCREEN:
  9219. base = " bckg(Screen):";
  9220. bg = 1/screen_gamma;
  9221. break;
  9222. case PNG_BACKGROUND_GAMMA_FILE:
  9223. base = " bckg(File):";
  9224. bg = file_gamma;
  9225. break;
  9226. case PNG_BACKGROUND_GAMMA_UNIQUE:
  9227. base = " bckg(Unique):";
  9228. /* This tests the handling of a unique value, the math is such that the
  9229. * value tends to be <1, but is neither screen nor file (even if they
  9230. * match!)
  9231. */
  9232. bg = (file_gamma + screen_gamma) / 3;
  9233. break;
  9234. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  9235. case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
  9236. base = " alpha(PNG)";
  9237. bg = 4; /* should not be used */
  9238. break;
  9239. case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
  9240. base = " alpha(Porter-Duff)";
  9241. bg = 4; /* should not be used */
  9242. break;
  9243. case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
  9244. base = " alpha(Optimized)";
  9245. bg = 4; /* should not be used */
  9246. break;
  9247. case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
  9248. base = " alpha(Broken)";
  9249. bg = 4; /* should not be used */
  9250. break;
  9251. #endif
  9252. }
  9253. /* Use random background values - the background is always presented in the
  9254. * output space (8 or 16 bit components).
  9255. */
  9256. if (expand_16 || bit_depth == 16)
  9257. {
  9258. png_uint_32 r = random_32();
  9259. background.red = (png_uint_16)r;
  9260. background.green = (png_uint_16)(r >> 16);
  9261. r = random_32();
  9262. background.blue = (png_uint_16)r;
  9263. background.gray = (png_uint_16)(r >> 16);
  9264. /* In earlier libpng versions, those where DIGITIZE is set, any background
  9265. * gamma correction in the expand16 case was done using 8-bit gamma
  9266. * correction tables, resulting in larger errors. To cope with those
  9267. * cases use a 16-bit background value which will handle this gamma
  9268. * correction.
  9269. */
  9270. # if DIGITIZE
  9271. if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
  9272. do_background == PNG_BACKGROUND_GAMMA_FILE) &&
  9273. fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
  9274. {
  9275. /* The background values will be looked up in an 8-bit table to do
  9276. * the gamma correction, so only select values which are an exact
  9277. * match for the 8-bit table entries:
  9278. */
  9279. background.red = (png_uint_16)((background.red >> 8) * 257);
  9280. background.green = (png_uint_16)((background.green >> 8) * 257);
  9281. background.blue = (png_uint_16)((background.blue >> 8) * 257);
  9282. background.gray = (png_uint_16)((background.gray >> 8) * 257);
  9283. }
  9284. # endif
  9285. }
  9286. else /* 8 bit colors */
  9287. {
  9288. png_uint_32 r = random_32();
  9289. background.red = (png_byte)r;
  9290. background.green = (png_byte)(r >> 8);
  9291. background.blue = (png_byte)(r >> 16);
  9292. background.gray = (png_byte)(r >> 24);
  9293. }
  9294. background.index = 193; /* rgb(193,193,193) to detect errors */
  9295. if (!(colour_type & PNG_COLOR_MASK_COLOR))
  9296. {
  9297. /* Because, currently, png_set_background is always called with
  9298. * 'need_expand' false in this case and because the gamma test itself
  9299. * doesn't cause an expand to 8-bit for lower bit depths the colour must
  9300. * be reduced to the correct range.
  9301. */
  9302. if (bit_depth < 8)
  9303. background.gray &= (png_uint_16)((1U << bit_depth)-1);
  9304. /* Grayscale input, we do not convert to RGB (TBD), so we must set the
  9305. * background to gray - else libpng seems to fail.
  9306. */
  9307. background.red = background.green = background.blue = background.gray;
  9308. }
  9309. pos = safecat(name, sizeof name, pos, "gamma ");
  9310. pos = safecatd(name, sizeof name, pos, file_gamma, 3);
  9311. pos = safecat(name, sizeof name, pos, "->");
  9312. pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
  9313. pos = safecat(name, sizeof name, pos, base);
  9314. if (do_background < ALPHA_MODE_OFFSET)
  9315. {
  9316. /* Include the background color and gamma in the name: */
  9317. pos = safecat(name, sizeof name, pos, "(");
  9318. /* This assumes no expand gray->rgb - the current code won't handle that!
  9319. */
  9320. if (colour_type & PNG_COLOR_MASK_COLOR)
  9321. {
  9322. pos = safecatn(name, sizeof name, pos, background.red);
  9323. pos = safecat(name, sizeof name, pos, ",");
  9324. pos = safecatn(name, sizeof name, pos, background.green);
  9325. pos = safecat(name, sizeof name, pos, ",");
  9326. pos = safecatn(name, sizeof name, pos, background.blue);
  9327. }
  9328. else
  9329. pos = safecatn(name, sizeof name, pos, background.gray);
  9330. pos = safecat(name, sizeof name, pos, ")^");
  9331. pos = safecatd(name, sizeof name, pos, bg, 3);
  9332. }
  9333. gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
  9334. file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
  9335. 0/*strip 16*/, expand_16, do_background, &background, bg);
  9336. }
  9337. static void
  9338. perform_gamma_composition_tests(png_modifier *pm, int do_background,
  9339. int expand_16)
  9340. {
  9341. png_byte colour_type = 0;
  9342. png_byte bit_depth = 0;
  9343. unsigned int palette_number = 0;
  9344. /* Skip the non-alpha cases - there is no setting of a transparency colour at
  9345. * present.
  9346. *
  9347. * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do,
  9348. * however the palette case fails miserably so is commented out below.
  9349. */
  9350. while (next_format(&colour_type, &bit_depth, &palette_number,
  9351. pm->test_lbg_gamma_composition, pm->test_tRNS))
  9352. if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0
  9353. #if 0 /* TODO: FIXME */
  9354. /*TODO: FIXME: this should work */
  9355. || colour_type == 3
  9356. #endif
  9357. || (colour_type != 3 && palette_number != 0))
  9358. {
  9359. unsigned int i, j;
  9360. /* Don't skip the i==j case here - it's relevant. */
  9361. for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j)
  9362. {
  9363. gamma_composition_test(pm, colour_type, bit_depth, palette_number,
  9364. pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
  9365. pm->use_input_precision, do_background, expand_16);
  9366. if (fail(pm))
  9367. return;
  9368. }
  9369. }
  9370. }
  9371. #endif /* READ_BACKGROUND || READ_ALPHA_MODE */
  9372. static void
  9373. init_gamma_errors(png_modifier *pm)
  9374. {
  9375. /* Use -1 to catch tests that were not actually run */
  9376. pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = -1.;
  9377. pm->error_color_8 = -1.;
  9378. pm->error_indexed = -1.;
  9379. pm->error_gray_16 = pm->error_color_16 = -1.;
  9380. }
  9381. static void
  9382. print_one(const char *leader, double err)
  9383. {
  9384. if (err != -1.)
  9385. printf(" %s %.5f\n", leader, err);
  9386. }
  9387. static void
  9388. summarize_gamma_errors(png_modifier *pm, png_const_charp who, int low_bit_depth,
  9389. int indexed)
  9390. {
  9391. fflush(stderr);
  9392. if (who)
  9393. printf("\nGamma correction with %s:\n", who);
  9394. else
  9395. printf("\nBasic gamma correction:\n");
  9396. if (low_bit_depth)
  9397. {
  9398. print_one(" 2 bit gray: ", pm->error_gray_2);
  9399. print_one(" 4 bit gray: ", pm->error_gray_4);
  9400. print_one(" 8 bit gray: ", pm->error_gray_8);
  9401. print_one(" 8 bit color:", pm->error_color_8);
  9402. if (indexed)
  9403. print_one(" indexed: ", pm->error_indexed);
  9404. }
  9405. print_one("16 bit gray: ", pm->error_gray_16);
  9406. print_one("16 bit color:", pm->error_color_16);
  9407. fflush(stdout);
  9408. }
  9409. static void
  9410. perform_gamma_test(png_modifier *pm, int summary)
  9411. {
  9412. /*TODO: remove this*/
  9413. /* Save certain values for the temporary overrides below. */
  9414. unsigned int calculations_use_input_precision =
  9415. pm->calculations_use_input_precision;
  9416. # ifdef PNG_READ_BACKGROUND_SUPPORTED
  9417. double maxout8 = pm->maxout8;
  9418. # endif
  9419. /* First some arbitrary no-transform tests: */
  9420. if (!pm->this.speed && pm->test_gamma_threshold)
  9421. {
  9422. perform_gamma_threshold_tests(pm);
  9423. if (fail(pm))
  9424. return;
  9425. }
  9426. /* Now some real transforms. */
  9427. if (pm->test_gamma_transform)
  9428. {
  9429. if (summary)
  9430. {
  9431. fflush(stderr);
  9432. printf("Gamma correction error summary\n\n");
  9433. printf("The printed value is the maximum error in the pixel values\n");
  9434. printf("calculated by the libpng gamma correction code. The error\n");
  9435. printf("is calculated as the difference between the output pixel\n");
  9436. printf("value (always an integer) and the ideal value from the\n");
  9437. printf("libpng specification (typically not an integer).\n\n");
  9438. printf("Expect this value to be less than .5 for 8 bit formats,\n");
  9439. printf("less than 1 for formats with fewer than 8 bits and a small\n");
  9440. printf("number (typically less than 5) for the 16 bit formats.\n");
  9441. printf("For performance reasons the value for 16 bit formats\n");
  9442. printf("increases when the image file includes an sBIT chunk.\n");
  9443. fflush(stdout);
  9444. }
  9445. init_gamma_errors(pm);
  9446. /*TODO: remove this. Necessary because the current libpng
  9447. * implementation works in 8 bits:
  9448. */
  9449. if (pm->test_gamma_expand16)
  9450. pm->calculations_use_input_precision = 1;
  9451. perform_gamma_transform_tests(pm);
  9452. if (!calculations_use_input_precision)
  9453. pm->calculations_use_input_precision = 0;
  9454. if (summary)
  9455. summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/);
  9456. if (fail(pm))
  9457. return;
  9458. }
  9459. /* The sbit tests produce much larger errors: */
  9460. if (pm->test_gamma_sbit)
  9461. {
  9462. init_gamma_errors(pm);
  9463. perform_gamma_sbit_tests(pm);
  9464. if (summary)
  9465. summarize_gamma_errors(pm, "sBIT", pm->sbitlow < 8U, 1/*indexed*/);
  9466. if (fail(pm))
  9467. return;
  9468. }
  9469. #ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */
  9470. if (pm->test_gamma_scale16)
  9471. {
  9472. /* The 16 to 8 bit strip operations: */
  9473. init_gamma_errors(pm);
  9474. perform_gamma_scale16_tests(pm);
  9475. if (summary)
  9476. {
  9477. fflush(stderr);
  9478. printf("\nGamma correction with 16 to 8 bit reduction:\n");
  9479. printf(" 16 bit gray: %.5f\n", pm->error_gray_16);
  9480. printf(" 16 bit color: %.5f\n", pm->error_color_16);
  9481. fflush(stdout);
  9482. }
  9483. if (fail(pm))
  9484. return;
  9485. }
  9486. #endif
  9487. #ifdef PNG_READ_BACKGROUND_SUPPORTED
  9488. if (pm->test_gamma_background)
  9489. {
  9490. init_gamma_errors(pm);
  9491. /*TODO: remove this. Necessary because the current libpng
  9492. * implementation works in 8 bits:
  9493. */
  9494. if (pm->test_gamma_expand16)
  9495. {
  9496. pm->calculations_use_input_precision = 1;
  9497. pm->maxout8 = .499; /* because the 16 bit background is smashed */
  9498. }
  9499. perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE,
  9500. pm->test_gamma_expand16);
  9501. if (!calculations_use_input_precision)
  9502. pm->calculations_use_input_precision = 0;
  9503. pm->maxout8 = maxout8;
  9504. if (summary)
  9505. summarize_gamma_errors(pm, "background", 1, 0/*indexed*/);
  9506. if (fail(pm))
  9507. return;
  9508. }
  9509. #endif
  9510. #ifdef PNG_READ_ALPHA_MODE_SUPPORTED
  9511. if (pm->test_gamma_alpha_mode)
  9512. {
  9513. int do_background;
  9514. init_gamma_errors(pm);
  9515. /*TODO: remove this. Necessary because the current libpng
  9516. * implementation works in 8 bits:
  9517. */
  9518. if (pm->test_gamma_expand16)
  9519. pm->calculations_use_input_precision = 1;
  9520. for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD;
  9521. do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm);
  9522. ++do_background)
  9523. perform_gamma_composition_tests(pm, do_background,
  9524. pm->test_gamma_expand16);
  9525. if (!calculations_use_input_precision)
  9526. pm->calculations_use_input_precision = 0;
  9527. if (summary)
  9528. summarize_gamma_errors(pm, "alpha mode", 1, 0/*indexed*/);
  9529. if (fail(pm))
  9530. return;
  9531. }
  9532. #endif
  9533. }
  9534. #endif /* PNG_READ_GAMMA_SUPPORTED */
  9535. #endif /* PNG_READ_SUPPORTED */
  9536. /* INTERLACE MACRO VALIDATION */
  9537. /* This is copied verbatim from the specification, it is simply the pass
  9538. * number in which each pixel in each 8x8 tile appears. The array must
  9539. * be indexed adam7[y][x] and notice that the pass numbers are based at
  9540. * 1, not 0 - the base libpng uses.
  9541. */
  9542. static const
  9543. png_byte adam7[8][8] =
  9544. {
  9545. { 1,6,4,6,2,6,4,6 },
  9546. { 7,7,7,7,7,7,7,7 },
  9547. { 5,6,5,6,5,6,5,6 },
  9548. { 7,7,7,7,7,7,7,7 },
  9549. { 3,6,4,6,3,6,4,6 },
  9550. { 7,7,7,7,7,7,7,7 },
  9551. { 5,6,5,6,5,6,5,6 },
  9552. { 7,7,7,7,7,7,7,7 }
  9553. };
  9554. /* This routine validates all the interlace support macros in png.h for
  9555. * a variety of valid PNG widths and heights. It uses a number of similarly
  9556. * named internal routines that feed off the above array.
  9557. */
  9558. static png_uint_32
  9559. png_pass_start_row(int pass)
  9560. {
  9561. int x, y;
  9562. ++pass;
  9563. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9564. return y;
  9565. return 0xf;
  9566. }
  9567. static png_uint_32
  9568. png_pass_start_col(int pass)
  9569. {
  9570. int x, y;
  9571. ++pass;
  9572. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9573. return x;
  9574. return 0xf;
  9575. }
  9576. static int
  9577. png_pass_row_shift(int pass)
  9578. {
  9579. int x, y, base=(-1), inc=8;
  9580. ++pass;
  9581. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9582. {
  9583. if (base == (-1))
  9584. base = y;
  9585. else if (base == y)
  9586. {}
  9587. else if (inc == y-base)
  9588. base=y;
  9589. else if (inc == 8)
  9590. inc = y-base, base=y;
  9591. else if (inc != y-base)
  9592. return 0xff; /* error - more than one 'inc' value! */
  9593. }
  9594. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  9595. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  9596. switch (inc)
  9597. {
  9598. case 2: return 1;
  9599. case 4: return 2;
  9600. case 8: return 3;
  9601. default: break;
  9602. }
  9603. /* error - unrecognized 'inc' */
  9604. return (inc << 8) + 0xfd;
  9605. }
  9606. static int
  9607. png_pass_col_shift(int pass)
  9608. {
  9609. int x, y, base=(-1), inc=8;
  9610. ++pass;
  9611. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9612. {
  9613. if (base == (-1))
  9614. base = x;
  9615. else if (base == x)
  9616. {}
  9617. else if (inc == x-base)
  9618. base=x;
  9619. else if (inc == 8)
  9620. inc = x-base, base=x;
  9621. else if (inc != x-base)
  9622. return 0xff; /* error - more than one 'inc' value! */
  9623. }
  9624. if (base == (-1)) return 0xfe; /* error - no row in pass! */
  9625. /* The shift is always 1, 2 or 3 - no pass has all the rows! */
  9626. switch (inc)
  9627. {
  9628. case 1: return 0; /* pass 7 has all the columns */
  9629. case 2: return 1;
  9630. case 4: return 2;
  9631. case 8: return 3;
  9632. default: break;
  9633. }
  9634. /* error - unrecognized 'inc' */
  9635. return (inc << 8) + 0xfd;
  9636. }
  9637. static png_uint_32
  9638. png_row_from_pass_row(png_uint_32 yIn, int pass)
  9639. {
  9640. /* By examination of the array: */
  9641. switch (pass)
  9642. {
  9643. case 0: return yIn * 8;
  9644. case 1: return yIn * 8;
  9645. case 2: return yIn * 8 + 4;
  9646. case 3: return yIn * 4;
  9647. case 4: return yIn * 4 + 2;
  9648. case 5: return yIn * 2;
  9649. case 6: return yIn * 2 + 1;
  9650. default: break;
  9651. }
  9652. return 0xff; /* bad pass number */
  9653. }
  9654. static png_uint_32
  9655. png_col_from_pass_col(png_uint_32 xIn, int pass)
  9656. {
  9657. /* By examination of the array: */
  9658. switch (pass)
  9659. {
  9660. case 0: return xIn * 8;
  9661. case 1: return xIn * 8 + 4;
  9662. case 2: return xIn * 4;
  9663. case 3: return xIn * 4 + 2;
  9664. case 4: return xIn * 2;
  9665. case 5: return xIn * 2 + 1;
  9666. case 6: return xIn;
  9667. default: break;
  9668. }
  9669. return 0xff; /* bad pass number */
  9670. }
  9671. static int
  9672. png_row_in_interlace_pass(png_uint_32 y, int pass)
  9673. {
  9674. /* Is row 'y' in pass 'pass'? */
  9675. int x;
  9676. y &= 7;
  9677. ++pass;
  9678. for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9679. return 1;
  9680. return 0;
  9681. }
  9682. static int
  9683. png_col_in_interlace_pass(png_uint_32 x, int pass)
  9684. {
  9685. /* Is column 'x' in pass 'pass'? */
  9686. int y;
  9687. x &= 7;
  9688. ++pass;
  9689. for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9690. return 1;
  9691. return 0;
  9692. }
  9693. static png_uint_32
  9694. png_pass_rows(png_uint_32 height, int pass)
  9695. {
  9696. png_uint_32 tiles = height>>3;
  9697. png_uint_32 rows = 0;
  9698. unsigned int x, y;
  9699. height &= 7;
  9700. ++pass;
  9701. for (y=0; y<8; ++y) for (x=0; x<8; ++x) if (adam7[y][x] == pass)
  9702. {
  9703. rows += tiles;
  9704. if (y < height) ++rows;
  9705. break; /* i.e. break the 'x', column, loop. */
  9706. }
  9707. return rows;
  9708. }
  9709. static png_uint_32
  9710. png_pass_cols(png_uint_32 width, int pass)
  9711. {
  9712. png_uint_32 tiles = width>>3;
  9713. png_uint_32 cols = 0;
  9714. unsigned int x, y;
  9715. width &= 7;
  9716. ++pass;
  9717. for (x=0; x<8; ++x) for (y=0; y<8; ++y) if (adam7[y][x] == pass)
  9718. {
  9719. cols += tiles;
  9720. if (x < width) ++cols;
  9721. break; /* i.e. break the 'y', row, loop. */
  9722. }
  9723. return cols;
  9724. }
  9725. static void
  9726. perform_interlace_macro_validation(void)
  9727. {
  9728. /* The macros to validate, first those that depend only on pass:
  9729. *
  9730. * PNG_PASS_START_ROW(pass)
  9731. * PNG_PASS_START_COL(pass)
  9732. * PNG_PASS_ROW_SHIFT(pass)
  9733. * PNG_PASS_COL_SHIFT(pass)
  9734. */
  9735. int pass;
  9736. for (pass=0; pass<7; ++pass)
  9737. {
  9738. png_uint_32 m, f, v;
  9739. m = PNG_PASS_START_ROW(pass);
  9740. f = png_pass_start_row(pass);
  9741. if (m != f)
  9742. {
  9743. fprintf(stderr, "PNG_PASS_START_ROW(%d) = %u != %x\n", pass, m, f);
  9744. exit(99);
  9745. }
  9746. m = PNG_PASS_START_COL(pass);
  9747. f = png_pass_start_col(pass);
  9748. if (m != f)
  9749. {
  9750. fprintf(stderr, "PNG_PASS_START_COL(%d) = %u != %x\n", pass, m, f);
  9751. exit(99);
  9752. }
  9753. m = PNG_PASS_ROW_SHIFT(pass);
  9754. f = png_pass_row_shift(pass);
  9755. if (m != f)
  9756. {
  9757. fprintf(stderr, "PNG_PASS_ROW_SHIFT(%d) = %u != %x\n", pass, m, f);
  9758. exit(99);
  9759. }
  9760. m = PNG_PASS_COL_SHIFT(pass);
  9761. f = png_pass_col_shift(pass);
  9762. if (m != f)
  9763. {
  9764. fprintf(stderr, "PNG_PASS_COL_SHIFT(%d) = %u != %x\n", pass, m, f);
  9765. exit(99);
  9766. }
  9767. /* Macros that depend on the image or sub-image height too:
  9768. *
  9769. * PNG_PASS_ROWS(height, pass)
  9770. * PNG_PASS_COLS(width, pass)
  9771. * PNG_ROW_FROM_PASS_ROW(yIn, pass)
  9772. * PNG_COL_FROM_PASS_COL(xIn, pass)
  9773. * PNG_ROW_IN_INTERLACE_PASS(y, pass)
  9774. * PNG_COL_IN_INTERLACE_PASS(x, pass)
  9775. */
  9776. for (v=0;;)
  9777. {
  9778. /* The first two tests overflow if the pass row or column is outside
  9779. * the possible range for a 32-bit result. In fact the values should
  9780. * never be outside the range for a 31-bit result, but checking for 32
  9781. * bits here ensures that if an app uses a bogus pass row or column
  9782. * (just so long as it fits in a 32 bit integer) it won't get a
  9783. * possibly dangerous overflow.
  9784. */
  9785. /* First the base 0 stuff: */
  9786. if (v < png_pass_rows(0xFFFFFFFFU, pass))
  9787. {
  9788. m = PNG_ROW_FROM_PASS_ROW(v, pass);
  9789. f = png_row_from_pass_row(v, pass);
  9790. if (m != f)
  9791. {
  9792. fprintf(stderr, "PNG_ROW_FROM_PASS_ROW(%u, %d) = %u != %x\n",
  9793. v, pass, m, f);
  9794. exit(99);
  9795. }
  9796. }
  9797. if (v < png_pass_cols(0xFFFFFFFFU, pass))
  9798. {
  9799. m = PNG_COL_FROM_PASS_COL(v, pass);
  9800. f = png_col_from_pass_col(v, pass);
  9801. if (m != f)
  9802. {
  9803. fprintf(stderr, "PNG_COL_FROM_PASS_COL(%u, %d) = %u != %x\n",
  9804. v, pass, m, f);
  9805. exit(99);
  9806. }
  9807. }
  9808. m = PNG_ROW_IN_INTERLACE_PASS(v, pass);
  9809. f = png_row_in_interlace_pass(v, pass);
  9810. if (m != f)
  9811. {
  9812. fprintf(stderr, "PNG_ROW_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  9813. v, pass, m, f);
  9814. exit(99);
  9815. }
  9816. m = PNG_COL_IN_INTERLACE_PASS(v, pass);
  9817. f = png_col_in_interlace_pass(v, pass);
  9818. if (m != f)
  9819. {
  9820. fprintf(stderr, "PNG_COL_IN_INTERLACE_PASS(%u, %d) = %u != %x\n",
  9821. v, pass, m, f);
  9822. exit(99);
  9823. }
  9824. /* Then the base 1 stuff: */
  9825. ++v;
  9826. m = PNG_PASS_ROWS(v, pass);
  9827. f = png_pass_rows(v, pass);
  9828. if (m != f)
  9829. {
  9830. fprintf(stderr, "PNG_PASS_ROWS(%u, %d) = %u != %x\n",
  9831. v, pass, m, f);
  9832. exit(99);
  9833. }
  9834. m = PNG_PASS_COLS(v, pass);
  9835. f = png_pass_cols(v, pass);
  9836. if (m != f)
  9837. {
  9838. fprintf(stderr, "PNG_PASS_COLS(%u, %d) = %u != %x\n",
  9839. v, pass, m, f);
  9840. exit(99);
  9841. }
  9842. /* Move to the next v - the stepping algorithm starts skipping
  9843. * values above 1024.
  9844. */
  9845. if (v > 1024)
  9846. {
  9847. if (v == PNG_UINT_31_MAX)
  9848. break;
  9849. v = (v << 1) ^ v;
  9850. if (v >= PNG_UINT_31_MAX)
  9851. v = PNG_UINT_31_MAX-1;
  9852. }
  9853. }
  9854. }
  9855. }
  9856. /* Test color encodings. These values are back-calculated from the published
  9857. * chromaticities. The values are accurate to about 14 decimal places; 15 are
  9858. * given. These values are much more accurate than the ones given in the spec,
  9859. * which typically don't exceed 4 decimal places. This allows testing of the
  9860. * libpng code to its theoretical accuracy of 4 decimal places. (If pngvalid
  9861. * used the published errors the 'slack' permitted would have to be +/-.5E-4 or
  9862. * more.)
  9863. *
  9864. * The png_modifier code assumes that encodings[0] is sRGB and treats it
  9865. * specially: do not change the first entry in this list!
  9866. */
  9867. static const color_encoding test_encodings[] =
  9868. {
  9869. /* sRGB: must be first in this list! */
  9870. /*gamma:*/ { 1/2.2,
  9871. /*red: */ { 0.412390799265959, 0.212639005871510, 0.019330818715592 },
  9872. /*green:*/ { 0.357584339383878, 0.715168678767756, 0.119194779794626 },
  9873. /*blue: */ { 0.180480788401834, 0.072192315360734, 0.950532152249660} },
  9874. /* Kodak ProPhoto (wide gamut) */
  9875. /*gamma:*/ { 1/1.6 /*approximate: uses 1.8 power law compared to sRGB 2.4*/,
  9876. /*red: */ { 0.797760489672303, 0.288071128229293, 0.000000000000000 },
  9877. /*green:*/ { 0.135185837175740, 0.711843217810102, 0.000000000000000 },
  9878. /*blue: */ { 0.031349349581525, 0.000085653960605, 0.825104602510460} },
  9879. /* Adobe RGB (1998) */
  9880. /*gamma:*/ { 1/(2+51./256),
  9881. /*red: */ { 0.576669042910131, 0.297344975250536, 0.027031361386412 },
  9882. /*green:*/ { 0.185558237906546, 0.627363566255466, 0.070688852535827 },
  9883. /*blue: */ { 0.188228646234995, 0.075291458493998, 0.991337536837639} },
  9884. /* Adobe Wide Gamut RGB */
  9885. /*gamma:*/ { 1/(2+51./256),
  9886. /*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 },
  9887. /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 },
  9888. /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} },
  9889. /* Fake encoding which selects just the green channel */
  9890. /*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */
  9891. /*red: */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 },
  9892. /*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 },
  9893. /*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} },
  9894. };
  9895. /* signal handler
  9896. *
  9897. * This attempts to trap signals and escape without crashing. It needs a
  9898. * context pointer so that it can throw an exception (call longjmp) to recover
  9899. * from the condition; this is handled by making the png_modifier used by 'main'
  9900. * into a global variable.
  9901. */
  9902. static png_modifier pm;
  9903. static void signal_handler(int signum)
  9904. {
  9905. size_t pos = 0;
  9906. char msg[64];
  9907. pos = safecat(msg, sizeof msg, pos, "caught signal: ");
  9908. switch (signum)
  9909. {
  9910. case SIGABRT:
  9911. pos = safecat(msg, sizeof msg, pos, "abort");
  9912. break;
  9913. case SIGFPE:
  9914. pos = safecat(msg, sizeof msg, pos, "floating point exception");
  9915. break;
  9916. case SIGILL:
  9917. pos = safecat(msg, sizeof msg, pos, "illegal instruction");
  9918. break;
  9919. case SIGINT:
  9920. pos = safecat(msg, sizeof msg, pos, "interrupt");
  9921. break;
  9922. case SIGSEGV:
  9923. pos = safecat(msg, sizeof msg, pos, "invalid memory access");
  9924. break;
  9925. case SIGTERM:
  9926. pos = safecat(msg, sizeof msg, pos, "termination request");
  9927. break;
  9928. default:
  9929. pos = safecat(msg, sizeof msg, pos, "unknown ");
  9930. pos = safecatn(msg, sizeof msg, pos, signum);
  9931. break;
  9932. }
  9933. store_log(&pm.this, NULL/*png_structp*/, msg, 1/*error*/);
  9934. /* And finally throw an exception so we can keep going, unless this is
  9935. * SIGTERM in which case stop now.
  9936. */
  9937. if (signum != SIGTERM)
  9938. {
  9939. struct exception_context *the_exception_context =
  9940. &pm.this.exception_context;
  9941. Throw &pm.this;
  9942. }
  9943. else
  9944. exit(1);
  9945. }
  9946. /* main program */
  9947. int main(int argc, char **argv)
  9948. {
  9949. int summary = 1; /* Print the error summary at the end */
  9950. int memstats = 0; /* Print memory statistics at the end */
  9951. /* Create the given output file on success: */
  9952. const char *touch = NULL;
  9953. /* This is an array of standard gamma values (believe it or not I've seen
  9954. * every one of these mentioned somewhere.)
  9955. *
  9956. * In the following list the most useful values are first!
  9957. */
  9958. static double
  9959. gammas[]={2.2, 1.0, 2.2/1.45, 1.8, 1.5, 2.4, 2.5, 2.62, 2.9};
  9960. /* This records the command and arguments: */
  9961. size_t cp = 0;
  9962. char command[1024];
  9963. anon_context(&pm.this);
  9964. gnu_volatile(summary)
  9965. gnu_volatile(memstats)
  9966. gnu_volatile(touch)
  9967. /* Add appropriate signal handlers, just the ANSI specified ones: */
  9968. signal(SIGABRT, signal_handler);
  9969. signal(SIGFPE, signal_handler);
  9970. signal(SIGILL, signal_handler);
  9971. signal(SIGINT, signal_handler);
  9972. signal(SIGSEGV, signal_handler);
  9973. signal(SIGTERM, signal_handler);
  9974. #ifdef HAVE_FEENABLEEXCEPT
  9975. /* Only required to enable FP exceptions on platforms where they start off
  9976. * disabled; this is not necessary but if it is not done pngvalid will likely
  9977. * end up ignoring FP conditions that other platforms fault.
  9978. */
  9979. feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
  9980. #endif
  9981. modifier_init(&pm);
  9982. /* Preallocate the image buffer, because we know how big it needs to be,
  9983. * note that, for testing purposes, it is deliberately mis-aligned by tag
  9984. * bytes either side. All rows have an additional five bytes of padding for
  9985. * overwrite checking.
  9986. */
  9987. store_ensure_image(&pm.this, NULL, 2, TRANSFORM_ROWMAX, TRANSFORM_HEIGHTMAX);
  9988. /* Don't give argv[0], it's normally some horrible libtool string: */
  9989. cp = safecat(command, sizeof command, cp, "pngvalid");
  9990. /* Default to error on warning: */
  9991. pm.this.treat_warnings_as_errors = 1;
  9992. /* Default assume_16_bit_calculations appropriately; this tells the checking
  9993. * code that 16-bit arithmetic is used for 8-bit samples when it would make a
  9994. * difference.
  9995. */
  9996. pm.assume_16_bit_calculations = PNG_LIBPNG_VER >= 10700;
  9997. /* Currently 16 bit expansion happens at the end of the pipeline, so the
  9998. * calculations are done in the input bit depth not the output.
  9999. *
  10000. * TODO: fix this
  10001. */
  10002. pm.calculations_use_input_precision = 1U;
  10003. /* Store the test gammas */
  10004. pm.gammas = gammas;
  10005. pm.ngammas = ARRAY_SIZE(gammas);
  10006. pm.ngamma_tests = 0; /* default to off */
  10007. /* Low bit depth gray images don't do well in the gamma tests, until
  10008. * this is fixed turn them off for some gamma cases:
  10009. */
  10010. # ifdef PNG_WRITE_tRNS_SUPPORTED
  10011. pm.test_tRNS = 1;
  10012. # endif
  10013. pm.test_lbg = PNG_LIBPNG_VER >= 10600;
  10014. pm.test_lbg_gamma_threshold = 1;
  10015. pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600;
  10016. pm.test_lbg_gamma_sbit = 1;
  10017. pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700;
  10018. /* And the test encodings */
  10019. pm.encodings = test_encodings;
  10020. pm.nencodings = ARRAY_SIZE(test_encodings);
  10021. # if PNG_LIBPNG_VER < 10700
  10022. pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */
  10023. # else
  10024. pm.sbitlow = 1U;
  10025. # endif
  10026. /* The following allows results to pass if they correspond to anything in the
  10027. * transformed range [input-.5,input+.5]; this is is required because of the
  10028. * way libpng treates the 16_TO_8 flag when building the gamma tables in
  10029. * releases up to 1.6.0.
  10030. *
  10031. * TODO: review this
  10032. */
  10033. pm.use_input_precision_16to8 = 1U;
  10034. pm.use_input_precision_sbit = 1U; /* because libpng now rounds sBIT */
  10035. /* Some default values (set the behavior for 'make check' here).
  10036. * These values simply control the maximum error permitted in the gamma
  10037. * transformations. The practical limits for human perception are described
  10038. * below (the setting for maxpc16), however for 8 bit encodings it isn't
  10039. * possible to meet the accepted capabilities of human vision - i.e. 8 bit
  10040. * images can never be good enough, regardless of encoding.
  10041. */
  10042. pm.maxout8 = .1; /* Arithmetic error in *encoded* value */
  10043. pm.maxabs8 = .00005; /* 1/20000 */
  10044. pm.maxcalc8 = 1./255; /* +/-1 in 8 bits for compose errors */
  10045. pm.maxpc8 = .499; /* I.e., .499% fractional error */
  10046. pm.maxout16 = .499; /* Error in *encoded* value */
  10047. pm.maxabs16 = .00005;/* 1/20000 */
  10048. pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */
  10049. # if PNG_LIBPNG_VER < 10700
  10050. pm.maxcalcG = 1./((1<<PNG_MAX_GAMMA_8)-1);
  10051. # else
  10052. pm.maxcalcG = 1./((1<<16)-1);
  10053. # endif
  10054. /* NOTE: this is a reasonable perceptual limit. We assume that humans can
  10055. * perceive light level differences of 1% over a 100:1 range, so we need to
  10056. * maintain 1 in 10000 accuracy (in linear light space), which is what the
  10057. * following guarantees. It also allows significantly higher errors at
  10058. * higher 16 bit values, which is important for performance. The actual
  10059. * maximum 16 bit error is about +/-1.9 in the fixed point implementation but
  10060. * this is only allowed for values >38149 by the following:
  10061. */
  10062. pm.maxpc16 = .005; /* I.e., 1/200% - 1/20000 */
  10063. /* Now parse the command line options. */
  10064. while (--argc >= 1)
  10065. {
  10066. int catmore = 0; /* Set if the argument has an argument. */
  10067. /* Record each argument for posterity: */
  10068. cp = safecat(command, sizeof command, cp, " ");
  10069. cp = safecat(command, sizeof command, cp, *++argv);
  10070. if (strcmp(*argv, "-v") == 0)
  10071. pm.this.verbose = 1;
  10072. else if (strcmp(*argv, "-l") == 0)
  10073. pm.log = 1;
  10074. else if (strcmp(*argv, "-q") == 0)
  10075. summary = pm.this.verbose = pm.log = 0;
  10076. else if (strcmp(*argv, "-w") == 0 ||
  10077. strcmp(*argv, "--strict") == 0)
  10078. pm.this.treat_warnings_as_errors = 1; /* NOTE: this is the default! */
  10079. else if (strcmp(*argv, "--nostrict") == 0)
  10080. pm.this.treat_warnings_as_errors = 0;
  10081. else if (strcmp(*argv, "--speed") == 0)
  10082. pm.this.speed = 1, pm.ngamma_tests = pm.ngammas, pm.test_standard = 0,
  10083. summary = 0;
  10084. else if (strcmp(*argv, "--memory") == 0)
  10085. memstats = 1;
  10086. else if (strcmp(*argv, "--size") == 0)
  10087. pm.test_size = 1;
  10088. else if (strcmp(*argv, "--nosize") == 0)
  10089. pm.test_size = 0;
  10090. else if (strcmp(*argv, "--standard") == 0)
  10091. pm.test_standard = 1;
  10092. else if (strcmp(*argv, "--nostandard") == 0)
  10093. pm.test_standard = 0;
  10094. else if (strcmp(*argv, "--transform") == 0)
  10095. pm.test_transform = 1;
  10096. else if (strcmp(*argv, "--notransform") == 0)
  10097. pm.test_transform = 0;
  10098. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  10099. else if (strncmp(*argv, "--transform-disable=",
  10100. sizeof "--transform-disable") == 0)
  10101. {
  10102. pm.test_transform = 1;
  10103. transform_disable(*argv + sizeof "--transform-disable");
  10104. }
  10105. else if (strncmp(*argv, "--transform-enable=",
  10106. sizeof "--transform-enable") == 0)
  10107. {
  10108. pm.test_transform = 1;
  10109. transform_enable(*argv + sizeof "--transform-enable");
  10110. }
  10111. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  10112. else if (strcmp(*argv, "--gamma") == 0)
  10113. {
  10114. /* Just do two gamma tests here (2.2 and linear) for speed: */
  10115. pm.ngamma_tests = 2U;
  10116. pm.test_gamma_threshold = 1;
  10117. pm.test_gamma_transform = 1;
  10118. pm.test_gamma_sbit = 1;
  10119. pm.test_gamma_scale16 = 1;
  10120. pm.test_gamma_background = 1; /* composition */
  10121. pm.test_gamma_alpha_mode = 1;
  10122. }
  10123. else if (strcmp(*argv, "--nogamma") == 0)
  10124. pm.ngamma_tests = 0;
  10125. else if (strcmp(*argv, "--gamma-threshold") == 0)
  10126. pm.ngamma_tests = 2U, pm.test_gamma_threshold = 1;
  10127. else if (strcmp(*argv, "--nogamma-threshold") == 0)
  10128. pm.test_gamma_threshold = 0;
  10129. else if (strcmp(*argv, "--gamma-transform") == 0)
  10130. pm.ngamma_tests = 2U, pm.test_gamma_transform = 1;
  10131. else if (strcmp(*argv, "--nogamma-transform") == 0)
  10132. pm.test_gamma_transform = 0;
  10133. else if (strcmp(*argv, "--gamma-sbit") == 0)
  10134. pm.ngamma_tests = 2U, pm.test_gamma_sbit = 1;
  10135. else if (strcmp(*argv, "--nogamma-sbit") == 0)
  10136. pm.test_gamma_sbit = 0;
  10137. else if (strcmp(*argv, "--gamma-16-to-8") == 0)
  10138. pm.ngamma_tests = 2U, pm.test_gamma_scale16 = 1;
  10139. else if (strcmp(*argv, "--nogamma-16-to-8") == 0)
  10140. pm.test_gamma_scale16 = 0;
  10141. else if (strcmp(*argv, "--gamma-background") == 0)
  10142. pm.ngamma_tests = 2U, pm.test_gamma_background = 1;
  10143. else if (strcmp(*argv, "--nogamma-background") == 0)
  10144. pm.test_gamma_background = 0;
  10145. else if (strcmp(*argv, "--gamma-alpha-mode") == 0)
  10146. pm.ngamma_tests = 2U, pm.test_gamma_alpha_mode = 1;
  10147. else if (strcmp(*argv, "--nogamma-alpha-mode") == 0)
  10148. pm.test_gamma_alpha_mode = 0;
  10149. else if (strcmp(*argv, "--expand16") == 0)
  10150. pm.test_gamma_expand16 = 1;
  10151. else if (strcmp(*argv, "--noexpand16") == 0)
  10152. pm.test_gamma_expand16 = 0;
  10153. else if (strcmp(*argv, "--low-depth-gray") == 0)
  10154. pm.test_lbg = pm.test_lbg_gamma_threshold =
  10155. pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
  10156. pm.test_lbg_gamma_composition = 1;
  10157. else if (strcmp(*argv, "--nolow-depth-gray") == 0)
  10158. pm.test_lbg = pm.test_lbg_gamma_threshold =
  10159. pm.test_lbg_gamma_transform = pm.test_lbg_gamma_sbit =
  10160. pm.test_lbg_gamma_composition = 0;
  10161. # ifdef PNG_WRITE_tRNS_SUPPORTED
  10162. else if (strcmp(*argv, "--tRNS") == 0)
  10163. pm.test_tRNS = 1;
  10164. # endif
  10165. else if (strcmp(*argv, "--notRNS") == 0)
  10166. pm.test_tRNS = 0;
  10167. else if (strcmp(*argv, "--more-gammas") == 0)
  10168. pm.ngamma_tests = 3U;
  10169. else if (strcmp(*argv, "--all-gammas") == 0)
  10170. pm.ngamma_tests = pm.ngammas;
  10171. else if (strcmp(*argv, "--progressive-read") == 0)
  10172. pm.this.progressive = 1;
  10173. else if (strcmp(*argv, "--use-update-info") == 0)
  10174. ++pm.use_update_info; /* Can call multiple times */
  10175. else if (strcmp(*argv, "--interlace") == 0)
  10176. {
  10177. # if CAN_WRITE_INTERLACE
  10178. pm.interlace_type = PNG_INTERLACE_ADAM7;
  10179. # else /* !CAN_WRITE_INTERLACE */
  10180. fprintf(stderr, "pngvalid: no write interlace support\n");
  10181. return SKIP;
  10182. # endif /* !CAN_WRITE_INTERLACE */
  10183. }
  10184. else if (strcmp(*argv, "--use-input-precision") == 0)
  10185. pm.use_input_precision = 1U;
  10186. else if (strcmp(*argv, "--use-calculation-precision") == 0)
  10187. pm.use_input_precision = 0;
  10188. else if (strcmp(*argv, "--calculations-use-input-precision") == 0)
  10189. pm.calculations_use_input_precision = 1U;
  10190. else if (strcmp(*argv, "--assume-16-bit-calculations") == 0)
  10191. pm.assume_16_bit_calculations = 1U;
  10192. else if (strcmp(*argv, "--calculations-follow-bit-depth") == 0)
  10193. pm.calculations_use_input_precision =
  10194. pm.assume_16_bit_calculations = 0;
  10195. else if (strcmp(*argv, "--exhaustive") == 0)
  10196. pm.test_exhaustive = 1;
  10197. else if (argc > 1 && strcmp(*argv, "--sbitlow") == 0)
  10198. --argc, pm.sbitlow = (png_byte)atoi(*++argv), catmore = 1;
  10199. else if (argc > 1 && strcmp(*argv, "--touch") == 0)
  10200. --argc, touch = *++argv, catmore = 1;
  10201. else if (argc > 1 && strncmp(*argv, "--max", 5) == 0)
  10202. {
  10203. --argc;
  10204. if (strcmp(5+*argv, "abs8") == 0)
  10205. pm.maxabs8 = atof(*++argv);
  10206. else if (strcmp(5+*argv, "abs16") == 0)
  10207. pm.maxabs16 = atof(*++argv);
  10208. else if (strcmp(5+*argv, "calc8") == 0)
  10209. pm.maxcalc8 = atof(*++argv);
  10210. else if (strcmp(5+*argv, "calc16") == 0)
  10211. pm.maxcalc16 = atof(*++argv);
  10212. else if (strcmp(5+*argv, "out8") == 0)
  10213. pm.maxout8 = atof(*++argv);
  10214. else if (strcmp(5+*argv, "out16") == 0)
  10215. pm.maxout16 = atof(*++argv);
  10216. else if (strcmp(5+*argv, "pc8") == 0)
  10217. pm.maxpc8 = atof(*++argv);
  10218. else if (strcmp(5+*argv, "pc16") == 0)
  10219. pm.maxpc16 = atof(*++argv);
  10220. else
  10221. {
  10222. fprintf(stderr, "pngvalid: %s: unknown 'max' option\n", *argv);
  10223. exit(99);
  10224. }
  10225. catmore = 1;
  10226. }
  10227. else if (strcmp(*argv, "--log8") == 0)
  10228. --argc, pm.log8 = atof(*++argv), catmore = 1;
  10229. else if (strcmp(*argv, "--log16") == 0)
  10230. --argc, pm.log16 = atof(*++argv), catmore = 1;
  10231. #ifdef PNG_SET_OPTION_SUPPORTED
  10232. else if (strncmp(*argv, "--option=", 9) == 0)
  10233. {
  10234. /* Syntax of the argument is <option>:{on|off} */
  10235. const char *arg = 9+*argv;
  10236. unsigned char option=0, setting=0;
  10237. #ifdef PNG_ARM_NEON
  10238. if (strncmp(arg, "arm-neon:", 9) == 0)
  10239. option = PNG_ARM_NEON, arg += 9;
  10240. else
  10241. #endif
  10242. #ifdef PNG_EXTENSIONS
  10243. if (strncmp(arg, "extensions:", 11) == 0)
  10244. option = PNG_EXTENSIONS, arg += 11;
  10245. else
  10246. #endif
  10247. #ifdef PNG_MAXIMUM_INFLATE_WINDOW
  10248. if (strncmp(arg, "max-inflate-window:", 19) == 0)
  10249. option = PNG_MAXIMUM_INFLATE_WINDOW, arg += 19;
  10250. else
  10251. #endif
  10252. {
  10253. fprintf(stderr, "pngvalid: %s: %s: unknown option\n", *argv, arg);
  10254. exit(99);
  10255. }
  10256. if (strcmp(arg, "off") == 0)
  10257. setting = PNG_OPTION_OFF;
  10258. else if (strcmp(arg, "on") == 0)
  10259. setting = PNG_OPTION_ON;
  10260. else
  10261. {
  10262. fprintf(stderr,
  10263. "pngvalid: %s: %s: unknown setting (use 'on' or 'off')\n",
  10264. *argv, arg);
  10265. exit(99);
  10266. }
  10267. pm.this.options[pm.this.noptions].option = option;
  10268. pm.this.options[pm.this.noptions++].setting = setting;
  10269. }
  10270. #endif /* PNG_SET_OPTION_SUPPORTED */
  10271. else
  10272. {
  10273. fprintf(stderr, "pngvalid: %s: unknown argument\n", *argv);
  10274. exit(99);
  10275. }
  10276. if (catmore) /* consumed an extra *argv */
  10277. {
  10278. cp = safecat(command, sizeof command, cp, " ");
  10279. cp = safecat(command, sizeof command, cp, *argv);
  10280. }
  10281. }
  10282. /* If pngvalid is run with no arguments default to a reasonable set of the
  10283. * tests.
  10284. */
  10285. if (pm.test_standard == 0 && pm.test_size == 0 && pm.test_transform == 0 &&
  10286. pm.ngamma_tests == 0)
  10287. {
  10288. /* Make this do all the tests done in the test shell scripts with the same
  10289. * parameters, where possible. The limitation is that all the progressive
  10290. * read and interlace stuff has to be done in separate runs, so only the
  10291. * basic 'standard' and 'size' tests are done.
  10292. */
  10293. pm.test_standard = 1;
  10294. pm.test_size = 1;
  10295. pm.test_transform = 1;
  10296. pm.ngamma_tests = 2U;
  10297. }
  10298. if (pm.ngamma_tests > 0 &&
  10299. pm.test_gamma_threshold == 0 && pm.test_gamma_transform == 0 &&
  10300. pm.test_gamma_sbit == 0 && pm.test_gamma_scale16 == 0 &&
  10301. pm.test_gamma_background == 0 && pm.test_gamma_alpha_mode == 0)
  10302. {
  10303. pm.test_gamma_threshold = 1;
  10304. pm.test_gamma_transform = 1;
  10305. pm.test_gamma_sbit = 1;
  10306. pm.test_gamma_scale16 = 1;
  10307. pm.test_gamma_background = 1;
  10308. pm.test_gamma_alpha_mode = 1;
  10309. }
  10310. else if (pm.ngamma_tests == 0)
  10311. {
  10312. /* Nothing to test so turn everything off: */
  10313. pm.test_gamma_threshold = 0;
  10314. pm.test_gamma_transform = 0;
  10315. pm.test_gamma_sbit = 0;
  10316. pm.test_gamma_scale16 = 0;
  10317. pm.test_gamma_background = 0;
  10318. pm.test_gamma_alpha_mode = 0;
  10319. }
  10320. Try
  10321. {
  10322. /* Make useful base images */
  10323. make_transform_images(&pm);
  10324. /* Perform the standard and gamma tests. */
  10325. if (pm.test_standard)
  10326. {
  10327. perform_interlace_macro_validation();
  10328. perform_formatting_test(&pm.this);
  10329. # ifdef PNG_READ_SUPPORTED
  10330. perform_standard_test(&pm);
  10331. # endif
  10332. perform_error_test(&pm);
  10333. }
  10334. /* Various oddly sized images: */
  10335. if (pm.test_size)
  10336. {
  10337. make_size_images(&pm.this);
  10338. # ifdef PNG_READ_SUPPORTED
  10339. perform_size_test(&pm);
  10340. # endif
  10341. }
  10342. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  10343. /* Combinatorial transforms: */
  10344. if (pm.test_transform)
  10345. perform_transform_test(&pm);
  10346. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  10347. #ifdef PNG_READ_GAMMA_SUPPORTED
  10348. if (pm.ngamma_tests > 0)
  10349. perform_gamma_test(&pm, summary);
  10350. #endif
  10351. }
  10352. Catch_anonymous
  10353. {
  10354. fprintf(stderr, "pngvalid: test aborted (probably failed in cleanup)\n");
  10355. if (!pm.this.verbose)
  10356. {
  10357. if (pm.this.error[0] != 0)
  10358. fprintf(stderr, "pngvalid: first error: %s\n", pm.this.error);
  10359. fprintf(stderr, "pngvalid: run with -v to see what happened\n");
  10360. }
  10361. exit(1);
  10362. }
  10363. if (summary)
  10364. {
  10365. printf("%s: %s (%s point arithmetic)\n",
  10366. (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  10367. pm.this.nwarnings)) ? "FAIL" : "PASS",
  10368. command,
  10369. #if defined(PNG_FLOATING_ARITHMETIC_SUPPORTED) || PNG_LIBPNG_VER < 10500
  10370. "floating"
  10371. #else
  10372. "fixed"
  10373. #endif
  10374. );
  10375. }
  10376. if (memstats)
  10377. {
  10378. printf("Allocated memory statistics (in bytes):\n"
  10379. "\tread %lu maximum single, %lu peak, %lu total\n"
  10380. "\twrite %lu maximum single, %lu peak, %lu total\n",
  10381. (unsigned long)pm.this.read_memory_pool.max_max,
  10382. (unsigned long)pm.this.read_memory_pool.max_limit,
  10383. (unsigned long)pm.this.read_memory_pool.max_total,
  10384. (unsigned long)pm.this.write_memory_pool.max_max,
  10385. (unsigned long)pm.this.write_memory_pool.max_limit,
  10386. (unsigned long)pm.this.write_memory_pool.max_total);
  10387. }
  10388. /* Do this here to provoke memory corruption errors in memory not directly
  10389. * allocated by libpng - not a complete test, but better than nothing.
  10390. */
  10391. store_delete(&pm.this);
  10392. /* Error exit if there are any errors, and maybe if there are any
  10393. * warnings.
  10394. */
  10395. if (pm.this.nerrors || (pm.this.treat_warnings_as_errors &&
  10396. pm.this.nwarnings))
  10397. {
  10398. if (!pm.this.verbose)
  10399. fprintf(stderr, "pngvalid: %s\n", pm.this.error);
  10400. fprintf(stderr, "pngvalid: %d errors, %d warnings\n", pm.this.nerrors,
  10401. pm.this.nwarnings);
  10402. exit(1);
  10403. }
  10404. /* Success case. */
  10405. if (touch != NULL)
  10406. {
  10407. FILE *fsuccess = fopen(touch, "wt");
  10408. if (fsuccess != NULL)
  10409. {
  10410. int error = 0;
  10411. fprintf(fsuccess, "PNG validation succeeded\n");
  10412. fflush(fsuccess);
  10413. error = ferror(fsuccess);
  10414. if (fclose(fsuccess) || error)
  10415. {
  10416. fprintf(stderr, "%s: write failed\n", touch);
  10417. exit(1);
  10418. }
  10419. }
  10420. else
  10421. {
  10422. fprintf(stderr, "%s: open failed\n", touch);
  10423. exit(1);
  10424. }
  10425. }
  10426. /* This is required because some very minimal configurations do not use it:
  10427. */
  10428. UNUSED(fail)
  10429. return 0;
  10430. }
  10431. #else /* write or low level APIs not supported */
  10432. int main(void)
  10433. {
  10434. fprintf(stderr,
  10435. "pngvalid: no low level write support in libpng, all tests skipped\n");
  10436. /* So the test is skipped: */
  10437. return SKIP;
  10438. }
  10439. #endif