jpgd.cpp 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230
  1. // jpgd.cpp - C++ class for JPEG decompression. Written by Richard Geldreich <[email protected]> between 1994-2020.
  2. // Supports progressive and baseline sequential JPEG image files, and the most common chroma subsampling factors: Y, H1V1, H2V1, H1V2, and H2V2.
  3. // Supports box and linear chroma upsampling.
  4. //
  5. // Released under two licenses. You are free to choose which license you want:
  6. // License 1:
  7. // Public Domain
  8. //
  9. // License 2:
  10. // Licensed under the Apache License, Version 2.0 (the "License");
  11. // you may not use this file except in compliance with the License.
  12. // You may obtain a copy of the License at
  13. //
  14. // http://www.apache.org/licenses/LICENSE-2.0
  15. //
  16. // Unless required by applicable law or agreed to in writing, software
  17. // distributed under the License is distributed on an "AS IS" BASIS,
  18. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. // See the License for the specific language governing permissions and
  20. // limitations under the License.
  21. //
  22. // Alex Evans: Linear memory allocator (taken from jpge.h).
  23. // v1.04, May. 19, 2012: Code tweaks to fix VS2008 static code analysis warnings
  24. // v2.00, March 20, 2020: Fuzzed with zzuf and afl. Fixed several issues, converted most assert()'s to run-time checks. Added chroma upsampling. Removed freq. domain upsampling. gcc/clang warnings.
  25. //
  26. #include "jpgd.h"
  27. #include <string.h>
  28. #include <algorithm>
  29. #include <assert.h>
  30. #ifdef _MSC_VER
  31. #pragma warning (disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable
  32. #endif
  33. #define JPGD_TRUE (1)
  34. #define JPGD_FALSE (0)
  35. #define JPGD_MAX(a,b) (((a)>(b)) ? (a) : (b))
  36. #define JPGD_MIN(a,b) (((a)<(b)) ? (a) : (b))
  37. namespace jpgd {
  38. static inline void* jpgd_malloc(size_t nSize) { return malloc(nSize); }
  39. static inline void jpgd_free(void* p) { free(p); }
  40. // DCT coefficients are stored in this sequence.
  41. static int g_ZAG[64] = { 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 };
  42. enum JPEG_MARKER
  43. {
  44. M_SOF0 = 0xC0, M_SOF1 = 0xC1, M_SOF2 = 0xC2, M_SOF3 = 0xC3, M_SOF5 = 0xC5, M_SOF6 = 0xC6, M_SOF7 = 0xC7, M_JPG = 0xC8,
  45. M_SOF9 = 0xC9, M_SOF10 = 0xCA, M_SOF11 = 0xCB, M_SOF13 = 0xCD, M_SOF14 = 0xCE, M_SOF15 = 0xCF, M_DHT = 0xC4, M_DAC = 0xCC,
  46. M_RST0 = 0xD0, M_RST1 = 0xD1, M_RST2 = 0xD2, M_RST3 = 0xD3, M_RST4 = 0xD4, M_RST5 = 0xD5, M_RST6 = 0xD6, M_RST7 = 0xD7,
  47. M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_DNL = 0xDC, M_DRI = 0xDD, M_DHP = 0xDE, M_EXP = 0xDF,
  48. M_APP0 = 0xE0, M_APP15 = 0xEF, M_JPG0 = 0xF0, M_JPG13 = 0xFD, M_COM = 0xFE, M_TEM = 0x01, M_ERROR = 0x100, RST0 = 0xD0
  49. };
  50. enum JPEG_SUBSAMPLING { JPGD_GRAYSCALE = 0, JPGD_YH1V1, JPGD_YH2V1, JPGD_YH1V2, JPGD_YH2V2 };
  51. #define CONST_BITS 13
  52. #define PASS1_BITS 2
  53. #define SCALEDONE ((int32)1)
  54. #define FIX_0_298631336 ((int32)2446) /* FIX(0.298631336) */
  55. #define FIX_0_390180644 ((int32)3196) /* FIX(0.390180644) */
  56. #define FIX_0_541196100 ((int32)4433) /* FIX(0.541196100) */
  57. #define FIX_0_765366865 ((int32)6270) /* FIX(0.765366865) */
  58. #define FIX_0_899976223 ((int32)7373) /* FIX(0.899976223) */
  59. #define FIX_1_175875602 ((int32)9633) /* FIX(1.175875602) */
  60. #define FIX_1_501321110 ((int32)12299) /* FIX(1.501321110) */
  61. #define FIX_1_847759065 ((int32)15137) /* FIX(1.847759065) */
  62. #define FIX_1_961570560 ((int32)16069) /* FIX(1.961570560) */
  63. #define FIX_2_053119869 ((int32)16819) /* FIX(2.053119869) */
  64. #define FIX_2_562915447 ((int32)20995) /* FIX(2.562915447) */
  65. #define FIX_3_072711026 ((int32)25172) /* FIX(3.072711026) */
  66. #define DESCALE(x,n) (((x) + (SCALEDONE << ((n)-1))) >> (n))
  67. #define DESCALE_ZEROSHIFT(x,n) (((x) + (128 << (n)) + (SCALEDONE << ((n)-1))) >> (n))
  68. #define MULTIPLY(var, cnst) ((var) * (cnst))
  69. #define CLAMP(i) ((static_cast<uint>(i) > 255) ? (((~i) >> 31) & 0xFF) : (i))
  70. static inline int left_shifti(int val, uint32_t bits)
  71. {
  72. return static_cast<int>(static_cast<uint32_t>(val) << bits);
  73. }
  74. // Compiler creates a fast path 1D IDCT for X non-zero columns
  75. template <int NONZERO_COLS>
  76. struct Row
  77. {
  78. static void idct(int* pTemp, const jpgd_block_t* pSrc)
  79. {
  80. // ACCESS_COL() will be optimized at compile time to either an array access, or 0. Good compilers will then optimize out muls against 0.
  81. #define ACCESS_COL(x) (((x) < NONZERO_COLS) ? (int)pSrc[x] : 0)
  82. const int z2 = ACCESS_COL(2), z3 = ACCESS_COL(6);
  83. const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  84. const int tmp2 = z1 + MULTIPLY(z3, -FIX_1_847759065);
  85. const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  86. const int tmp0 = left_shifti(ACCESS_COL(0) + ACCESS_COL(4), CONST_BITS);
  87. const int tmp1 = left_shifti(ACCESS_COL(0) - ACCESS_COL(4), CONST_BITS);
  88. const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
  89. const int atmp0 = ACCESS_COL(7), atmp1 = ACCESS_COL(5), atmp2 = ACCESS_COL(3), atmp3 = ACCESS_COL(1);
  90. const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
  91. const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
  92. const int az1 = MULTIPLY(bz1, -FIX_0_899976223);
  93. const int az2 = MULTIPLY(bz2, -FIX_2_562915447);
  94. const int az3 = MULTIPLY(bz3, -FIX_1_961570560) + bz5;
  95. const int az4 = MULTIPLY(bz4, -FIX_0_390180644) + bz5;
  96. const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
  97. const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
  98. const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
  99. const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
  100. pTemp[0] = DESCALE(tmp10 + btmp3, CONST_BITS - PASS1_BITS);
  101. pTemp[7] = DESCALE(tmp10 - btmp3, CONST_BITS - PASS1_BITS);
  102. pTemp[1] = DESCALE(tmp11 + btmp2, CONST_BITS - PASS1_BITS);
  103. pTemp[6] = DESCALE(tmp11 - btmp2, CONST_BITS - PASS1_BITS);
  104. pTemp[2] = DESCALE(tmp12 + btmp1, CONST_BITS - PASS1_BITS);
  105. pTemp[5] = DESCALE(tmp12 - btmp1, CONST_BITS - PASS1_BITS);
  106. pTemp[3] = DESCALE(tmp13 + btmp0, CONST_BITS - PASS1_BITS);
  107. pTemp[4] = DESCALE(tmp13 - btmp0, CONST_BITS - PASS1_BITS);
  108. }
  109. };
  110. template <>
  111. struct Row<0>
  112. {
  113. static void idct(int* pTemp, const jpgd_block_t* pSrc)
  114. {
  115. (void)pTemp;
  116. (void)pSrc;
  117. }
  118. };
  119. template <>
  120. struct Row<1>
  121. {
  122. static void idct(int* pTemp, const jpgd_block_t* pSrc)
  123. {
  124. const int dcval = left_shifti(pSrc[0], PASS1_BITS);
  125. pTemp[0] = dcval;
  126. pTemp[1] = dcval;
  127. pTemp[2] = dcval;
  128. pTemp[3] = dcval;
  129. pTemp[4] = dcval;
  130. pTemp[5] = dcval;
  131. pTemp[6] = dcval;
  132. pTemp[7] = dcval;
  133. }
  134. };
  135. // Compiler creates a fast path 1D IDCT for X non-zero rows
  136. template <int NONZERO_ROWS>
  137. struct Col
  138. {
  139. static void idct(uint8* pDst_ptr, const int* pTemp)
  140. {
  141. // ACCESS_ROW() will be optimized at compile time to either an array access, or 0.
  142. #define ACCESS_ROW(x) (((x) < NONZERO_ROWS) ? pTemp[x * 8] : 0)
  143. const int z2 = ACCESS_ROW(2);
  144. const int z3 = ACCESS_ROW(6);
  145. const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  146. const int tmp2 = z1 + MULTIPLY(z3, -FIX_1_847759065);
  147. const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  148. const int tmp0 = left_shifti(ACCESS_ROW(0) + ACCESS_ROW(4), CONST_BITS);
  149. const int tmp1 = left_shifti(ACCESS_ROW(0) - ACCESS_ROW(4), CONST_BITS);
  150. const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
  151. const int atmp0 = ACCESS_ROW(7), atmp1 = ACCESS_ROW(5), atmp2 = ACCESS_ROW(3), atmp3 = ACCESS_ROW(1);
  152. const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
  153. const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
  154. const int az1 = MULTIPLY(bz1, -FIX_0_899976223);
  155. const int az2 = MULTIPLY(bz2, -FIX_2_562915447);
  156. const int az3 = MULTIPLY(bz3, -FIX_1_961570560) + bz5;
  157. const int az4 = MULTIPLY(bz4, -FIX_0_390180644) + bz5;
  158. const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
  159. const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
  160. const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
  161. const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
  162. int i = DESCALE_ZEROSHIFT(tmp10 + btmp3, CONST_BITS + PASS1_BITS + 3);
  163. pDst_ptr[8 * 0] = (uint8)CLAMP(i);
  164. i = DESCALE_ZEROSHIFT(tmp10 - btmp3, CONST_BITS + PASS1_BITS + 3);
  165. pDst_ptr[8 * 7] = (uint8)CLAMP(i);
  166. i = DESCALE_ZEROSHIFT(tmp11 + btmp2, CONST_BITS + PASS1_BITS + 3);
  167. pDst_ptr[8 * 1] = (uint8)CLAMP(i);
  168. i = DESCALE_ZEROSHIFT(tmp11 - btmp2, CONST_BITS + PASS1_BITS + 3);
  169. pDst_ptr[8 * 6] = (uint8)CLAMP(i);
  170. i = DESCALE_ZEROSHIFT(tmp12 + btmp1, CONST_BITS + PASS1_BITS + 3);
  171. pDst_ptr[8 * 2] = (uint8)CLAMP(i);
  172. i = DESCALE_ZEROSHIFT(tmp12 - btmp1, CONST_BITS + PASS1_BITS + 3);
  173. pDst_ptr[8 * 5] = (uint8)CLAMP(i);
  174. i = DESCALE_ZEROSHIFT(tmp13 + btmp0, CONST_BITS + PASS1_BITS + 3);
  175. pDst_ptr[8 * 3] = (uint8)CLAMP(i);
  176. i = DESCALE_ZEROSHIFT(tmp13 - btmp0, CONST_BITS + PASS1_BITS + 3);
  177. pDst_ptr[8 * 4] = (uint8)CLAMP(i);
  178. }
  179. };
  180. template <>
  181. struct Col<1>
  182. {
  183. static void idct(uint8* pDst_ptr, const int* pTemp)
  184. {
  185. int dcval = DESCALE_ZEROSHIFT(pTemp[0], PASS1_BITS + 3);
  186. const uint8 dcval_clamped = (uint8)CLAMP(dcval);
  187. pDst_ptr[0 * 8] = dcval_clamped;
  188. pDst_ptr[1 * 8] = dcval_clamped;
  189. pDst_ptr[2 * 8] = dcval_clamped;
  190. pDst_ptr[3 * 8] = dcval_clamped;
  191. pDst_ptr[4 * 8] = dcval_clamped;
  192. pDst_ptr[5 * 8] = dcval_clamped;
  193. pDst_ptr[6 * 8] = dcval_clamped;
  194. pDst_ptr[7 * 8] = dcval_clamped;
  195. }
  196. };
  197. static const uint8 s_idct_row_table[] =
  198. {
  199. 1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 2,1,0,0,0,0,0,0, 2,1,1,0,0,0,0,0, 2,2,1,0,0,0,0,0, 3,2,1,0,0,0,0,0, 4,2,1,0,0,0,0,0, 4,3,1,0,0,0,0,0,
  200. 4,3,2,0,0,0,0,0, 4,3,2,1,0,0,0,0, 4,3,2,1,1,0,0,0, 4,3,2,2,1,0,0,0, 4,3,3,2,1,0,0,0, 4,4,3,2,1,0,0,0, 5,4,3,2,1,0,0,0, 6,4,3,2,1,0,0,0,
  201. 6,5,3,2,1,0,0,0, 6,5,4,2,1,0,0,0, 6,5,4,3,1,0,0,0, 6,5,4,3,2,0,0,0, 6,5,4,3,2,1,0,0, 6,5,4,3,2,1,1,0, 6,5,4,3,2,2,1,0, 6,5,4,3,3,2,1,0,
  202. 6,5,4,4,3,2,1,0, 6,5,5,4,3,2,1,0, 6,6,5,4,3,2,1,0, 7,6,5,4,3,2,1,0, 8,6,5,4,3,2,1,0, 8,7,5,4,3,2,1,0, 8,7,6,4,3,2,1,0, 8,7,6,5,3,2,1,0,
  203. 8,7,6,5,4,2,1,0, 8,7,6,5,4,3,1,0, 8,7,6,5,4,3,2,0, 8,7,6,5,4,3,2,1, 8,7,6,5,4,3,2,2, 8,7,6,5,4,3,3,2, 8,7,6,5,4,4,3,2, 8,7,6,5,5,4,3,2,
  204. 8,7,6,6,5,4,3,2, 8,7,7,6,5,4,3,2, 8,8,7,6,5,4,3,2, 8,8,8,6,5,4,3,2, 8,8,8,7,5,4,3,2, 8,8,8,7,6,4,3,2, 8,8,8,7,6,5,3,2, 8,8,8,7,6,5,4,2,
  205. 8,8,8,7,6,5,4,3, 8,8,8,7,6,5,4,4, 8,8,8,7,6,5,5,4, 8,8,8,7,6,6,5,4, 8,8,8,7,7,6,5,4, 8,8,8,8,7,6,5,4, 8,8,8,8,8,6,5,4, 8,8,8,8,8,7,5,4,
  206. 8,8,8,8,8,7,6,4, 8,8,8,8,8,7,6,5, 8,8,8,8,8,7,6,6, 8,8,8,8,8,7,7,6, 8,8,8,8,8,8,7,6, 8,8,8,8,8,8,8,6, 8,8,8,8,8,8,8,7, 8,8,8,8,8,8,8,8,
  207. };
  208. static const uint8 s_idct_col_table[] =
  209. {
  210. 1, 1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  211. 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
  212. };
  213. // Scalar "fast pathing" IDCT.
  214. static void idct(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr, int block_max_zag)
  215. {
  216. assert(block_max_zag >= 1);
  217. assert(block_max_zag <= 64);
  218. if (block_max_zag <= 1)
  219. {
  220. int k = ((pSrc_ptr[0] + 4) >> 3) + 128;
  221. k = CLAMP(k);
  222. k = k | (k << 8);
  223. k = k | (k << 16);
  224. for (int i = 8; i > 0; i--)
  225. {
  226. *(int*)&pDst_ptr[0] = k;
  227. *(int*)&pDst_ptr[4] = k;
  228. pDst_ptr += 8;
  229. }
  230. return;
  231. }
  232. int temp[64];
  233. const jpgd_block_t* pSrc = pSrc_ptr;
  234. int* pTemp = temp;
  235. const uint8* pRow_tab = &s_idct_row_table[(block_max_zag - 1) * 8];
  236. int i;
  237. for (i = 8; i > 0; i--, pRow_tab++)
  238. {
  239. switch (*pRow_tab)
  240. {
  241. case 0: Row<0>::idct(pTemp, pSrc); break;
  242. case 1: Row<1>::idct(pTemp, pSrc); break;
  243. case 2: Row<2>::idct(pTemp, pSrc); break;
  244. case 3: Row<3>::idct(pTemp, pSrc); break;
  245. case 4: Row<4>::idct(pTemp, pSrc); break;
  246. case 5: Row<5>::idct(pTemp, pSrc); break;
  247. case 6: Row<6>::idct(pTemp, pSrc); break;
  248. case 7: Row<7>::idct(pTemp, pSrc); break;
  249. case 8: Row<8>::idct(pTemp, pSrc); break;
  250. }
  251. pSrc += 8;
  252. pTemp += 8;
  253. }
  254. pTemp = temp;
  255. const int nonzero_rows = s_idct_col_table[block_max_zag - 1];
  256. for (i = 8; i > 0; i--)
  257. {
  258. switch (nonzero_rows)
  259. {
  260. case 1: Col<1>::idct(pDst_ptr, pTemp); break;
  261. case 2: Col<2>::idct(pDst_ptr, pTemp); break;
  262. case 3: Col<3>::idct(pDst_ptr, pTemp); break;
  263. case 4: Col<4>::idct(pDst_ptr, pTemp); break;
  264. case 5: Col<5>::idct(pDst_ptr, pTemp); break;
  265. case 6: Col<6>::idct(pDst_ptr, pTemp); break;
  266. case 7: Col<7>::idct(pDst_ptr, pTemp); break;
  267. case 8: Col<8>::idct(pDst_ptr, pTemp); break;
  268. }
  269. pTemp++;
  270. pDst_ptr++;
  271. }
  272. }
  273. // Retrieve one character from the input stream.
  274. inline uint jpeg_decoder::get_char()
  275. {
  276. // Any bytes remaining in buffer?
  277. if (!m_in_buf_left)
  278. {
  279. // Try to get more bytes.
  280. prep_in_buffer();
  281. // Still nothing to get?
  282. if (!m_in_buf_left)
  283. {
  284. // Pad the end of the stream with 0xFF 0xD9 (EOI marker)
  285. int t = m_tem_flag;
  286. m_tem_flag ^= 1;
  287. if (t)
  288. return 0xD9;
  289. else
  290. return 0xFF;
  291. }
  292. }
  293. uint c = *m_pIn_buf_ofs++;
  294. m_in_buf_left--;
  295. return c;
  296. }
  297. // Same as previous method, except can indicate if the character is a pad character or not.
  298. inline uint jpeg_decoder::get_char(bool* pPadding_flag)
  299. {
  300. if (!m_in_buf_left)
  301. {
  302. prep_in_buffer();
  303. if (!m_in_buf_left)
  304. {
  305. *pPadding_flag = true;
  306. int t = m_tem_flag;
  307. m_tem_flag ^= 1;
  308. if (t)
  309. return 0xD9;
  310. else
  311. return 0xFF;
  312. }
  313. }
  314. *pPadding_flag = false;
  315. uint c = *m_pIn_buf_ofs++;
  316. m_in_buf_left--;
  317. return c;
  318. }
  319. // Inserts a previously retrieved character back into the input buffer.
  320. inline void jpeg_decoder::stuff_char(uint8 q)
  321. {
  322. // This could write before the input buffer, but we've placed another array there.
  323. *(--m_pIn_buf_ofs) = q;
  324. m_in_buf_left++;
  325. }
  326. // Retrieves one character from the input stream, but does not read past markers. Will continue to return 0xFF when a marker is encountered.
  327. inline uint8 jpeg_decoder::get_octet()
  328. {
  329. bool padding_flag;
  330. int c = get_char(&padding_flag);
  331. if (c == 0xFF)
  332. {
  333. if (padding_flag)
  334. return 0xFF;
  335. c = get_char(&padding_flag);
  336. if (padding_flag)
  337. {
  338. stuff_char(0xFF);
  339. return 0xFF;
  340. }
  341. if (c == 0x00)
  342. return 0xFF;
  343. else
  344. {
  345. stuff_char(static_cast<uint8>(c));
  346. stuff_char(0xFF);
  347. return 0xFF;
  348. }
  349. }
  350. return static_cast<uint8>(c);
  351. }
  352. // Retrieves a variable number of bits from the input stream. Does not recognize markers.
  353. inline uint jpeg_decoder::get_bits(int num_bits)
  354. {
  355. if (!num_bits)
  356. return 0;
  357. uint i = m_bit_buf >> (32 - num_bits);
  358. if ((m_bits_left -= num_bits) <= 0)
  359. {
  360. m_bit_buf <<= (num_bits += m_bits_left);
  361. uint c1 = get_char();
  362. uint c2 = get_char();
  363. m_bit_buf = (m_bit_buf & 0xFFFF0000) | (c1 << 8) | c2;
  364. m_bit_buf <<= -m_bits_left;
  365. m_bits_left += 16;
  366. assert(m_bits_left >= 0);
  367. }
  368. else
  369. m_bit_buf <<= num_bits;
  370. return i;
  371. }
  372. // Retrieves a variable number of bits from the input stream. Markers will not be read into the input bit buffer. Instead, an infinite number of all 1's will be returned when a marker is encountered.
  373. inline uint jpeg_decoder::get_bits_no_markers(int num_bits)
  374. {
  375. if (!num_bits)
  376. return 0;
  377. assert(num_bits <= 16);
  378. uint i = m_bit_buf >> (32 - num_bits);
  379. if ((m_bits_left -= num_bits) <= 0)
  380. {
  381. m_bit_buf <<= (num_bits += m_bits_left);
  382. if ((m_in_buf_left < 2) || (m_pIn_buf_ofs[0] == 0xFF) || (m_pIn_buf_ofs[1] == 0xFF))
  383. {
  384. uint c1 = get_octet();
  385. uint c2 = get_octet();
  386. m_bit_buf |= (c1 << 8) | c2;
  387. }
  388. else
  389. {
  390. m_bit_buf |= ((uint)m_pIn_buf_ofs[0] << 8) | m_pIn_buf_ofs[1];
  391. m_in_buf_left -= 2;
  392. m_pIn_buf_ofs += 2;
  393. }
  394. m_bit_buf <<= -m_bits_left;
  395. m_bits_left += 16;
  396. assert(m_bits_left >= 0);
  397. }
  398. else
  399. m_bit_buf <<= num_bits;
  400. return i;
  401. }
  402. // Decodes a Huffman encoded symbol.
  403. inline int jpeg_decoder::huff_decode(huff_tables* pH)
  404. {
  405. if (!pH)
  406. stop_decoding(JPGD_DECODE_ERROR);
  407. int symbol;
  408. // Check first 8-bits: do we have a complete symbol?
  409. if ((symbol = pH->look_up[m_bit_buf >> 24]) < 0)
  410. {
  411. // Decode more bits, use a tree traversal to find symbol.
  412. int ofs = 23;
  413. do
  414. {
  415. unsigned int idx = -(int)(symbol + ((m_bit_buf >> ofs) & 1));
  416. // This should never happen, but to be safe I'm turning these asserts into a run-time check.
  417. if ((idx >= JPGD_HUFF_TREE_MAX_LENGTH) || (ofs < 0))
  418. stop_decoding(JPGD_DECODE_ERROR);
  419. symbol = pH->tree[idx];
  420. ofs--;
  421. } while (symbol < 0);
  422. get_bits_no_markers(8 + (23 - ofs));
  423. }
  424. else
  425. {
  426. assert(symbol < JPGD_HUFF_CODE_SIZE_MAX_LENGTH);
  427. get_bits_no_markers(pH->code_size[symbol]);
  428. }
  429. return symbol;
  430. }
  431. // Decodes a Huffman encoded symbol.
  432. inline int jpeg_decoder::huff_decode(huff_tables* pH, int& extra_bits)
  433. {
  434. int symbol;
  435. if (!pH)
  436. stop_decoding(JPGD_DECODE_ERROR);
  437. // Check first 8-bits: do we have a complete symbol?
  438. if ((symbol = pH->look_up2[m_bit_buf >> 24]) < 0)
  439. {
  440. // Use a tree traversal to find symbol.
  441. int ofs = 23;
  442. do
  443. {
  444. unsigned int idx = -(int)(symbol + ((m_bit_buf >> ofs) & 1));
  445. // This should never happen, but to be safe I'm turning these asserts into a run-time check.
  446. if ((idx >= JPGD_HUFF_TREE_MAX_LENGTH) || (ofs < 0))
  447. stop_decoding(JPGD_DECODE_ERROR);
  448. symbol = pH->tree[idx];
  449. ofs--;
  450. } while (symbol < 0);
  451. get_bits_no_markers(8 + (23 - ofs));
  452. extra_bits = get_bits_no_markers(symbol & 0xF);
  453. }
  454. else
  455. {
  456. if (symbol & 0x8000)
  457. {
  458. //get_bits_no_markers((symbol >> 8) & 31);
  459. assert(((symbol >> 8) & 31) <= 15);
  460. get_bits_no_markers((symbol >> 8) & 15);
  461. extra_bits = symbol >> 16;
  462. }
  463. else
  464. {
  465. int code_size = (symbol >> 8) & 31;
  466. int num_extra_bits = symbol & 0xF;
  467. int bits = code_size + num_extra_bits;
  468. if (bits <= 16)
  469. extra_bits = get_bits_no_markers(bits) & ((1 << num_extra_bits) - 1);
  470. else
  471. {
  472. get_bits_no_markers(code_size);
  473. extra_bits = get_bits_no_markers(num_extra_bits);
  474. }
  475. }
  476. symbol &= 0xFF;
  477. }
  478. return symbol;
  479. }
  480. // Tables and macro used to fully decode the DPCM differences.
  481. static const int s_extend_test[16] = { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  482. static const int s_extend_offset[16] = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767 };
  483. //static const int s_extend_mask[] = { 0, (1 << 0), (1 << 1), (1 << 2), (1 << 3), (1 << 4), (1 << 5), (1 << 6), (1 << 7), (1 << 8), (1 << 9), (1 << 10), (1 << 11), (1 << 12), (1 << 13), (1 << 14), (1 << 15), (1 << 16) };
  484. #define JPGD_HUFF_EXTEND(x, s) (((x) < s_extend_test[s & 15]) ? ((x) + s_extend_offset[s & 15]) : (x))
  485. // Unconditionally frees all allocated m_blocks.
  486. void jpeg_decoder::free_all_blocks()
  487. {
  488. m_pStream = nullptr;
  489. for (mem_block* b = m_pMem_blocks; b; )
  490. {
  491. mem_block* n = b->m_pNext;
  492. jpgd_free(b);
  493. b = n;
  494. }
  495. m_pMem_blocks = nullptr;
  496. }
  497. // This method handles all errors. It will never return.
  498. // It could easily be changed to use C++ exceptions.
  499. JPGD_NORETURN void jpeg_decoder::stop_decoding(jpgd_status status)
  500. {
  501. m_error_code = status;
  502. free_all_blocks();
  503. longjmp(m_jmp_state, status);
  504. }
  505. void* jpeg_decoder::alloc(size_t nSize, bool zero)
  506. {
  507. nSize = (JPGD_MAX(nSize, 1) + 3) & ~3;
  508. char* rv = nullptr;
  509. for (mem_block* b = m_pMem_blocks; b; b = b->m_pNext)
  510. {
  511. if ((b->m_used_count + nSize) <= b->m_size)
  512. {
  513. rv = b->m_data + b->m_used_count;
  514. b->m_used_count += nSize;
  515. break;
  516. }
  517. }
  518. if (!rv)
  519. {
  520. int capacity = JPGD_MAX(32768 - 256, ((int)nSize + 2047) & ~2047);
  521. mem_block* b = (mem_block*)jpgd_malloc(sizeof(mem_block) + capacity);
  522. if (!b)
  523. {
  524. stop_decoding(JPGD_NOTENOUGHMEM);
  525. }
  526. b->m_pNext = m_pMem_blocks;
  527. m_pMem_blocks = b;
  528. b->m_used_count = nSize;
  529. b->m_size = capacity;
  530. rv = b->m_data;
  531. }
  532. if (zero) memset(rv, 0, nSize);
  533. return rv;
  534. }
  535. void jpeg_decoder::word_clear(void* p, uint16 c, uint n)
  536. {
  537. uint8* pD = (uint8*)p;
  538. const uint8 l = c & 0xFF, h = (c >> 8) & 0xFF;
  539. while (n)
  540. {
  541. pD[0] = l;
  542. pD[1] = h;
  543. pD += 2;
  544. n--;
  545. }
  546. }
  547. // Refill the input buffer.
  548. // This method will sit in a loop until (A) the buffer is full or (B)
  549. // the stream's read() method reports and end of file condition.
  550. void jpeg_decoder::prep_in_buffer()
  551. {
  552. m_in_buf_left = 0;
  553. m_pIn_buf_ofs = m_in_buf;
  554. if (m_eof_flag)
  555. return;
  556. do
  557. {
  558. int bytes_read = m_pStream->read(m_in_buf + m_in_buf_left, JPGD_IN_BUF_SIZE - m_in_buf_left, &m_eof_flag);
  559. if (bytes_read == -1)
  560. stop_decoding(JPGD_STREAM_READ);
  561. m_in_buf_left += bytes_read;
  562. } while ((m_in_buf_left < JPGD_IN_BUF_SIZE) && (!m_eof_flag));
  563. m_total_bytes_read += m_in_buf_left;
  564. // Pad the end of the block with M_EOI (prevents the decompressor from going off the rails if the stream is invalid).
  565. // (This dates way back to when this decompressor was written in C/asm, and the all-asm Huffman decoder did some fancy things to increase perf.)
  566. word_clear(m_pIn_buf_ofs + m_in_buf_left, 0xD9FF, 64);
  567. }
  568. // Read a Huffman code table.
  569. void jpeg_decoder::read_dht_marker()
  570. {
  571. int i, index, count;
  572. uint8 huff_num[17];
  573. uint8 huff_val[256];
  574. uint num_left = get_bits(16);
  575. if (num_left < 2)
  576. stop_decoding(JPGD_BAD_DHT_MARKER);
  577. num_left -= 2;
  578. while (num_left)
  579. {
  580. index = get_bits(8);
  581. huff_num[0] = 0;
  582. count = 0;
  583. for (i = 1; i <= 16; i++)
  584. {
  585. huff_num[i] = static_cast<uint8>(get_bits(8));
  586. count += huff_num[i];
  587. }
  588. if (count > 255)
  589. stop_decoding(JPGD_BAD_DHT_COUNTS);
  590. bool symbol_present[256];
  591. memset(symbol_present, 0, sizeof(symbol_present));
  592. for (i = 0; i < count; i++)
  593. {
  594. const int s = get_bits(8);
  595. // Check for obviously bogus tables.
  596. if (symbol_present[s])
  597. stop_decoding(JPGD_BAD_DHT_COUNTS);
  598. huff_val[i] = static_cast<uint8_t>(s);
  599. symbol_present[s] = true;
  600. }
  601. i = 1 + 16 + count;
  602. if (num_left < (uint)i)
  603. stop_decoding(JPGD_BAD_DHT_MARKER);
  604. num_left -= i;
  605. if ((index & 0x10) > 0x10)
  606. stop_decoding(JPGD_BAD_DHT_INDEX);
  607. index = (index & 0x0F) + ((index & 0x10) >> 4) * (JPGD_MAX_HUFF_TABLES >> 1);
  608. if (index >= JPGD_MAX_HUFF_TABLES)
  609. stop_decoding(JPGD_BAD_DHT_INDEX);
  610. if (!m_huff_num[index])
  611. m_huff_num[index] = (uint8*)alloc(17);
  612. if (!m_huff_val[index])
  613. m_huff_val[index] = (uint8*)alloc(256);
  614. m_huff_ac[index] = (index & 0x10) != 0;
  615. memcpy(m_huff_num[index], huff_num, 17);
  616. memcpy(m_huff_val[index], huff_val, 256);
  617. }
  618. }
  619. // Read a quantization table.
  620. void jpeg_decoder::read_dqt_marker()
  621. {
  622. int n, i, prec;
  623. uint num_left;
  624. uint temp;
  625. num_left = get_bits(16);
  626. if (num_left < 2)
  627. stop_decoding(JPGD_BAD_DQT_MARKER);
  628. num_left -= 2;
  629. while (num_left)
  630. {
  631. n = get_bits(8);
  632. prec = n >> 4;
  633. n &= 0x0F;
  634. if (n >= JPGD_MAX_QUANT_TABLES)
  635. stop_decoding(JPGD_BAD_DQT_TABLE);
  636. if (!m_quant[n])
  637. m_quant[n] = (jpgd_quant_t*)alloc(64 * sizeof(jpgd_quant_t));
  638. // read quantization entries, in zag order
  639. for (i = 0; i < 64; i++)
  640. {
  641. temp = get_bits(8);
  642. if (prec)
  643. temp = (temp << 8) + get_bits(8);
  644. m_quant[n][i] = static_cast<jpgd_quant_t>(temp);
  645. }
  646. i = 64 + 1;
  647. if (prec)
  648. i += 64;
  649. if (num_left < (uint)i)
  650. stop_decoding(JPGD_BAD_DQT_LENGTH);
  651. num_left -= i;
  652. }
  653. }
  654. // Read the start of frame (SOF) marker.
  655. void jpeg_decoder::read_sof_marker()
  656. {
  657. int i;
  658. uint num_left;
  659. num_left = get_bits(16);
  660. /* precision: sorry, only 8-bit precision is supported */
  661. if (get_bits(8) != 8)
  662. stop_decoding(JPGD_BAD_PRECISION);
  663. m_image_y_size = get_bits(16);
  664. if ((m_image_y_size < 1) || (m_image_y_size > JPGD_MAX_HEIGHT))
  665. stop_decoding(JPGD_BAD_HEIGHT);
  666. m_image_x_size = get_bits(16);
  667. if ((m_image_x_size < 1) || (m_image_x_size > JPGD_MAX_WIDTH))
  668. stop_decoding(JPGD_BAD_WIDTH);
  669. m_comps_in_frame = get_bits(8);
  670. if (m_comps_in_frame > JPGD_MAX_COMPONENTS)
  671. stop_decoding(JPGD_TOO_MANY_COMPONENTS);
  672. if (num_left != (uint)(m_comps_in_frame * 3 + 8))
  673. stop_decoding(JPGD_BAD_SOF_LENGTH);
  674. for (i = 0; i < m_comps_in_frame; i++)
  675. {
  676. m_comp_ident[i] = get_bits(8);
  677. m_comp_h_samp[i] = get_bits(4);
  678. m_comp_v_samp[i] = get_bits(4);
  679. if (!m_comp_h_samp[i] || !m_comp_v_samp[i] || (m_comp_h_samp[i] > 2) || (m_comp_v_samp[i] > 2))
  680. stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
  681. m_comp_quant[i] = get_bits(8);
  682. if (m_comp_quant[i] >= JPGD_MAX_QUANT_TABLES)
  683. stop_decoding(JPGD_DECODE_ERROR);
  684. }
  685. }
  686. // Used to skip unrecognized markers.
  687. void jpeg_decoder::skip_variable_marker()
  688. {
  689. uint num_left;
  690. num_left = get_bits(16);
  691. if (num_left < 2)
  692. stop_decoding(JPGD_BAD_VARIABLE_MARKER);
  693. num_left -= 2;
  694. while (num_left)
  695. {
  696. get_bits(8);
  697. num_left--;
  698. }
  699. }
  700. // Read a define restart interval (DRI) marker.
  701. void jpeg_decoder::read_dri_marker()
  702. {
  703. if (get_bits(16) != 4)
  704. stop_decoding(JPGD_BAD_DRI_LENGTH);
  705. m_restart_interval = get_bits(16);
  706. }
  707. // Read a start of scan (SOS) marker.
  708. void jpeg_decoder::read_sos_marker()
  709. {
  710. uint num_left;
  711. int i, ci, n, c, cc;
  712. num_left = get_bits(16);
  713. n = get_bits(8);
  714. m_comps_in_scan = n;
  715. num_left -= 3;
  716. if ((num_left != (uint)(n * 2 + 3)) || (n < 1) || (n > JPGD_MAX_COMPS_IN_SCAN))
  717. stop_decoding(JPGD_BAD_SOS_LENGTH);
  718. for (i = 0; i < n; i++)
  719. {
  720. cc = get_bits(8);
  721. c = get_bits(8);
  722. num_left -= 2;
  723. for (ci = 0; ci < m_comps_in_frame; ci++)
  724. if (cc == m_comp_ident[ci])
  725. break;
  726. if (ci >= m_comps_in_frame)
  727. stop_decoding(JPGD_BAD_SOS_COMP_ID);
  728. if (ci >= JPGD_MAX_COMPONENTS)
  729. stop_decoding(JPGD_DECODE_ERROR);
  730. m_comp_list[i] = ci;
  731. m_comp_dc_tab[ci] = (c >> 4) & 15;
  732. m_comp_ac_tab[ci] = (c & 15) + (JPGD_MAX_HUFF_TABLES >> 1);
  733. if (m_comp_dc_tab[ci] >= JPGD_MAX_HUFF_TABLES)
  734. stop_decoding(JPGD_DECODE_ERROR);
  735. if (m_comp_ac_tab[ci] >= JPGD_MAX_HUFF_TABLES)
  736. stop_decoding(JPGD_DECODE_ERROR);
  737. }
  738. m_spectral_start = get_bits(8);
  739. m_spectral_end = get_bits(8);
  740. m_successive_high = get_bits(4);
  741. m_successive_low = get_bits(4);
  742. if (!m_progressive_flag)
  743. {
  744. m_spectral_start = 0;
  745. m_spectral_end = 63;
  746. }
  747. num_left -= 3;
  748. /* read past whatever is num_left */
  749. while (num_left)
  750. {
  751. get_bits(8);
  752. num_left--;
  753. }
  754. }
  755. // Finds the next marker.
  756. int jpeg_decoder::next_marker()
  757. {
  758. uint c, bytes;
  759. bytes = 0;
  760. do
  761. {
  762. do
  763. {
  764. bytes++;
  765. c = get_bits(8);
  766. } while (c != 0xFF);
  767. do
  768. {
  769. c = get_bits(8);
  770. } while (c == 0xFF);
  771. } while (c == 0);
  772. // If bytes > 0 here, there where extra bytes before the marker (not good).
  773. return c;
  774. }
  775. // Process markers. Returns when an SOFx, SOI, EOI, or SOS marker is
  776. // encountered.
  777. int jpeg_decoder::process_markers()
  778. {
  779. int c;
  780. for (; ; )
  781. {
  782. c = next_marker();
  783. switch (c)
  784. {
  785. case M_SOF0:
  786. case M_SOF1:
  787. case M_SOF2:
  788. case M_SOF3:
  789. case M_SOF5:
  790. case M_SOF6:
  791. case M_SOF7:
  792. // case M_JPG:
  793. case M_SOF9:
  794. case M_SOF10:
  795. case M_SOF11:
  796. case M_SOF13:
  797. case M_SOF14:
  798. case M_SOF15:
  799. case M_SOI:
  800. case M_EOI:
  801. case M_SOS:
  802. {
  803. return c;
  804. }
  805. case M_DHT:
  806. {
  807. read_dht_marker();
  808. break;
  809. }
  810. // No arithmitic support - dumb patents!
  811. case M_DAC:
  812. {
  813. stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
  814. break;
  815. }
  816. case M_DQT:
  817. {
  818. read_dqt_marker();
  819. break;
  820. }
  821. case M_DRI:
  822. {
  823. read_dri_marker();
  824. break;
  825. }
  826. //case M_APP0: /* no need to read the JFIF marker */
  827. case M_JPG:
  828. case M_RST0: /* no parameters */
  829. case M_RST1:
  830. case M_RST2:
  831. case M_RST3:
  832. case M_RST4:
  833. case M_RST5:
  834. case M_RST6:
  835. case M_RST7:
  836. case M_TEM:
  837. {
  838. stop_decoding(JPGD_UNEXPECTED_MARKER);
  839. break;
  840. }
  841. default: /* must be DNL, DHP, EXP, APPn, JPGn, COM, or RESn or APP0 */
  842. {
  843. skip_variable_marker();
  844. break;
  845. }
  846. }
  847. }
  848. }
  849. // Finds the start of image (SOI) marker.
  850. void jpeg_decoder::locate_soi_marker()
  851. {
  852. uint lastchar, thischar;
  853. uint bytesleft;
  854. lastchar = get_bits(8);
  855. thischar = get_bits(8);
  856. /* ok if it's a normal JPEG file without a special header */
  857. if ((lastchar == 0xFF) && (thischar == M_SOI))
  858. return;
  859. bytesleft = 4096;
  860. for (; ; )
  861. {
  862. if (--bytesleft == 0)
  863. stop_decoding(JPGD_NOT_JPEG);
  864. lastchar = thischar;
  865. thischar = get_bits(8);
  866. if (lastchar == 0xFF)
  867. {
  868. if (thischar == M_SOI)
  869. break;
  870. else if (thischar == M_EOI) // get_bits will keep returning M_EOI if we read past the end
  871. stop_decoding(JPGD_NOT_JPEG);
  872. }
  873. }
  874. // Check the next character after marker: if it's not 0xFF, it can't be the start of the next marker, so the file is bad.
  875. thischar = (m_bit_buf >> 24) & 0xFF;
  876. if (thischar != 0xFF)
  877. stop_decoding(JPGD_NOT_JPEG);
  878. }
  879. // Find a start of frame (SOF) marker.
  880. void jpeg_decoder::locate_sof_marker()
  881. {
  882. locate_soi_marker();
  883. int c = process_markers();
  884. switch (c)
  885. {
  886. case M_SOF2:
  887. {
  888. m_progressive_flag = JPGD_TRUE;
  889. read_sof_marker();
  890. break;
  891. }
  892. case M_SOF0: /* baseline DCT */
  893. case M_SOF1: /* extended sequential DCT */
  894. {
  895. read_sof_marker();
  896. break;
  897. }
  898. case M_SOF9: /* Arithmitic coding */
  899. {
  900. stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
  901. break;
  902. }
  903. default:
  904. {
  905. stop_decoding(JPGD_UNSUPPORTED_MARKER);
  906. break;
  907. }
  908. }
  909. }
  910. // Find a start of scan (SOS) marker.
  911. int jpeg_decoder::locate_sos_marker()
  912. {
  913. int c;
  914. c = process_markers();
  915. if (c == M_EOI)
  916. return JPGD_FALSE;
  917. else if (c != M_SOS)
  918. stop_decoding(JPGD_UNEXPECTED_MARKER);
  919. read_sos_marker();
  920. return JPGD_TRUE;
  921. }
  922. // Reset everything to default/uninitialized state.
  923. void jpeg_decoder::init(jpeg_decoder_stream* pStream, uint32_t flags)
  924. {
  925. m_flags = flags;
  926. m_pMem_blocks = nullptr;
  927. m_error_code = JPGD_SUCCESS;
  928. m_ready_flag = false;
  929. m_image_x_size = m_image_y_size = 0;
  930. m_pStream = pStream;
  931. m_progressive_flag = JPGD_FALSE;
  932. memset(m_huff_ac, 0, sizeof(m_huff_ac));
  933. memset(m_huff_num, 0, sizeof(m_huff_num));
  934. memset(m_huff_val, 0, sizeof(m_huff_val));
  935. memset(m_quant, 0, sizeof(m_quant));
  936. m_scan_type = 0;
  937. m_comps_in_frame = 0;
  938. memset(m_comp_h_samp, 0, sizeof(m_comp_h_samp));
  939. memset(m_comp_v_samp, 0, sizeof(m_comp_v_samp));
  940. memset(m_comp_quant, 0, sizeof(m_comp_quant));
  941. memset(m_comp_ident, 0, sizeof(m_comp_ident));
  942. memset(m_comp_h_blocks, 0, sizeof(m_comp_h_blocks));
  943. memset(m_comp_v_blocks, 0, sizeof(m_comp_v_blocks));
  944. m_comps_in_scan = 0;
  945. memset(m_comp_list, 0, sizeof(m_comp_list));
  946. memset(m_comp_dc_tab, 0, sizeof(m_comp_dc_tab));
  947. memset(m_comp_ac_tab, 0, sizeof(m_comp_ac_tab));
  948. m_spectral_start = 0;
  949. m_spectral_end = 0;
  950. m_successive_low = 0;
  951. m_successive_high = 0;
  952. m_max_mcu_x_size = 0;
  953. m_max_mcu_y_size = 0;
  954. m_blocks_per_mcu = 0;
  955. m_max_blocks_per_row = 0;
  956. m_mcus_per_row = 0;
  957. m_mcus_per_col = 0;
  958. memset(m_mcu_org, 0, sizeof(m_mcu_org));
  959. m_total_lines_left = 0;
  960. m_mcu_lines_left = 0;
  961. m_num_buffered_scanlines = 0;
  962. m_real_dest_bytes_per_scan_line = 0;
  963. m_dest_bytes_per_scan_line = 0;
  964. m_dest_bytes_per_pixel = 0;
  965. memset(m_pHuff_tabs, 0, sizeof(m_pHuff_tabs));
  966. memset(m_dc_coeffs, 0, sizeof(m_dc_coeffs));
  967. memset(m_ac_coeffs, 0, sizeof(m_ac_coeffs));
  968. memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
  969. m_eob_run = 0;
  970. m_pIn_buf_ofs = m_in_buf;
  971. m_in_buf_left = 0;
  972. m_eof_flag = false;
  973. m_tem_flag = 0;
  974. memset(m_in_buf_pad_start, 0, sizeof(m_in_buf_pad_start));
  975. memset(m_in_buf, 0, sizeof(m_in_buf));
  976. memset(m_in_buf_pad_end, 0, sizeof(m_in_buf_pad_end));
  977. m_restart_interval = 0;
  978. m_restarts_left = 0;
  979. m_next_restart_num = 0;
  980. m_max_mcus_per_row = 0;
  981. m_max_blocks_per_mcu = 0;
  982. m_max_mcus_per_col = 0;
  983. memset(m_last_dc_val, 0, sizeof(m_last_dc_val));
  984. m_pMCU_coefficients = nullptr;
  985. m_pSample_buf = nullptr;
  986. m_pSample_buf_prev = nullptr;
  987. m_sample_buf_prev_valid = false;
  988. m_total_bytes_read = 0;
  989. m_pScan_line_0 = nullptr;
  990. m_pScan_line_1 = nullptr;
  991. // Ready the input buffer.
  992. prep_in_buffer();
  993. // Prime the bit buffer.
  994. m_bits_left = 16;
  995. m_bit_buf = 0;
  996. get_bits(16);
  997. get_bits(16);
  998. for (int i = 0; i < JPGD_MAX_BLOCKS_PER_MCU; i++)
  999. m_mcu_block_max_zag[i] = 64;
  1000. }
  1001. #define SCALEBITS 16
  1002. #define ONE_HALF ((int) 1 << (SCALEBITS-1))
  1003. #define FIX(x) ((int) ((x) * (1L<<SCALEBITS) + 0.5f))
  1004. // Create a few tables that allow us to quickly convert YCbCr to RGB.
  1005. void jpeg_decoder::create_look_ups()
  1006. {
  1007. for (int i = 0; i <= 255; i++)
  1008. {
  1009. int k = i - 128;
  1010. m_crr[i] = (FIX(1.40200f) * k + ONE_HALF) >> SCALEBITS;
  1011. m_cbb[i] = (FIX(1.77200f) * k + ONE_HALF) >> SCALEBITS;
  1012. m_crg[i] = (-FIX(0.71414f)) * k;
  1013. m_cbg[i] = (-FIX(0.34414f)) * k + ONE_HALF;
  1014. }
  1015. }
  1016. // This method throws back into the stream any bytes that where read
  1017. // into the bit buffer during initial marker scanning.
  1018. void jpeg_decoder::fix_in_buffer()
  1019. {
  1020. // In case any 0xFF's where pulled into the buffer during marker scanning.
  1021. assert((m_bits_left & 7) == 0);
  1022. if (m_bits_left == 16)
  1023. stuff_char((uint8)(m_bit_buf & 0xFF));
  1024. if (m_bits_left >= 8)
  1025. stuff_char((uint8)((m_bit_buf >> 8) & 0xFF));
  1026. stuff_char((uint8)((m_bit_buf >> 16) & 0xFF));
  1027. stuff_char((uint8)((m_bit_buf >> 24) & 0xFF));
  1028. m_bits_left = 16;
  1029. get_bits_no_markers(16);
  1030. get_bits_no_markers(16);
  1031. }
  1032. void jpeg_decoder::transform_mcu(int mcu_row)
  1033. {
  1034. jpgd_block_t* pSrc_ptr = m_pMCU_coefficients;
  1035. if (mcu_row * m_blocks_per_mcu >= m_max_blocks_per_row)
  1036. stop_decoding(JPGD_DECODE_ERROR);
  1037. uint8* pDst_ptr = m_pSample_buf + mcu_row * m_blocks_per_mcu * 64;
  1038. for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
  1039. {
  1040. idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]);
  1041. pSrc_ptr += 64;
  1042. pDst_ptr += 64;
  1043. }
  1044. }
  1045. // Loads and dequantizes the next row of (already decoded) coefficients.
  1046. // Progressive images only.
  1047. void jpeg_decoder::load_next_row()
  1048. {
  1049. int i;
  1050. jpgd_block_t* p;
  1051. jpgd_quant_t* q;
  1052. int mcu_row, mcu_block, row_block = 0;
  1053. int component_num, component_id;
  1054. int block_x_mcu[JPGD_MAX_COMPONENTS];
  1055. memset(block_x_mcu, 0, JPGD_MAX_COMPONENTS * sizeof(int));
  1056. for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
  1057. {
  1058. int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
  1059. for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
  1060. {
  1061. component_id = m_mcu_org[mcu_block];
  1062. if (m_comp_quant[component_id] >= JPGD_MAX_QUANT_TABLES)
  1063. stop_decoding(JPGD_DECODE_ERROR);
  1064. q = m_quant[m_comp_quant[component_id]];
  1065. p = m_pMCU_coefficients + 64 * mcu_block;
  1066. jpgd_block_t* pAC = coeff_buf_getp(m_ac_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
  1067. jpgd_block_t* pDC = coeff_buf_getp(m_dc_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
  1068. p[0] = pDC[0];
  1069. memcpy(&p[1], &pAC[1], 63 * sizeof(jpgd_block_t));
  1070. for (i = 63; i > 0; i--)
  1071. if (p[g_ZAG[i]])
  1072. break;
  1073. m_mcu_block_max_zag[mcu_block] = i + 1;
  1074. for (; i >= 0; i--)
  1075. if (p[g_ZAG[i]])
  1076. p[g_ZAG[i]] = static_cast<jpgd_block_t>(p[g_ZAG[i]] * q[i]);
  1077. row_block++;
  1078. if (m_comps_in_scan == 1)
  1079. block_x_mcu[component_id]++;
  1080. else
  1081. {
  1082. if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
  1083. {
  1084. block_x_mcu_ofs = 0;
  1085. if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
  1086. {
  1087. block_y_mcu_ofs = 0;
  1088. block_x_mcu[component_id] += m_comp_h_samp[component_id];
  1089. }
  1090. }
  1091. }
  1092. }
  1093. transform_mcu(mcu_row);
  1094. }
  1095. if (m_comps_in_scan == 1)
  1096. m_block_y_mcu[m_comp_list[0]]++;
  1097. else
  1098. {
  1099. for (component_num = 0; component_num < m_comps_in_scan; component_num++)
  1100. {
  1101. component_id = m_comp_list[component_num];
  1102. m_block_y_mcu[component_id] += m_comp_v_samp[component_id];
  1103. }
  1104. }
  1105. }
  1106. // Restart interval processing.
  1107. void jpeg_decoder::process_restart()
  1108. {
  1109. int i;
  1110. int c = 0;
  1111. // Align to a byte boundry
  1112. // FIXME: Is this really necessary? get_bits_no_markers() never reads in markers!
  1113. //get_bits_no_markers(m_bits_left & 7);
  1114. // Let's scan a little bit to find the marker, but not _too_ far.
  1115. // 1536 is a "fudge factor" that determines how much to scan.
  1116. for (i = 1536; i > 0; i--)
  1117. if (get_char() == 0xFF)
  1118. break;
  1119. if (i == 0)
  1120. stop_decoding(JPGD_BAD_RESTART_MARKER);
  1121. for (; i > 0; i--)
  1122. if ((c = get_char()) != 0xFF)
  1123. break;
  1124. if (i == 0)
  1125. stop_decoding(JPGD_BAD_RESTART_MARKER);
  1126. // Is it the expected marker? If not, something bad happened.
  1127. if (c != (m_next_restart_num + M_RST0))
  1128. stop_decoding(JPGD_BAD_RESTART_MARKER);
  1129. // Reset each component's DC prediction values.
  1130. memset(&m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
  1131. m_eob_run = 0;
  1132. m_restarts_left = m_restart_interval;
  1133. m_next_restart_num = (m_next_restart_num + 1) & 7;
  1134. // Get the bit buffer going again...
  1135. m_bits_left = 16;
  1136. get_bits_no_markers(16);
  1137. get_bits_no_markers(16);
  1138. }
  1139. static inline int dequantize_ac(int c, int q) { c *= q; return c; }
  1140. // Decodes and dequantizes the next row of coefficients.
  1141. void jpeg_decoder::decode_next_row()
  1142. {
  1143. int row_block = 0;
  1144. for (int mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
  1145. {
  1146. if ((m_restart_interval) && (m_restarts_left == 0))
  1147. process_restart();
  1148. jpgd_block_t* p = m_pMCU_coefficients;
  1149. for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++, p += 64)
  1150. {
  1151. int component_id = m_mcu_org[mcu_block];
  1152. if (m_comp_quant[component_id] >= JPGD_MAX_QUANT_TABLES)
  1153. stop_decoding(JPGD_DECODE_ERROR);
  1154. jpgd_quant_t* q = m_quant[m_comp_quant[component_id]];
  1155. int r, s;
  1156. s = huff_decode(m_pHuff_tabs[m_comp_dc_tab[component_id]], r);
  1157. if (s >= 16)
  1158. stop_decoding(JPGD_DECODE_ERROR);
  1159. s = JPGD_HUFF_EXTEND(r, s);
  1160. m_last_dc_val[component_id] = (s += m_last_dc_val[component_id]);
  1161. p[0] = static_cast<jpgd_block_t>(s * q[0]);
  1162. int prev_num_set = m_mcu_block_max_zag[mcu_block];
  1163. huff_tables* pH = m_pHuff_tabs[m_comp_ac_tab[component_id]];
  1164. int k;
  1165. for (k = 1; k < 64; k++)
  1166. {
  1167. int extra_bits;
  1168. s = huff_decode(pH, extra_bits);
  1169. r = s >> 4;
  1170. s &= 15;
  1171. if (s)
  1172. {
  1173. if (r)
  1174. {
  1175. if ((k + r) > 63)
  1176. stop_decoding(JPGD_DECODE_ERROR);
  1177. if (k < prev_num_set)
  1178. {
  1179. int n = JPGD_MIN(r, prev_num_set - k);
  1180. int kt = k;
  1181. while (n--)
  1182. p[g_ZAG[kt++]] = 0;
  1183. }
  1184. k += r;
  1185. }
  1186. s = JPGD_HUFF_EXTEND(extra_bits, s);
  1187. if (k >= 64)
  1188. stop_decoding(JPGD_DECODE_ERROR);
  1189. p[g_ZAG[k]] = static_cast<jpgd_block_t>(dequantize_ac(s, q[k])); //s * q[k];
  1190. }
  1191. else
  1192. {
  1193. if (r == 15)
  1194. {
  1195. if ((k + 16) > 64)
  1196. stop_decoding(JPGD_DECODE_ERROR);
  1197. if (k < prev_num_set)
  1198. {
  1199. int n = JPGD_MIN(16, prev_num_set - k);
  1200. int kt = k;
  1201. while (n--)
  1202. {
  1203. if (kt > 63)
  1204. stop_decoding(JPGD_DECODE_ERROR);
  1205. p[g_ZAG[kt++]] = 0;
  1206. }
  1207. }
  1208. k += 16 - 1; // - 1 because the loop counter is k
  1209. if (p[g_ZAG[k & 63]] != 0)
  1210. stop_decoding(JPGD_DECODE_ERROR);
  1211. }
  1212. else
  1213. break;
  1214. }
  1215. }
  1216. if (k < prev_num_set)
  1217. {
  1218. int kt = k;
  1219. while (kt < prev_num_set)
  1220. p[g_ZAG[kt++]] = 0;
  1221. }
  1222. m_mcu_block_max_zag[mcu_block] = k;
  1223. row_block++;
  1224. }
  1225. transform_mcu(mcu_row);
  1226. m_restarts_left--;
  1227. }
  1228. }
  1229. // YCbCr H1V1 (1x1:1:1, 3 m_blocks per MCU) to RGB
  1230. void jpeg_decoder::H1V1Convert()
  1231. {
  1232. int row = m_max_mcu_y_size - m_mcu_lines_left;
  1233. uint8* d = m_pScan_line_0;
  1234. uint8* s = m_pSample_buf + row * 8;
  1235. for (int i = m_max_mcus_per_row; i > 0; i--)
  1236. {
  1237. for (int j = 0; j < 8; j++)
  1238. {
  1239. int y = s[j];
  1240. int cb = s[64 + j];
  1241. int cr = s[128 + j];
  1242. d[0] = clamp(y + m_crr[cr]);
  1243. d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
  1244. d[2] = clamp(y + m_cbb[cb]);
  1245. d[3] = 255;
  1246. d += 4;
  1247. }
  1248. s += 64 * 3;
  1249. }
  1250. }
  1251. // YCbCr H2V1 (2x1:1:1, 4 m_blocks per MCU) to RGB
  1252. void jpeg_decoder::H2V1Convert()
  1253. {
  1254. int row = m_max_mcu_y_size - m_mcu_lines_left;
  1255. uint8* d0 = m_pScan_line_0;
  1256. uint8* y = m_pSample_buf + row * 8;
  1257. uint8* c = m_pSample_buf + 2 * 64 + row * 8;
  1258. for (int i = m_max_mcus_per_row; i > 0; i--)
  1259. {
  1260. for (int l = 0; l < 2; l++)
  1261. {
  1262. for (int j = 0; j < 4; j++)
  1263. {
  1264. int cb = c[0];
  1265. int cr = c[64];
  1266. int rc = m_crr[cr];
  1267. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1268. int bc = m_cbb[cb];
  1269. int yy = y[j << 1];
  1270. d0[0] = clamp(yy + rc);
  1271. d0[1] = clamp(yy + gc);
  1272. d0[2] = clamp(yy + bc);
  1273. d0[3] = 255;
  1274. yy = y[(j << 1) + 1];
  1275. d0[4] = clamp(yy + rc);
  1276. d0[5] = clamp(yy + gc);
  1277. d0[6] = clamp(yy + bc);
  1278. d0[7] = 255;
  1279. d0 += 8;
  1280. c++;
  1281. }
  1282. y += 64;
  1283. }
  1284. y += 64 * 4 - 64 * 2;
  1285. c += 64 * 4 - 8;
  1286. }
  1287. }
  1288. // YCbCr H2V1 (2x1:1:1, 4 m_blocks per MCU) to RGB
  1289. void jpeg_decoder::H2V1ConvertFiltered()
  1290. {
  1291. const uint BLOCKS_PER_MCU = 4;
  1292. int row = m_max_mcu_y_size - m_mcu_lines_left;
  1293. uint8* d0 = m_pScan_line_0;
  1294. const int half_image_x_size = (m_image_x_size >> 1) - 1;
  1295. const int row_x8 = row * 8;
  1296. for (int x = 0; x < m_image_x_size; x++)
  1297. {
  1298. int y = m_pSample_buf[check_sample_buf_ofs((x >> 4) * BLOCKS_PER_MCU * 64 + ((x & 8) ? 64 : 0) + (x & 7) + row_x8)];
  1299. int c_x0 = (x - 1) >> 1;
  1300. int c_x1 = JPGD_MIN(c_x0 + 1, half_image_x_size);
  1301. c_x0 = JPGD_MAX(c_x0, 0);
  1302. int a = (c_x0 >> 3) * BLOCKS_PER_MCU * 64 + (c_x0 & 7) + row_x8 + 128;
  1303. int cb0 = m_pSample_buf[check_sample_buf_ofs(a)];
  1304. int cr0 = m_pSample_buf[check_sample_buf_ofs(a + 64)];
  1305. int b = (c_x1 >> 3) * BLOCKS_PER_MCU * 64 + (c_x1 & 7) + row_x8 + 128;
  1306. int cb1 = m_pSample_buf[check_sample_buf_ofs(b)];
  1307. int cr1 = m_pSample_buf[check_sample_buf_ofs(b + 64)];
  1308. int w0 = (x & 1) ? 3 : 1;
  1309. int w1 = (x & 1) ? 1 : 3;
  1310. int cb = (cb0 * w0 + cb1 * w1 + 2) >> 2;
  1311. int cr = (cr0 * w0 + cr1 * w1 + 2) >> 2;
  1312. int rc = m_crr[cr];
  1313. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1314. int bc = m_cbb[cb];
  1315. d0[0] = clamp(y + rc);
  1316. d0[1] = clamp(y + gc);
  1317. d0[2] = clamp(y + bc);
  1318. d0[3] = 255;
  1319. d0 += 4;
  1320. }
  1321. }
  1322. // YCbCr H2V1 (1x2:1:1, 4 m_blocks per MCU) to RGB
  1323. void jpeg_decoder::H1V2Convert()
  1324. {
  1325. int row = m_max_mcu_y_size - m_mcu_lines_left;
  1326. uint8* d0 = m_pScan_line_0;
  1327. uint8* d1 = m_pScan_line_1;
  1328. uint8* y;
  1329. uint8* c;
  1330. if (row < 8)
  1331. y = m_pSample_buf + row * 8;
  1332. else
  1333. y = m_pSample_buf + 64 * 1 + (row & 7) * 8;
  1334. c = m_pSample_buf + 64 * 2 + (row >> 1) * 8;
  1335. for (int i = m_max_mcus_per_row; i > 0; i--)
  1336. {
  1337. for (int j = 0; j < 8; j++)
  1338. {
  1339. int cb = c[0 + j];
  1340. int cr = c[64 + j];
  1341. int rc = m_crr[cr];
  1342. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1343. int bc = m_cbb[cb];
  1344. int yy = y[j];
  1345. d0[0] = clamp(yy + rc);
  1346. d0[1] = clamp(yy + gc);
  1347. d0[2] = clamp(yy + bc);
  1348. d0[3] = 255;
  1349. yy = y[8 + j];
  1350. d1[0] = clamp(yy + rc);
  1351. d1[1] = clamp(yy + gc);
  1352. d1[2] = clamp(yy + bc);
  1353. d1[3] = 255;
  1354. d0 += 4;
  1355. d1 += 4;
  1356. }
  1357. y += 64 * 4;
  1358. c += 64 * 4;
  1359. }
  1360. }
  1361. // YCbCr H2V1 (1x2:1:1, 4 m_blocks per MCU) to RGB
  1362. void jpeg_decoder::H1V2ConvertFiltered()
  1363. {
  1364. const uint BLOCKS_PER_MCU = 4;
  1365. int y = m_image_y_size - m_total_lines_left;
  1366. int row = y & 15;
  1367. const int half_image_y_size = (m_image_y_size >> 1) - 1;
  1368. uint8* d0 = m_pScan_line_0;
  1369. const int w0 = (row & 1) ? 3 : 1;
  1370. const int w1 = (row & 1) ? 1 : 3;
  1371. int c_y0 = (y - 1) >> 1;
  1372. int c_y1 = JPGD_MIN(c_y0 + 1, half_image_y_size);
  1373. const uint8_t* p_YSamples = m_pSample_buf;
  1374. const uint8_t* p_C0Samples = m_pSample_buf;
  1375. if ((c_y0 >= 0) && (((row & 15) == 0) || ((row & 15) == 15)) && (m_total_lines_left > 1))
  1376. {
  1377. assert(y > 0);
  1378. assert(m_sample_buf_prev_valid);
  1379. if ((row & 15) == 15)
  1380. p_YSamples = m_pSample_buf_prev;
  1381. p_C0Samples = m_pSample_buf_prev;
  1382. }
  1383. const int y_sample_base_ofs = ((row & 8) ? 64 : 0) + (row & 7) * 8;
  1384. const int y0_base = (c_y0 & 7) * 8 + 128;
  1385. const int y1_base = (c_y1 & 7) * 8 + 128;
  1386. for (int x = 0; x < m_image_x_size; x++)
  1387. {
  1388. const int base_ofs = (x >> 3) * BLOCKS_PER_MCU * 64 + (x & 7);
  1389. int y_sample = p_YSamples[check_sample_buf_ofs(base_ofs + y_sample_base_ofs)];
  1390. int a = base_ofs + y0_base;
  1391. int cb0_sample = p_C0Samples[check_sample_buf_ofs(a)];
  1392. int cr0_sample = p_C0Samples[check_sample_buf_ofs(a + 64)];
  1393. int b = base_ofs + y1_base;
  1394. int cb1_sample = m_pSample_buf[check_sample_buf_ofs(b)];
  1395. int cr1_sample = m_pSample_buf[check_sample_buf_ofs(b + 64)];
  1396. int cb = (cb0_sample * w0 + cb1_sample * w1 + 2) >> 2;
  1397. int cr = (cr0_sample * w0 + cr1_sample * w1 + 2) >> 2;
  1398. int rc = m_crr[cr];
  1399. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1400. int bc = m_cbb[cb];
  1401. d0[0] = clamp(y_sample + rc);
  1402. d0[1] = clamp(y_sample + gc);
  1403. d0[2] = clamp(y_sample + bc);
  1404. d0[3] = 255;
  1405. d0 += 4;
  1406. }
  1407. }
  1408. // YCbCr H2V2 (2x2:1:1, 6 m_blocks per MCU) to RGB
  1409. void jpeg_decoder::H2V2Convert()
  1410. {
  1411. int row = m_max_mcu_y_size - m_mcu_lines_left;
  1412. uint8* d0 = m_pScan_line_0;
  1413. uint8* d1 = m_pScan_line_1;
  1414. uint8* y;
  1415. uint8* c;
  1416. if (row < 8)
  1417. y = m_pSample_buf + row * 8;
  1418. else
  1419. y = m_pSample_buf + 64 * 2 + (row & 7) * 8;
  1420. c = m_pSample_buf + 64 * 4 + (row >> 1) * 8;
  1421. for (int i = m_max_mcus_per_row; i > 0; i--)
  1422. {
  1423. for (int l = 0; l < 2; l++)
  1424. {
  1425. for (int j = 0; j < 8; j += 2)
  1426. {
  1427. int cb = c[0];
  1428. int cr = c[64];
  1429. int rc = m_crr[cr];
  1430. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1431. int bc = m_cbb[cb];
  1432. int yy = y[j];
  1433. d0[0] = clamp(yy + rc);
  1434. d0[1] = clamp(yy + gc);
  1435. d0[2] = clamp(yy + bc);
  1436. d0[3] = 255;
  1437. yy = y[j + 1];
  1438. d0[4] = clamp(yy + rc);
  1439. d0[5] = clamp(yy + gc);
  1440. d0[6] = clamp(yy + bc);
  1441. d0[7] = 255;
  1442. yy = y[j + 8];
  1443. d1[0] = clamp(yy + rc);
  1444. d1[1] = clamp(yy + gc);
  1445. d1[2] = clamp(yy + bc);
  1446. d1[3] = 255;
  1447. yy = y[j + 8 + 1];
  1448. d1[4] = clamp(yy + rc);
  1449. d1[5] = clamp(yy + gc);
  1450. d1[6] = clamp(yy + bc);
  1451. d1[7] = 255;
  1452. d0 += 8;
  1453. d1 += 8;
  1454. c++;
  1455. }
  1456. y += 64;
  1457. }
  1458. y += 64 * 6 - 64 * 2;
  1459. c += 64 * 6 - 8;
  1460. }
  1461. }
  1462. uint32_t jpeg_decoder::H2V2ConvertFiltered()
  1463. {
  1464. const uint BLOCKS_PER_MCU = 6;
  1465. int y = m_image_y_size - m_total_lines_left;
  1466. int row = y & 15;
  1467. const int half_image_y_size = (m_image_y_size >> 1) - 1;
  1468. uint8* d0 = m_pScan_line_0;
  1469. int c_y0 = (y - 1) >> 1;
  1470. int c_y1 = JPGD_MIN(c_y0 + 1, half_image_y_size);
  1471. const uint8_t* p_YSamples = m_pSample_buf;
  1472. const uint8_t* p_C0Samples = m_pSample_buf;
  1473. if ((c_y0 >= 0) && (((row & 15) == 0) || ((row & 15) == 15)) && (m_total_lines_left > 1))
  1474. {
  1475. assert(y > 0);
  1476. assert(m_sample_buf_prev_valid);
  1477. if ((row & 15) == 15)
  1478. p_YSamples = m_pSample_buf_prev;
  1479. p_C0Samples = m_pSample_buf_prev;
  1480. }
  1481. const int y_sample_base_ofs = ((row & 8) ? 128 : 0) + (row & 7) * 8;
  1482. const int y0_base = (c_y0 & 7) * 8 + 256;
  1483. const int y1_base = (c_y1 & 7) * 8 + 256;
  1484. const int half_image_x_size = (m_image_x_size >> 1) - 1;
  1485. static const uint8_t s_muls[2][2][4] =
  1486. {
  1487. { { 1, 3, 3, 9 }, { 3, 9, 1, 3 }, },
  1488. { { 3, 1, 9, 3 }, { 9, 3, 3, 1 } }
  1489. };
  1490. if (((row & 15) >= 1) && ((row & 15) <= 14))
  1491. {
  1492. assert((row & 1) == 1);
  1493. assert(((y + 1 - 1) >> 1) == c_y0);
  1494. assert(p_YSamples == m_pSample_buf);
  1495. assert(p_C0Samples == m_pSample_buf);
  1496. uint8* d1 = m_pScan_line_1;
  1497. const int y_sample_base_ofs1 = (((row + 1) & 8) ? 128 : 0) + ((row + 1) & 7) * 8;
  1498. for (int x = 0; x < m_image_x_size; x++)
  1499. {
  1500. int k = (x >> 4) * BLOCKS_PER_MCU * 64 + ((x & 8) ? 64 : 0) + (x & 7);
  1501. int y_sample0 = p_YSamples[check_sample_buf_ofs(k + y_sample_base_ofs)];
  1502. int y_sample1 = p_YSamples[check_sample_buf_ofs(k + y_sample_base_ofs1)];
  1503. int c_x0 = (x - 1) >> 1;
  1504. int c_x1 = JPGD_MIN(c_x0 + 1, half_image_x_size);
  1505. c_x0 = JPGD_MAX(c_x0, 0);
  1506. int a = (c_x0 >> 3) * BLOCKS_PER_MCU * 64 + (c_x0 & 7);
  1507. int cb00_sample = p_C0Samples[check_sample_buf_ofs(a + y0_base)];
  1508. int cr00_sample = p_C0Samples[check_sample_buf_ofs(a + y0_base + 64)];
  1509. int cb01_sample = m_pSample_buf[check_sample_buf_ofs(a + y1_base)];
  1510. int cr01_sample = m_pSample_buf[check_sample_buf_ofs(a + y1_base + 64)];
  1511. int b = (c_x1 >> 3) * BLOCKS_PER_MCU * 64 + (c_x1 & 7);
  1512. int cb10_sample = p_C0Samples[check_sample_buf_ofs(b + y0_base)];
  1513. int cr10_sample = p_C0Samples[check_sample_buf_ofs(b + y0_base + 64)];
  1514. int cb11_sample = m_pSample_buf[check_sample_buf_ofs(b + y1_base)];
  1515. int cr11_sample = m_pSample_buf[check_sample_buf_ofs(b + y1_base + 64)];
  1516. {
  1517. const uint8_t* pMuls = &s_muls[row & 1][x & 1][0];
  1518. int cb = (cb00_sample * pMuls[0] + cb01_sample * pMuls[1] + cb10_sample * pMuls[2] + cb11_sample * pMuls[3] + 8) >> 4;
  1519. int cr = (cr00_sample * pMuls[0] + cr01_sample * pMuls[1] + cr10_sample * pMuls[2] + cr11_sample * pMuls[3] + 8) >> 4;
  1520. int rc = m_crr[cr];
  1521. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1522. int bc = m_cbb[cb];
  1523. d0[0] = clamp(y_sample0 + rc);
  1524. d0[1] = clamp(y_sample0 + gc);
  1525. d0[2] = clamp(y_sample0 + bc);
  1526. d0[3] = 255;
  1527. d0 += 4;
  1528. }
  1529. {
  1530. const uint8_t* pMuls = &s_muls[(row + 1) & 1][x & 1][0];
  1531. int cb = (cb00_sample * pMuls[0] + cb01_sample * pMuls[1] + cb10_sample * pMuls[2] + cb11_sample * pMuls[3] + 8) >> 4;
  1532. int cr = (cr00_sample * pMuls[0] + cr01_sample * pMuls[1] + cr10_sample * pMuls[2] + cr11_sample * pMuls[3] + 8) >> 4;
  1533. int rc = m_crr[cr];
  1534. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1535. int bc = m_cbb[cb];
  1536. d1[0] = clamp(y_sample1 + rc);
  1537. d1[1] = clamp(y_sample1 + gc);
  1538. d1[2] = clamp(y_sample1 + bc);
  1539. d1[3] = 255;
  1540. d1 += 4;
  1541. }
  1542. if (((x & 1) == 1) && (x < m_image_x_size - 1))
  1543. {
  1544. const int nx = x + 1;
  1545. assert(c_x0 == (nx - 1) >> 1);
  1546. k = (nx >> 4) * BLOCKS_PER_MCU * 64 + ((nx & 8) ? 64 : 0) + (nx & 7);
  1547. y_sample0 = p_YSamples[check_sample_buf_ofs(k + y_sample_base_ofs)];
  1548. y_sample1 = p_YSamples[check_sample_buf_ofs(k + y_sample_base_ofs1)];
  1549. {
  1550. const uint8_t* pMuls = &s_muls[row & 1][nx & 1][0];
  1551. int cb = (cb00_sample * pMuls[0] + cb01_sample * pMuls[1] + cb10_sample * pMuls[2] + cb11_sample * pMuls[3] + 8) >> 4;
  1552. int cr = (cr00_sample * pMuls[0] + cr01_sample * pMuls[1] + cr10_sample * pMuls[2] + cr11_sample * pMuls[3] + 8) >> 4;
  1553. int rc = m_crr[cr];
  1554. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1555. int bc = m_cbb[cb];
  1556. d0[0] = clamp(y_sample0 + rc);
  1557. d0[1] = clamp(y_sample0 + gc);
  1558. d0[2] = clamp(y_sample0 + bc);
  1559. d0[3] = 255;
  1560. d0 += 4;
  1561. }
  1562. {
  1563. const uint8_t* pMuls = &s_muls[(row + 1) & 1][nx & 1][0];
  1564. int cb = (cb00_sample * pMuls[0] + cb01_sample * pMuls[1] + cb10_sample * pMuls[2] + cb11_sample * pMuls[3] + 8) >> 4;
  1565. int cr = (cr00_sample * pMuls[0] + cr01_sample * pMuls[1] + cr10_sample * pMuls[2] + cr11_sample * pMuls[3] + 8) >> 4;
  1566. int rc = m_crr[cr];
  1567. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1568. int bc = m_cbb[cb];
  1569. d1[0] = clamp(y_sample1 + rc);
  1570. d1[1] = clamp(y_sample1 + gc);
  1571. d1[2] = clamp(y_sample1 + bc);
  1572. d1[3] = 255;
  1573. d1 += 4;
  1574. }
  1575. ++x;
  1576. }
  1577. }
  1578. return 2;
  1579. }
  1580. else
  1581. {
  1582. for (int x = 0; x < m_image_x_size; x++)
  1583. {
  1584. int y_sample = p_YSamples[check_sample_buf_ofs((x >> 4) * BLOCKS_PER_MCU * 64 + ((x & 8) ? 64 : 0) + (x & 7) + y_sample_base_ofs)];
  1585. int c_x0 = (x - 1) >> 1;
  1586. int c_x1 = JPGD_MIN(c_x0 + 1, half_image_x_size);
  1587. c_x0 = JPGD_MAX(c_x0, 0);
  1588. int a = (c_x0 >> 3) * BLOCKS_PER_MCU * 64 + (c_x0 & 7);
  1589. int cb00_sample = p_C0Samples[check_sample_buf_ofs(a + y0_base)];
  1590. int cr00_sample = p_C0Samples[check_sample_buf_ofs(a + y0_base + 64)];
  1591. int cb01_sample = m_pSample_buf[check_sample_buf_ofs(a + y1_base)];
  1592. int cr01_sample = m_pSample_buf[check_sample_buf_ofs(a + y1_base + 64)];
  1593. int b = (c_x1 >> 3) * BLOCKS_PER_MCU * 64 + (c_x1 & 7);
  1594. int cb10_sample = p_C0Samples[check_sample_buf_ofs(b + y0_base)];
  1595. int cr10_sample = p_C0Samples[check_sample_buf_ofs(b + y0_base + 64)];
  1596. int cb11_sample = m_pSample_buf[check_sample_buf_ofs(b + y1_base)];
  1597. int cr11_sample = m_pSample_buf[check_sample_buf_ofs(b + y1_base + 64)];
  1598. const uint8_t* pMuls = &s_muls[row & 1][x & 1][0];
  1599. int cb = (cb00_sample * pMuls[0] + cb01_sample * pMuls[1] + cb10_sample * pMuls[2] + cb11_sample * pMuls[3] + 8) >> 4;
  1600. int cr = (cr00_sample * pMuls[0] + cr01_sample * pMuls[1] + cr10_sample * pMuls[2] + cr11_sample * pMuls[3] + 8) >> 4;
  1601. int rc = m_crr[cr];
  1602. int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
  1603. int bc = m_cbb[cb];
  1604. d0[0] = clamp(y_sample + rc);
  1605. d0[1] = clamp(y_sample + gc);
  1606. d0[2] = clamp(y_sample + bc);
  1607. d0[3] = 255;
  1608. d0 += 4;
  1609. }
  1610. return 1;
  1611. }
  1612. }
  1613. // Y (1 block per MCU) to 8-bit grayscale
  1614. void jpeg_decoder::gray_convert()
  1615. {
  1616. int row = m_max_mcu_y_size - m_mcu_lines_left;
  1617. uint8* d = m_pScan_line_0;
  1618. uint8* s = m_pSample_buf + row * 8;
  1619. for (int i = m_max_mcus_per_row; i > 0; i--)
  1620. {
  1621. *(uint*)d = *(uint*)s;
  1622. *(uint*)(&d[4]) = *(uint*)(&s[4]);
  1623. s += 64;
  1624. d += 8;
  1625. }
  1626. }
  1627. // Find end of image (EOI) marker, so we can return to the user the exact size of the input stream.
  1628. void jpeg_decoder::find_eoi()
  1629. {
  1630. if (!m_progressive_flag)
  1631. {
  1632. // Attempt to read the EOI marker.
  1633. //get_bits_no_markers(m_bits_left & 7);
  1634. // Prime the bit buffer
  1635. m_bits_left = 16;
  1636. get_bits(16);
  1637. get_bits(16);
  1638. // The next marker _should_ be EOI
  1639. process_markers();
  1640. }
  1641. m_total_bytes_read -= m_in_buf_left;
  1642. }
  1643. int jpeg_decoder::decode_next_mcu_row()
  1644. {
  1645. if (setjmp(m_jmp_state))
  1646. return JPGD_FAILED;
  1647. const bool chroma_y_filtering = (m_flags & cFlagLinearChromaFiltering) && ((m_scan_type == JPGD_YH2V2) || (m_scan_type == JPGD_YH1V2)) && (m_image_x_size >= 2) && (m_image_y_size >= 2);
  1648. if (chroma_y_filtering)
  1649. {
  1650. std::swap(m_pSample_buf, m_pSample_buf_prev);
  1651. m_sample_buf_prev_valid = true;
  1652. }
  1653. if (m_progressive_flag)
  1654. load_next_row();
  1655. else
  1656. decode_next_row();
  1657. // Find the EOI marker if that was the last row.
  1658. if (m_total_lines_left <= m_max_mcu_y_size)
  1659. find_eoi();
  1660. m_mcu_lines_left = m_max_mcu_y_size;
  1661. return 0;
  1662. }
  1663. int jpeg_decoder::decode(const void** pScan_line, uint* pScan_line_len)
  1664. {
  1665. if ((m_error_code) || (!m_ready_flag))
  1666. return JPGD_FAILED;
  1667. if (m_total_lines_left == 0)
  1668. return JPGD_DONE;
  1669. const bool chroma_y_filtering = (m_flags & cFlagLinearChromaFiltering) && ((m_scan_type == JPGD_YH2V2) || (m_scan_type == JPGD_YH1V2)) && (m_image_x_size >= 2) && (m_image_y_size >= 2);
  1670. bool get_another_mcu_row = false;
  1671. bool got_mcu_early = false;
  1672. if (chroma_y_filtering)
  1673. {
  1674. if (m_total_lines_left == m_image_y_size)
  1675. get_another_mcu_row = true;
  1676. else if ((m_mcu_lines_left == 1) && (m_total_lines_left > 1))
  1677. {
  1678. get_another_mcu_row = true;
  1679. got_mcu_early = true;
  1680. }
  1681. }
  1682. else
  1683. {
  1684. get_another_mcu_row = (m_mcu_lines_left == 0);
  1685. }
  1686. if (get_another_mcu_row)
  1687. {
  1688. int status = decode_next_mcu_row();
  1689. if (status != 0)
  1690. return status;
  1691. }
  1692. switch (m_scan_type)
  1693. {
  1694. case JPGD_YH2V2:
  1695. {
  1696. if ((m_flags & cFlagLinearChromaFiltering) && (m_image_x_size >= 2) && (m_image_y_size >= 2))
  1697. {
  1698. if (m_num_buffered_scanlines == 1)
  1699. {
  1700. *pScan_line = m_pScan_line_1;
  1701. }
  1702. else if (m_num_buffered_scanlines == 0)
  1703. {
  1704. m_num_buffered_scanlines = H2V2ConvertFiltered();
  1705. *pScan_line = m_pScan_line_0;
  1706. }
  1707. m_num_buffered_scanlines--;
  1708. }
  1709. else
  1710. {
  1711. if ((m_mcu_lines_left & 1) == 0)
  1712. {
  1713. H2V2Convert();
  1714. *pScan_line = m_pScan_line_0;
  1715. }
  1716. else
  1717. *pScan_line = m_pScan_line_1;
  1718. }
  1719. break;
  1720. }
  1721. case JPGD_YH2V1:
  1722. {
  1723. if ((m_flags & cFlagLinearChromaFiltering) && (m_image_x_size >= 2) && (m_image_y_size >= 2))
  1724. H2V1ConvertFiltered();
  1725. else
  1726. H2V1Convert();
  1727. *pScan_line = m_pScan_line_0;
  1728. break;
  1729. }
  1730. case JPGD_YH1V2:
  1731. {
  1732. if (chroma_y_filtering)
  1733. {
  1734. H1V2ConvertFiltered();
  1735. *pScan_line = m_pScan_line_0;
  1736. }
  1737. else
  1738. {
  1739. if ((m_mcu_lines_left & 1) == 0)
  1740. {
  1741. H1V2Convert();
  1742. *pScan_line = m_pScan_line_0;
  1743. }
  1744. else
  1745. *pScan_line = m_pScan_line_1;
  1746. }
  1747. break;
  1748. }
  1749. case JPGD_YH1V1:
  1750. {
  1751. H1V1Convert();
  1752. *pScan_line = m_pScan_line_0;
  1753. break;
  1754. }
  1755. case JPGD_GRAYSCALE:
  1756. {
  1757. gray_convert();
  1758. *pScan_line = m_pScan_line_0;
  1759. break;
  1760. }
  1761. }
  1762. *pScan_line_len = m_real_dest_bytes_per_scan_line;
  1763. if (!got_mcu_early)
  1764. {
  1765. m_mcu_lines_left--;
  1766. }
  1767. m_total_lines_left--;
  1768. return JPGD_SUCCESS;
  1769. }
  1770. // Creates the tables needed for efficient Huffman decoding.
  1771. void jpeg_decoder::make_huff_table(int index, huff_tables* pH)
  1772. {
  1773. int p, i, l, si;
  1774. uint8 huffsize[258];
  1775. uint huffcode[258];
  1776. uint code;
  1777. uint subtree;
  1778. int code_size;
  1779. int lastp;
  1780. int nextfreeentry;
  1781. int currententry;
  1782. pH->ac_table = m_huff_ac[index] != 0;
  1783. p = 0;
  1784. for (l = 1; l <= 16; l++)
  1785. {
  1786. for (i = 1; i <= m_huff_num[index][l]; i++)
  1787. {
  1788. if (p >= 257)
  1789. stop_decoding(JPGD_DECODE_ERROR);
  1790. huffsize[p++] = static_cast<uint8>(l);
  1791. }
  1792. }
  1793. assert(p < 258);
  1794. huffsize[p] = 0;
  1795. lastp = p;
  1796. code = 0;
  1797. si = huffsize[0];
  1798. p = 0;
  1799. while (huffsize[p])
  1800. {
  1801. while (huffsize[p] == si)
  1802. {
  1803. if (p >= 257)
  1804. stop_decoding(JPGD_DECODE_ERROR);
  1805. huffcode[p++] = code;
  1806. code++;
  1807. }
  1808. code <<= 1;
  1809. si++;
  1810. }
  1811. memset(pH->look_up, 0, sizeof(pH->look_up));
  1812. memset(pH->look_up2, 0, sizeof(pH->look_up2));
  1813. memset(pH->tree, 0, sizeof(pH->tree));
  1814. memset(pH->code_size, 0, sizeof(pH->code_size));
  1815. nextfreeentry = -1;
  1816. p = 0;
  1817. while (p < lastp)
  1818. {
  1819. i = m_huff_val[index][p];
  1820. code = huffcode[p];
  1821. code_size = huffsize[p];
  1822. assert(i < JPGD_HUFF_CODE_SIZE_MAX_LENGTH);
  1823. pH->code_size[i] = static_cast<uint8>(code_size);
  1824. if (code_size <= 8)
  1825. {
  1826. code <<= (8 - code_size);
  1827. for (l = 1 << (8 - code_size); l > 0; l--)
  1828. {
  1829. if (code >= 256)
  1830. stop_decoding(JPGD_DECODE_ERROR);
  1831. pH->look_up[code] = i;
  1832. bool has_extrabits = false;
  1833. int extra_bits = 0;
  1834. int num_extra_bits = i & 15;
  1835. int bits_to_fetch = code_size;
  1836. if (num_extra_bits)
  1837. {
  1838. int total_codesize = code_size + num_extra_bits;
  1839. if (total_codesize <= 8)
  1840. {
  1841. has_extrabits = true;
  1842. extra_bits = ((1 << num_extra_bits) - 1) & (code >> (8 - total_codesize));
  1843. if (extra_bits > 0x7FFF)
  1844. stop_decoding(JPGD_DECODE_ERROR);
  1845. bits_to_fetch += num_extra_bits;
  1846. }
  1847. }
  1848. if (!has_extrabits)
  1849. pH->look_up2[code] = i | (bits_to_fetch << 8);
  1850. else
  1851. pH->look_up2[code] = i | 0x8000 | (extra_bits << 16) | (bits_to_fetch << 8);
  1852. code++;
  1853. }
  1854. }
  1855. else
  1856. {
  1857. subtree = (code >> (code_size - 8)) & 0xFF;
  1858. currententry = pH->look_up[subtree];
  1859. if (currententry == 0)
  1860. {
  1861. pH->look_up[subtree] = currententry = nextfreeentry;
  1862. pH->look_up2[subtree] = currententry = nextfreeentry;
  1863. nextfreeentry -= 2;
  1864. }
  1865. code <<= (16 - (code_size - 8));
  1866. for (l = code_size; l > 9; l--)
  1867. {
  1868. if ((code & 0x8000) == 0)
  1869. currententry--;
  1870. unsigned int idx = -currententry - 1;
  1871. if (idx >= JPGD_HUFF_TREE_MAX_LENGTH)
  1872. stop_decoding(JPGD_DECODE_ERROR);
  1873. if (pH->tree[idx] == 0)
  1874. {
  1875. pH->tree[idx] = nextfreeentry;
  1876. currententry = nextfreeentry;
  1877. nextfreeentry -= 2;
  1878. }
  1879. else
  1880. {
  1881. currententry = pH->tree[idx];
  1882. }
  1883. code <<= 1;
  1884. }
  1885. if ((code & 0x8000) == 0)
  1886. currententry--;
  1887. if ((-currententry - 1) >= JPGD_HUFF_TREE_MAX_LENGTH)
  1888. stop_decoding(JPGD_DECODE_ERROR);
  1889. pH->tree[-currententry - 1] = i;
  1890. }
  1891. p++;
  1892. }
  1893. }
  1894. // Verifies the quantization tables needed for this scan are available.
  1895. void jpeg_decoder::check_quant_tables()
  1896. {
  1897. for (int i = 0; i < m_comps_in_scan; i++)
  1898. if (m_quant[m_comp_quant[m_comp_list[i]]] == nullptr)
  1899. stop_decoding(JPGD_UNDEFINED_QUANT_TABLE);
  1900. }
  1901. // Verifies that all the Huffman tables needed for this scan are available.
  1902. void jpeg_decoder::check_huff_tables()
  1903. {
  1904. for (int i = 0; i < m_comps_in_scan; i++)
  1905. {
  1906. if ((m_spectral_start == 0) && (m_huff_num[m_comp_dc_tab[m_comp_list[i]]] == nullptr))
  1907. stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
  1908. if ((m_spectral_end > 0) && (m_huff_num[m_comp_ac_tab[m_comp_list[i]]] == nullptr))
  1909. stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
  1910. }
  1911. for (int i = 0; i < JPGD_MAX_HUFF_TABLES; i++)
  1912. if (m_huff_num[i])
  1913. {
  1914. if (!m_pHuff_tabs[i])
  1915. m_pHuff_tabs[i] = (huff_tables*)alloc(sizeof(huff_tables));
  1916. make_huff_table(i, m_pHuff_tabs[i]);
  1917. }
  1918. }
  1919. // Determines the component order inside each MCU.
  1920. // Also calcs how many MCU's are on each row, etc.
  1921. bool jpeg_decoder::calc_mcu_block_order()
  1922. {
  1923. int component_num, component_id;
  1924. int max_h_samp = 0, max_v_samp = 0;
  1925. for (component_id = 0; component_id < m_comps_in_frame; component_id++)
  1926. {
  1927. if (m_comp_h_samp[component_id] > max_h_samp)
  1928. max_h_samp = m_comp_h_samp[component_id];
  1929. if (m_comp_v_samp[component_id] > max_v_samp)
  1930. max_v_samp = m_comp_v_samp[component_id];
  1931. }
  1932. for (component_id = 0; component_id < m_comps_in_frame; component_id++)
  1933. {
  1934. m_comp_h_blocks[component_id] = ((((m_image_x_size * m_comp_h_samp[component_id]) + (max_h_samp - 1)) / max_h_samp) + 7) / 8;
  1935. m_comp_v_blocks[component_id] = ((((m_image_y_size * m_comp_v_samp[component_id]) + (max_v_samp - 1)) / max_v_samp) + 7) / 8;
  1936. }
  1937. if (m_comps_in_scan == 1)
  1938. {
  1939. m_mcus_per_row = m_comp_h_blocks[m_comp_list[0]];
  1940. m_mcus_per_col = m_comp_v_blocks[m_comp_list[0]];
  1941. }
  1942. else
  1943. {
  1944. m_mcus_per_row = (((m_image_x_size + 7) / 8) + (max_h_samp - 1)) / max_h_samp;
  1945. m_mcus_per_col = (((m_image_y_size + 7) / 8) + (max_v_samp - 1)) / max_v_samp;
  1946. }
  1947. if (m_comps_in_scan == 1)
  1948. {
  1949. m_mcu_org[0] = m_comp_list[0];
  1950. m_blocks_per_mcu = 1;
  1951. }
  1952. else
  1953. {
  1954. m_blocks_per_mcu = 0;
  1955. for (component_num = 0; component_num < m_comps_in_scan; component_num++)
  1956. {
  1957. int num_blocks;
  1958. component_id = m_comp_list[component_num];
  1959. num_blocks = m_comp_h_samp[component_id] * m_comp_v_samp[component_id];
  1960. while (num_blocks--)
  1961. m_mcu_org[m_blocks_per_mcu++] = component_id;
  1962. }
  1963. }
  1964. if (m_blocks_per_mcu > m_max_blocks_per_mcu)
  1965. return false;
  1966. for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
  1967. {
  1968. int comp_id = m_mcu_org[mcu_block];
  1969. if (comp_id >= JPGD_MAX_QUANT_TABLES)
  1970. return false;
  1971. }
  1972. return true;
  1973. }
  1974. // Starts a new scan.
  1975. int jpeg_decoder::init_scan()
  1976. {
  1977. if (!locate_sos_marker())
  1978. return JPGD_FALSE;
  1979. if (!calc_mcu_block_order())
  1980. return JPGD_FALSE;
  1981. check_huff_tables();
  1982. check_quant_tables();
  1983. memset(m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
  1984. m_eob_run = 0;
  1985. if (m_restart_interval)
  1986. {
  1987. m_restarts_left = m_restart_interval;
  1988. m_next_restart_num = 0;
  1989. }
  1990. fix_in_buffer();
  1991. return JPGD_TRUE;
  1992. }
  1993. // Starts a frame. Determines if the number of components or sampling factors
  1994. // are supported.
  1995. void jpeg_decoder::init_frame()
  1996. {
  1997. int i;
  1998. if (m_comps_in_frame == 1)
  1999. {
  2000. if ((m_comp_h_samp[0] != 1) || (m_comp_v_samp[0] != 1))
  2001. stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
  2002. m_scan_type = JPGD_GRAYSCALE;
  2003. m_max_blocks_per_mcu = 1;
  2004. m_max_mcu_x_size = 8;
  2005. m_max_mcu_y_size = 8;
  2006. }
  2007. else if (m_comps_in_frame == 3)
  2008. {
  2009. if (((m_comp_h_samp[1] != 1) || (m_comp_v_samp[1] != 1)) ||
  2010. ((m_comp_h_samp[2] != 1) || (m_comp_v_samp[2] != 1)))
  2011. stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
  2012. if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1))
  2013. {
  2014. m_scan_type = JPGD_YH1V1;
  2015. m_max_blocks_per_mcu = 3;
  2016. m_max_mcu_x_size = 8;
  2017. m_max_mcu_y_size = 8;
  2018. }
  2019. else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1))
  2020. {
  2021. m_scan_type = JPGD_YH2V1;
  2022. m_max_blocks_per_mcu = 4;
  2023. m_max_mcu_x_size = 16;
  2024. m_max_mcu_y_size = 8;
  2025. }
  2026. else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 2))
  2027. {
  2028. m_scan_type = JPGD_YH1V2;
  2029. m_max_blocks_per_mcu = 4;
  2030. m_max_mcu_x_size = 8;
  2031. m_max_mcu_y_size = 16;
  2032. }
  2033. else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2))
  2034. {
  2035. m_scan_type = JPGD_YH2V2;
  2036. m_max_blocks_per_mcu = 6;
  2037. m_max_mcu_x_size = 16;
  2038. m_max_mcu_y_size = 16;
  2039. }
  2040. else
  2041. stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
  2042. }
  2043. else
  2044. stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
  2045. m_max_mcus_per_row = (m_image_x_size + (m_max_mcu_x_size - 1)) / m_max_mcu_x_size;
  2046. m_max_mcus_per_col = (m_image_y_size + (m_max_mcu_y_size - 1)) / m_max_mcu_y_size;
  2047. // These values are for the *destination* pixels: after conversion.
  2048. if (m_scan_type == JPGD_GRAYSCALE)
  2049. m_dest_bytes_per_pixel = 1;
  2050. else
  2051. m_dest_bytes_per_pixel = 4;
  2052. m_dest_bytes_per_scan_line = ((m_image_x_size + 15) & 0xFFF0) * m_dest_bytes_per_pixel;
  2053. m_real_dest_bytes_per_scan_line = (m_image_x_size * m_dest_bytes_per_pixel);
  2054. // Initialize two scan line buffers.
  2055. m_pScan_line_0 = (uint8*)alloc(m_dest_bytes_per_scan_line, true);
  2056. if ((m_scan_type == JPGD_YH1V2) || (m_scan_type == JPGD_YH2V2))
  2057. m_pScan_line_1 = (uint8*)alloc(m_dest_bytes_per_scan_line, true);
  2058. m_max_blocks_per_row = m_max_mcus_per_row * m_max_blocks_per_mcu;
  2059. // Should never happen
  2060. if (m_max_blocks_per_row > JPGD_MAX_BLOCKS_PER_ROW)
  2061. stop_decoding(JPGD_DECODE_ERROR);
  2062. // Allocate the coefficient buffer, enough for one MCU
  2063. m_pMCU_coefficients = (jpgd_block_t*)alloc(m_max_blocks_per_mcu * 64 * sizeof(jpgd_block_t));
  2064. for (i = 0; i < m_max_blocks_per_mcu; i++)
  2065. m_mcu_block_max_zag[i] = 64;
  2066. m_pSample_buf = (uint8*)alloc(m_max_blocks_per_row * 64);
  2067. m_pSample_buf_prev = (uint8*)alloc(m_max_blocks_per_row * 64);
  2068. m_total_lines_left = m_image_y_size;
  2069. m_mcu_lines_left = 0;
  2070. create_look_ups();
  2071. }
  2072. // The coeff_buf series of methods originally stored the coefficients
  2073. // into a "virtual" file which was located in EMS, XMS, or a disk file. A cache
  2074. // was used to make this process more efficient. Now, we can store the entire
  2075. // thing in RAM.
  2076. jpeg_decoder::coeff_buf* jpeg_decoder::coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y)
  2077. {
  2078. coeff_buf* cb = (coeff_buf*)alloc(sizeof(coeff_buf));
  2079. cb->block_num_x = block_num_x;
  2080. cb->block_num_y = block_num_y;
  2081. cb->block_len_x = block_len_x;
  2082. cb->block_len_y = block_len_y;
  2083. cb->block_size = (block_len_x * block_len_y) * sizeof(jpgd_block_t);
  2084. cb->pData = (uint8*)alloc(cb->block_size * block_num_x * block_num_y, true);
  2085. return cb;
  2086. }
  2087. inline jpgd_block_t* jpeg_decoder::coeff_buf_getp(coeff_buf* cb, int block_x, int block_y)
  2088. {
  2089. if ((block_x >= cb->block_num_x) || (block_y >= cb->block_num_y))
  2090. stop_decoding(JPGD_DECODE_ERROR);
  2091. return (jpgd_block_t*)(cb->pData + block_x * cb->block_size + block_y * (cb->block_size * cb->block_num_x));
  2092. }
  2093. // The following methods decode the various types of m_blocks encountered
  2094. // in progressively encoded images.
  2095. void jpeg_decoder::decode_block_dc_first(jpeg_decoder* pD, int component_id, int block_x, int block_y)
  2096. {
  2097. int s, r;
  2098. jpgd_block_t* p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
  2099. if ((s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_dc_tab[component_id]])) != 0)
  2100. {
  2101. if (s >= 16)
  2102. pD->stop_decoding(JPGD_DECODE_ERROR);
  2103. r = pD->get_bits_no_markers(s);
  2104. s = JPGD_HUFF_EXTEND(r, s);
  2105. }
  2106. pD->m_last_dc_val[component_id] = (s += pD->m_last_dc_val[component_id]);
  2107. p[0] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
  2108. }
  2109. void jpeg_decoder::decode_block_dc_refine(jpeg_decoder* pD, int component_id, int block_x, int block_y)
  2110. {
  2111. if (pD->get_bits_no_markers(1))
  2112. {
  2113. jpgd_block_t* p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
  2114. p[0] |= (1 << pD->m_successive_low);
  2115. }
  2116. }
  2117. void jpeg_decoder::decode_block_ac_first(jpeg_decoder* pD, int component_id, int block_x, int block_y)
  2118. {
  2119. int k, s, r;
  2120. if (pD->m_eob_run)
  2121. {
  2122. pD->m_eob_run--;
  2123. return;
  2124. }
  2125. jpgd_block_t* p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
  2126. for (k = pD->m_spectral_start; k <= pD->m_spectral_end; k++)
  2127. {
  2128. unsigned int idx = pD->m_comp_ac_tab[component_id];
  2129. if (idx >= JPGD_MAX_HUFF_TABLES)
  2130. pD->stop_decoding(JPGD_DECODE_ERROR);
  2131. s = pD->huff_decode(pD->m_pHuff_tabs[idx]);
  2132. r = s >> 4;
  2133. s &= 15;
  2134. if (s)
  2135. {
  2136. if ((k += r) > 63)
  2137. pD->stop_decoding(JPGD_DECODE_ERROR);
  2138. r = pD->get_bits_no_markers(s);
  2139. s = JPGD_HUFF_EXTEND(r, s);
  2140. p[g_ZAG[k]] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
  2141. }
  2142. else
  2143. {
  2144. if (r == 15)
  2145. {
  2146. if ((k += 15) > 63)
  2147. pD->stop_decoding(JPGD_DECODE_ERROR);
  2148. }
  2149. else
  2150. {
  2151. pD->m_eob_run = 1 << r;
  2152. if (r)
  2153. pD->m_eob_run += pD->get_bits_no_markers(r);
  2154. pD->m_eob_run--;
  2155. break;
  2156. }
  2157. }
  2158. }
  2159. }
  2160. void jpeg_decoder::decode_block_ac_refine(jpeg_decoder* pD, int component_id, int block_x, int block_y)
  2161. {
  2162. int s, k, r;
  2163. int p1 = 1 << pD->m_successive_low;
  2164. //int m1 = (-1) << pD->m_successive_low;
  2165. int m1 = static_cast<int>((UINT32_MAX << pD->m_successive_low));
  2166. jpgd_block_t* p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
  2167. if (pD->m_spectral_end > 63)
  2168. pD->stop_decoding(JPGD_DECODE_ERROR);
  2169. k = pD->m_spectral_start;
  2170. if (pD->m_eob_run == 0)
  2171. {
  2172. for (; k <= pD->m_spectral_end; k++)
  2173. {
  2174. unsigned int idx = pD->m_comp_ac_tab[component_id];
  2175. if (idx >= JPGD_MAX_HUFF_TABLES)
  2176. pD->stop_decoding(JPGD_DECODE_ERROR);
  2177. s = pD->huff_decode(pD->m_pHuff_tabs[idx]);
  2178. r = s >> 4;
  2179. s &= 15;
  2180. if (s)
  2181. {
  2182. if (s != 1)
  2183. pD->stop_decoding(JPGD_DECODE_ERROR);
  2184. if (pD->get_bits_no_markers(1))
  2185. s = p1;
  2186. else
  2187. s = m1;
  2188. }
  2189. else
  2190. {
  2191. if (r != 15)
  2192. {
  2193. pD->m_eob_run = 1 << r;
  2194. if (r)
  2195. pD->m_eob_run += pD->get_bits_no_markers(r);
  2196. break;
  2197. }
  2198. }
  2199. do
  2200. {
  2201. jpgd_block_t* this_coef = p + g_ZAG[k & 63];
  2202. if (*this_coef != 0)
  2203. {
  2204. if (pD->get_bits_no_markers(1))
  2205. {
  2206. if ((*this_coef & p1) == 0)
  2207. {
  2208. if (*this_coef >= 0)
  2209. *this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
  2210. else
  2211. *this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
  2212. }
  2213. }
  2214. }
  2215. else
  2216. {
  2217. if (--r < 0)
  2218. break;
  2219. }
  2220. k++;
  2221. } while (k <= pD->m_spectral_end);
  2222. if ((s) && (k < 64))
  2223. {
  2224. p[g_ZAG[k]] = static_cast<jpgd_block_t>(s);
  2225. }
  2226. }
  2227. }
  2228. if (pD->m_eob_run > 0)
  2229. {
  2230. for (; k <= pD->m_spectral_end; k++)
  2231. {
  2232. jpgd_block_t* this_coef = p + g_ZAG[k & 63]; // logical AND to shut up static code analysis
  2233. if (*this_coef != 0)
  2234. {
  2235. if (pD->get_bits_no_markers(1))
  2236. {
  2237. if ((*this_coef & p1) == 0)
  2238. {
  2239. if (*this_coef >= 0)
  2240. *this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
  2241. else
  2242. *this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
  2243. }
  2244. }
  2245. }
  2246. }
  2247. pD->m_eob_run--;
  2248. }
  2249. }
  2250. // Decode a scan in a progressively encoded image.
  2251. void jpeg_decoder::decode_scan(pDecode_block_func decode_block_func)
  2252. {
  2253. int mcu_row, mcu_col, mcu_block;
  2254. int block_x_mcu[JPGD_MAX_COMPONENTS], block_y_mcu[JPGD_MAX_COMPONENTS];
  2255. memset(block_y_mcu, 0, sizeof(block_y_mcu));
  2256. for (mcu_col = 0; mcu_col < m_mcus_per_col; mcu_col++)
  2257. {
  2258. int component_num, component_id;
  2259. memset(block_x_mcu, 0, sizeof(block_x_mcu));
  2260. for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
  2261. {
  2262. int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
  2263. if ((m_restart_interval) && (m_restarts_left == 0))
  2264. process_restart();
  2265. for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
  2266. {
  2267. component_id = m_mcu_org[mcu_block];
  2268. decode_block_func(this, component_id, block_x_mcu[component_id] + block_x_mcu_ofs, block_y_mcu[component_id] + block_y_mcu_ofs);
  2269. if (m_comps_in_scan == 1)
  2270. block_x_mcu[component_id]++;
  2271. else
  2272. {
  2273. if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
  2274. {
  2275. block_x_mcu_ofs = 0;
  2276. if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
  2277. {
  2278. block_y_mcu_ofs = 0;
  2279. block_x_mcu[component_id] += m_comp_h_samp[component_id];
  2280. }
  2281. }
  2282. }
  2283. }
  2284. m_restarts_left--;
  2285. }
  2286. if (m_comps_in_scan == 1)
  2287. block_y_mcu[m_comp_list[0]]++;
  2288. else
  2289. {
  2290. for (component_num = 0; component_num < m_comps_in_scan; component_num++)
  2291. {
  2292. component_id = m_comp_list[component_num];
  2293. block_y_mcu[component_id] += m_comp_v_samp[component_id];
  2294. }
  2295. }
  2296. }
  2297. }
  2298. // Decode a progressively encoded image.
  2299. void jpeg_decoder::init_progressive()
  2300. {
  2301. int i;
  2302. if (m_comps_in_frame == 4)
  2303. stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
  2304. // Allocate the coefficient buffers.
  2305. for (i = 0; i < m_comps_in_frame; i++)
  2306. {
  2307. m_dc_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 1, 1);
  2308. m_ac_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 8, 8);
  2309. }
  2310. // See https://libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
  2311. uint32_t total_scans = 0;
  2312. const uint32_t MAX_SCANS_TO_PROCESS = 1000;
  2313. for (; ; )
  2314. {
  2315. int dc_only_scan, refinement_scan;
  2316. pDecode_block_func decode_block_func;
  2317. if (!init_scan())
  2318. break;
  2319. dc_only_scan = (m_spectral_start == 0);
  2320. refinement_scan = (m_successive_high != 0);
  2321. if ((m_spectral_start > m_spectral_end) || (m_spectral_end > 63))
  2322. stop_decoding(JPGD_BAD_SOS_SPECTRAL);
  2323. if (dc_only_scan)
  2324. {
  2325. if (m_spectral_end)
  2326. stop_decoding(JPGD_BAD_SOS_SPECTRAL);
  2327. }
  2328. else if (m_comps_in_scan != 1) /* AC scans can only contain one component */
  2329. stop_decoding(JPGD_BAD_SOS_SPECTRAL);
  2330. if ((refinement_scan) && (m_successive_low != m_successive_high - 1))
  2331. stop_decoding(JPGD_BAD_SOS_SUCCESSIVE);
  2332. if (dc_only_scan)
  2333. {
  2334. if (refinement_scan)
  2335. decode_block_func = decode_block_dc_refine;
  2336. else
  2337. decode_block_func = decode_block_dc_first;
  2338. }
  2339. else
  2340. {
  2341. if (refinement_scan)
  2342. decode_block_func = decode_block_ac_refine;
  2343. else
  2344. decode_block_func = decode_block_ac_first;
  2345. }
  2346. decode_scan(decode_block_func);
  2347. m_bits_left = 16;
  2348. get_bits(16);
  2349. get_bits(16);
  2350. total_scans++;
  2351. if (total_scans > MAX_SCANS_TO_PROCESS)
  2352. stop_decoding(JPGD_TOO_MANY_SCANS);
  2353. }
  2354. m_comps_in_scan = m_comps_in_frame;
  2355. for (i = 0; i < m_comps_in_frame; i++)
  2356. m_comp_list[i] = i;
  2357. if (!calc_mcu_block_order())
  2358. stop_decoding(JPGD_DECODE_ERROR);
  2359. }
  2360. void jpeg_decoder::init_sequential()
  2361. {
  2362. if (!init_scan())
  2363. stop_decoding(JPGD_UNEXPECTED_MARKER);
  2364. }
  2365. void jpeg_decoder::decode_start()
  2366. {
  2367. init_frame();
  2368. if (m_progressive_flag)
  2369. init_progressive();
  2370. else
  2371. init_sequential();
  2372. }
  2373. void jpeg_decoder::decode_init(jpeg_decoder_stream* pStream, uint32_t flags)
  2374. {
  2375. init(pStream, flags);
  2376. locate_sof_marker();
  2377. }
  2378. jpeg_decoder::jpeg_decoder(jpeg_decoder_stream* pStream, uint32_t flags)
  2379. {
  2380. if (setjmp(m_jmp_state))
  2381. return;
  2382. decode_init(pStream, flags);
  2383. }
  2384. int jpeg_decoder::begin_decoding()
  2385. {
  2386. if (m_ready_flag)
  2387. return JPGD_SUCCESS;
  2388. if (m_error_code)
  2389. return JPGD_FAILED;
  2390. if (setjmp(m_jmp_state))
  2391. return JPGD_FAILED;
  2392. decode_start();
  2393. m_ready_flag = true;
  2394. return JPGD_SUCCESS;
  2395. }
  2396. jpeg_decoder::~jpeg_decoder()
  2397. {
  2398. free_all_blocks();
  2399. }
  2400. jpeg_decoder_file_stream::jpeg_decoder_file_stream()
  2401. {
  2402. m_pFile = nullptr;
  2403. m_eof_flag = false;
  2404. m_error_flag = false;
  2405. }
  2406. void jpeg_decoder_file_stream::close()
  2407. {
  2408. if (m_pFile)
  2409. {
  2410. fclose(m_pFile);
  2411. m_pFile = nullptr;
  2412. }
  2413. m_eof_flag = false;
  2414. m_error_flag = false;
  2415. }
  2416. jpeg_decoder_file_stream::~jpeg_decoder_file_stream()
  2417. {
  2418. close();
  2419. }
  2420. bool jpeg_decoder_file_stream::open(const char* Pfilename)
  2421. {
  2422. close();
  2423. m_eof_flag = false;
  2424. m_error_flag = false;
  2425. #if defined(_MSC_VER)
  2426. m_pFile = nullptr;
  2427. fopen_s(&m_pFile, Pfilename, "rb");
  2428. #else
  2429. m_pFile = fopen(Pfilename, "rb");
  2430. #endif
  2431. return m_pFile != nullptr;
  2432. }
  2433. int jpeg_decoder_file_stream::read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag)
  2434. {
  2435. if (!m_pFile)
  2436. return -1;
  2437. if (m_eof_flag)
  2438. {
  2439. *pEOF_flag = true;
  2440. return 0;
  2441. }
  2442. if (m_error_flag)
  2443. return -1;
  2444. int bytes_read = static_cast<int>(fread(pBuf, 1, max_bytes_to_read, m_pFile));
  2445. if (bytes_read < max_bytes_to_read)
  2446. {
  2447. if (ferror(m_pFile))
  2448. {
  2449. m_error_flag = true;
  2450. return -1;
  2451. }
  2452. m_eof_flag = true;
  2453. *pEOF_flag = true;
  2454. }
  2455. return bytes_read;
  2456. }
  2457. bool jpeg_decoder_mem_stream::open(const uint8* pSrc_data, uint size)
  2458. {
  2459. close();
  2460. m_pSrc_data = pSrc_data;
  2461. m_ofs = 0;
  2462. m_size = size;
  2463. return true;
  2464. }
  2465. int jpeg_decoder_mem_stream::read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag)
  2466. {
  2467. *pEOF_flag = false;
  2468. if (!m_pSrc_data)
  2469. return -1;
  2470. uint bytes_remaining = m_size - m_ofs;
  2471. if ((uint)max_bytes_to_read > bytes_remaining)
  2472. {
  2473. max_bytes_to_read = bytes_remaining;
  2474. *pEOF_flag = true;
  2475. }
  2476. memcpy(pBuf, m_pSrc_data + m_ofs, max_bytes_to_read);
  2477. m_ofs += max_bytes_to_read;
  2478. return max_bytes_to_read;
  2479. }
  2480. unsigned char* decompress_jpeg_image_from_stream(jpeg_decoder_stream* pStream, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags)
  2481. {
  2482. if (!actual_comps)
  2483. return nullptr;
  2484. *actual_comps = 0;
  2485. if ((!pStream) || (!width) || (!height) || (!req_comps))
  2486. return nullptr;
  2487. if ((req_comps != 1) && (req_comps != 3) && (req_comps != 4))
  2488. return nullptr;
  2489. jpeg_decoder decoder(pStream, flags);
  2490. if (decoder.get_error_code() != JPGD_SUCCESS)
  2491. return nullptr;
  2492. const int image_width = decoder.get_width(), image_height = decoder.get_height();
  2493. *width = image_width;
  2494. *height = image_height;
  2495. *actual_comps = decoder.get_num_components();
  2496. if (decoder.begin_decoding() != JPGD_SUCCESS)
  2497. return nullptr;
  2498. const int dst_bpl = image_width * req_comps;
  2499. uint8* pImage_data = (uint8*)jpgd_malloc(dst_bpl * image_height);
  2500. if (!pImage_data)
  2501. return nullptr;
  2502. for (int y = 0; y < image_height; y++)
  2503. {
  2504. const uint8* pScan_line;
  2505. uint scan_line_len;
  2506. if (decoder.decode((const void**)&pScan_line, &scan_line_len) != JPGD_SUCCESS)
  2507. {
  2508. jpgd_free(pImage_data);
  2509. return nullptr;
  2510. }
  2511. uint8* pDst = pImage_data + y * dst_bpl;
  2512. if (((req_comps == 1) && (decoder.get_num_components() == 1)) || ((req_comps == 4) && (decoder.get_num_components() == 3)))
  2513. memcpy(pDst, pScan_line, dst_bpl);
  2514. else if (decoder.get_num_components() == 1)
  2515. {
  2516. if (req_comps == 3)
  2517. {
  2518. for (int x = 0; x < image_width; x++)
  2519. {
  2520. uint8 luma = pScan_line[x];
  2521. pDst[0] = luma;
  2522. pDst[1] = luma;
  2523. pDst[2] = luma;
  2524. pDst += 3;
  2525. }
  2526. }
  2527. else
  2528. {
  2529. for (int x = 0; x < image_width; x++)
  2530. {
  2531. uint8 luma = pScan_line[x];
  2532. pDst[0] = luma;
  2533. pDst[1] = luma;
  2534. pDst[2] = luma;
  2535. pDst[3] = 255;
  2536. pDst += 4;
  2537. }
  2538. }
  2539. }
  2540. else if (decoder.get_num_components() == 3)
  2541. {
  2542. if (req_comps == 1)
  2543. {
  2544. const int YR = 19595, YG = 38470, YB = 7471;
  2545. for (int x = 0; x < image_width; x++)
  2546. {
  2547. int r = pScan_line[x * 4 + 0];
  2548. int g = pScan_line[x * 4 + 1];
  2549. int b = pScan_line[x * 4 + 2];
  2550. *pDst++ = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
  2551. }
  2552. }
  2553. else
  2554. {
  2555. for (int x = 0; x < image_width; x++)
  2556. {
  2557. pDst[0] = pScan_line[x * 4 + 0];
  2558. pDst[1] = pScan_line[x * 4 + 1];
  2559. pDst[2] = pScan_line[x * 4 + 2];
  2560. pDst += 3;
  2561. }
  2562. }
  2563. }
  2564. }
  2565. return pImage_data;
  2566. }
  2567. unsigned char* decompress_jpeg_image_from_memory(const unsigned char* pSrc_data, int src_data_size, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags)
  2568. {
  2569. jpgd::jpeg_decoder_mem_stream mem_stream(pSrc_data, src_data_size);
  2570. return decompress_jpeg_image_from_stream(&mem_stream, width, height, actual_comps, req_comps, flags);
  2571. }
  2572. unsigned char* decompress_jpeg_image_from_file(const char* pSrc_filename, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags)
  2573. {
  2574. jpgd::jpeg_decoder_file_stream file_stream;
  2575. if (!file_stream.open(pSrc_filename))
  2576. return nullptr;
  2577. return decompress_jpeg_image_from_stream(&file_stream, width, height, actual_comps, req_comps, flags);
  2578. }
  2579. } // namespace jpgd