11/*!
22 * JPEG codec. This software is based in part on the work of the Independent JPEG Group: the IDCT, FDCT, upsampling,
3- * downsampling, color conversion, quantization, progressive refinement and optimal Huffman tables are translated from
4- * libjpeg/libjpeg-turbo (IJG license, see licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js
3+ * downsampling, color conversion, quantization, progressive refinement and encoding and optimal Huffman tables are
4+ * translated from libjpeg/libjpeg-turbo, and the progressive scan script is mozjpeg's (IJG license, see
5+ * licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js
56 * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md
67 */
78
@@ -1544,14 +1545,16 @@ export interface EncodeMetadata {
15441545 fullChroma ?: boolean ;
15451546 /** the chroma subsampling, overriding the default by quality (4:2:0 up to 90, 4:4:4 above) */
15461547 subsampling ?: '4:4:4' | '4:2:0' ;
1548+ /** whether to write a progressive JPEG (mozjpeg's scans, each with Huffman tables made for it) */
1549+ progressive ?: boolean ;
15471550 /**
15481551 * with it, `pixels` is the one row of scratch pixels (width * 4 bytes): `rows(y)` fills it with row y before the
15491552 * row is read, so the pixels need not be in memory whole (the image composited onto a background, row by row)
15501553 */
15511554 rows ?: ( y : number ) => void ;
15521555}
15531556
1554- export function encode ( pixels : Uint8Array , width : number , height : number , quality = 90 , { exif, comment, segments, gray = false , fullChroma = false , subsampling, rows } : EncodeMetadata = { } ) : Uint8Array < ArrayBuffer > {
1557+ export function encode ( pixels : Uint8Array , width : number , height : number , quality = 90 , { exif, comment, segments, gray = false , fullChroma = false , subsampling, progressive = false , rows } : EncodeMetadata = { } ) : Uint8Array < ArrayBuffer > {
15551558 if ( ! width || ! height ) throw new RangeError ( 'JPEG: invalid dimensions' ) ;
15561559 checkFormatSize ( 'JPEG' , width , height , 0xffff ) ;
15571560
@@ -1678,11 +1681,11 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit
16781681
16791682 const blocks = { coefficients, owners, ends, count } ;
16801683
1681- // pass 1: gather symbol statistics, pass 2: write with optimal tables
1684+ // (sequential: pass 1 gathers symbol statistics, pass 2 writes with optimal tables; progressive: both per scan)
16821685 const frequencies = [ new Int32Array ( 257 ) , new Int32Array ( 257 ) , new Int32Array ( 257 ) , new Int32Array ( 257 ) ] ;
1683- countSymbols ( blocks , frequencies ) ;
1686+ if ( ! progressive ) countSymbols ( blocks , frequencies ) ;
16841687
1685- const huffman = frequencies . slice ( 0 , gray ? 2 : 4 ) . map ( buildOptimalTable ) ;
1688+ const huffman = progressive ? [ ] : frequencies . slice ( 0 , gray ? 2 : 4 ) . map ( buildOptimalTable ) ;
16861689 const writer = new BitWriter ( width * height ) ;
16871690
16881691 writer . bytes ( 0xff , 0xd8 ) ;
@@ -1704,13 +1707,22 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit
17041707 for ( let k = 0 ; k < 64 ; k ++ ) writer . bytes ( tables [ t ] [ ZIGZAG [ k ] ] ) ;
17051708 }
17061709
1707- // SOF0
1708- if ( gray ) writer . bytes ( 0xff , 0xc0 , 0x00 , 0x0b , 0x08 , height >> 8 , height & 0xff , width >> 8 , width & 0xff , 0x01 , 1 , 0x11 , 0 ) ;
1710+ // SOF0, or SOF2 for progressive
1711+ const sof = progressive ? 0xc2 : 0xc0 ;
1712+ if ( gray ) writer . bytes ( 0xff , sof , 0x00 , 0x0b , 0x08 , height >> 8 , height & 0xff , width >> 8 , width & 0xff , 0x01 , 1 , 0x11 , 0 ) ;
17091713 else {
1710- writer . bytes ( 0xff , 0xc0 , 0x00 , 0x11 , 0x08 , height >> 8 , height & 0xff , width >> 8 , width & 0xff , 0x03 ) ;
1714+ writer . bytes ( 0xff , sof , 0x00 , 0x11 , 0x08 , height >> 8 , height & 0xff , width >> 8 , width & 0xff , 0x03 ) ;
17111715 writer . bytes ( 1 , hmax << 4 | hmax , 0 , 2 , 0x11 , 1 , 3 , 0x11 , 1 ) ;
17121716 }
17131717
1718+ if ( progressive ) {
1719+ // (the blocks of a component, by position, in MCU order: the MCU, then the block in it)
1720+ const layout = components . slice ( 0 , componentCount ) . map ( ( component , c ) => ( { ...component , offset : c === 0 ? 0 : hmax * hmax + c - 1 } ) ) ;
1721+ writeProgressive ( writer , progressiveScans ( componentCount ) , blocks , layout , mcusPerLine , blocksPerMcu ) ;
1722+ writer . bytes ( 0xff , 0xd9 ) ;
1723+ return writer . finish ( ) ;
1724+ }
1725+
17141726 // DHT: luma DC, luma AC, chroma DC, chroma AC
17151727 for ( const [ index , id ] of ( [ [ 0 , 0x00 ] , [ 1 , 0x10 ] , [ 2 , 0x01 ] , [ 3 , 0x11 ] ] as Array < [ number , number ] > ) . slice ( 0 , gray ? 2 : 4 ) ) {
17161728 const { bits, values } = huffman [ index ] ;
@@ -1730,6 +1742,258 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit
17301742 return writer . finish ( ) ;
17311743}
17321744
1745+ // a progressive scan: the components (by index) and the band of coefficients (in zigzag order) it holds, and the bit
1746+ // of the coefficients it starts at (Al) and refines from (Ah, 0 for the first scan of a band)
1747+ interface Scan {
1748+ comps : number [ ] ;
1749+ ss : number ;
1750+ se : number ;
1751+ ah : number ;
1752+ al : number ;
1753+ }
1754+
1755+ // mozjpeg's script (jpeg_simple_progression of its jcparam.c, the max compression profile), which makes smaller files
1756+ // than libjpeg's ten scans (libjpeg-turbo's: DC at two bits, luma 1-5, chroma, luma 6-63 each at lower bits and refined
1757+ // later): the DC first, the luma's lowest frequencies and the rest of its AC at one bit less than full, that bit
1758+ // last, and each chroma component's AC in two bands
1759+ function progressiveScans ( componentCount : number ) : Scan [ ] {
1760+ const dc : Scan = { comps : Array . from ( { length : componentCount } , ( _ , c ) => c ) , ss : 0 , se : 0 , ah : 0 , al : 0 } ;
1761+ const ac = ( comp : number , ss : number , se : number , ah : number , al : number ) : Scan => ( { comps : [ comp ] , ss, se, ah, al } ) ;
1762+
1763+ const luma = [ ac ( 0 , 1 , 2 , 0 , 1 ) , ac ( 0 , 3 , 63 , 0 , 1 ) , ac ( 0 , 1 , 63 , 1 , 0 ) ] ;
1764+ if ( componentCount === 1 ) return [ dc , ...luma ] ;
1765+ return [ dc , ...luma , ac ( 1 , 1 , 8 , 0 , 0 ) , ac ( 1 , 9 , 63 , 0 , 0 ) , ac ( 2 , 1 , 8 , 0 , 0 ) , ac ( 2 , 9 , 63 , 0 , 0 ) ] ;
1766+ }
1767+
1768+ // correction bits of refinement scans wait for the end-of-band run they belong to: at most this many (jcphuff.c)
1769+ const MAX_CORR_BITS = 1000 ;
1770+
1771+ interface ProgressiveComponent {
1772+ h : number ;
1773+ v : number ;
1774+ blocksX : number ;
1775+ blocksY : number ;
1776+ offset : number ;
1777+ }
1778+
1779+ // jcphuff.c's encoders of one scan: counts the symbols of its Huffman tables (`counts`), or writes the scan with them
1780+ // (`tables`)
1781+ class ScanCoder {
1782+ private eobrun = 0 ;
1783+ // correction bits waiting for the end-of-band run, and how many
1784+ private readonly pending = new Uint8Array ( MAX_CORR_BITS ) ;
1785+ private waiting = 0 ;
1786+ private readonly magnitudes = new Int32Array ( 64 ) ;
1787+
1788+ private readonly writer : BitWriter ;
1789+ private readonly counts : Int32Array [ ] | null ;
1790+ private readonly tables : OptimalTable [ ] | null ;
1791+
1792+ constructor ( writer : BitWriter , counts : Int32Array [ ] | null , tables : OptimalTable [ ] | null ) {
1793+ this . writer = writer ;
1794+ this . counts = counts ;
1795+ this . tables = tables ;
1796+ }
1797+
1798+ private symbol ( table : number , symbol : number ) : void {
1799+ if ( this . counts ) this . counts [ table ] [ symbol ] ++ ;
1800+ else {
1801+ const { codes, sizes } = ( this . tables as OptimalTable [ ] ) [ table ] ;
1802+ this . writer . write ( codes [ symbol ] , sizes [ symbol ] ) ;
1803+ }
1804+ }
1805+
1806+ private bits ( value : number , size : number ) : void {
1807+ if ( ! this . counts ) this . writer . write ( value , size ) ;
1808+ }
1809+
1810+ private buffered ( start : number , count : number ) : void {
1811+ if ( ! this . counts ) for ( let i = 0 ; i < count ; i ++ ) this . writer . write ( this . pending [ start + i ] , 1 ) ;
1812+ }
1813+
1814+ private emitEobrun ( table : number ) : void {
1815+ if ( this . eobrun === 0 ) return ;
1816+ const nbits = 31 - Math . clz32 ( this . eobrun ) ;
1817+ this . symbol ( table , nbits << 4 ) ;
1818+ if ( nbits ) this . bits ( this . eobrun , nbits ) ;
1819+ this . eobrun = 0 ;
1820+ // (the correction bits that go with it)
1821+ this . buffered ( 0 , this . waiting ) ;
1822+ this . waiting = 0 ;
1823+ }
1824+
1825+ /** the first scan of the DC coefficients (point transform Al): the differences of the shifted values */
1826+ dcFirst ( coefficients : Int16Array , owners : Uint8Array , count : number , last : number [ ] , al : number ) : void {
1827+ for ( let n = 0 ; n < count ; n ++ ) {
1828+ const component = owners [ n ] , table = component === 0 ? 0 : 1 ;
1829+ const value = coefficients [ n * 64 ] >> al , diff = value - last [ component ] ;
1830+ last [ component ] = value ;
1831+ const nbits = 32 - Math . clz32 ( Math . abs ( diff ) ) ;
1832+ this . symbol ( table , nbits ) ;
1833+ if ( nbits ) this . bits ( diff < 0 ? diff - 1 : diff , nbits ) ;
1834+ }
1835+ }
1836+
1837+ /** a refinement scan of the DC coefficients: their next bit */
1838+ dcRefine ( coefficients : Int16Array , count : number , al : number ) : void {
1839+ for ( let n = 0 ; n < count ; n ++ ) this . bits ( coefficients [ n * 64 ] >> al , 1 ) ;
1840+ }
1841+
1842+ /** the first scan of a band of AC coefficients of one block, whose last nonzero coefficient is `end` */
1843+ acFirst ( coefficients : Int16Array , o : number , end : number , table : number , ss : number , se : number , al : number ) : void {
1844+ // (the coefficients after the last nonzero one are zeros: a run)
1845+ const stop = Math . min ( se , end ) ;
1846+ let run = 0 ;
1847+ for ( let k = ss ; k <= stop ; k ++ ) {
1848+ let value = coefficients [ o + k ] ;
1849+ if ( value === 0 ) {
1850+ run ++ ;
1851+ continue ;
1852+ }
1853+ // (the point transform divides the magnitude, rounding toward zero)
1854+ let bits : number ;
1855+ if ( value < 0 ) {
1856+ value = - value >> al ;
1857+ bits = ~ value ;
1858+ } else {
1859+ value >>= al ;
1860+ bits = value ;
1861+ }
1862+ if ( value === 0 ) {
1863+ run ++ ;
1864+ continue ;
1865+ }
1866+
1867+ this . emitEobrun ( table ) ;
1868+ for ( ; run > 15 ; run -= 16 ) this . symbol ( table , 0xf0 ) ;
1869+ const nbits = 32 - Math . clz32 ( value ) ;
1870+ this . symbol ( table , run << 4 | nbits ) ;
1871+ this . bits ( bits , nbits ) ;
1872+ run = 0 ;
1873+ }
1874+
1875+ if ( stop < se ) run += se - Math . max ( stop , ss - 1 ) ;
1876+ if ( run > 0 ) {
1877+ this . eobrun ++ ;
1878+ if ( this . eobrun === 0x7fff ) this . emitEobrun ( table ) ;
1879+ }
1880+ }
1881+
1882+ /** a refinement scan of a band of AC coefficients of one block: the new nonzero ones and the next bit of the others */
1883+ acRefine ( coefficients : Int16Array , o : number , end : number , table : number , ss : number , se : number , al : number ) : void {
1884+ const magnitudes = this . magnitudes ;
1885+ const stop = Math . min ( se , end ) ;
1886+ // (the last coefficient that becomes nonzero: zero runs after it fold into the end of the band)
1887+ let eob = 0 ;
1888+ for ( let k = ss ; k <= stop ; k ++ ) {
1889+ const value = Math . abs ( coefficients [ o + k ] ) >> al ;
1890+ magnitudes [ k ] = value ;
1891+ if ( value === 1 ) eob = k ;
1892+ }
1893+
1894+ let run = 0 , start = this . waiting , count = 0 ;
1895+ for ( let k = ss ; k <= stop ; k ++ ) {
1896+ const value = magnitudes [ k ] ;
1897+ if ( value === 0 ) {
1898+ run ++ ;
1899+ continue ;
1900+ }
1901+
1902+ for ( ; run > 15 && k <= eob ; run -= 16 ) {
1903+ this . emitEobrun ( table ) ;
1904+ this . symbol ( table , 0xf0 ) ;
1905+ this . buffered ( start , count ) ;
1906+ start = 0 ;
1907+ count = 0 ;
1908+ }
1909+
1910+ // already nonzero: only its next bit
1911+ if ( value > 1 ) {
1912+ this . pending [ start + count ++ ] = value & 1 ;
1913+ continue ;
1914+ }
1915+
1916+ this . emitEobrun ( table ) ;
1917+ this . symbol ( table , run << 4 | 1 ) ;
1918+ this . bits ( coefficients [ o + k ] < 0 ? 0 : 1 , 1 ) ;
1919+ this . buffered ( start , count ) ;
1920+ start = 0 ;
1921+ count = 0 ;
1922+ run = 0 ;
1923+ }
1924+
1925+ if ( stop < se ) run += se - Math . max ( stop , ss - 1 ) ;
1926+ if ( run > 0 || count > 0 ) {
1927+ this . eobrun ++ ;
1928+ this . waiting += count ;
1929+ // (forced out before the run or the correction bits can overflow)
1930+ if ( this . eobrun === 0x7fff || this . waiting > MAX_CORR_BITS - 63 ) this . emitEobrun ( table ) ;
1931+ }
1932+ }
1933+
1934+ /** the end of the scan: the pending run */
1935+ finish ( table : number ) : void {
1936+ this . emitEobrun ( table ) ;
1937+ }
1938+ }
1939+
1940+ // the scans of a progressive JPEG, each with Huffman tables made for its own symbols (libjpeg writes progressive files
1941+ // with optimized tables: jcphuff.c, jcmarker.c)
1942+ function writeProgressive ( writer : BitWriter , scans : Scan [ ] , { coefficients, owners, ends, count } : Blocks , layout : ProgressiveComponent [ ] , mcusPerLine : number , blocksPerMcu : number ) : void {
1943+ // (the table of a component: luma 0, chroma 1)
1944+ const slot = ( comp : number ) : number => comp === 0 ? 0 : 1 ;
1945+
1946+ const run = ( coder : ScanCoder , { comps, ss, se, ah, al } : Scan ) : void => {
1947+ if ( ss === 0 ) {
1948+ if ( ah === 0 ) coder . dcFirst ( coefficients , owners , count , [ 0 , 0 , 0 ] , al ) ;
1949+ else coder . dcRefine ( coefficients , count , al ) ;
1950+ return ;
1951+ }
1952+
1953+ // (the blocks of the image only, a row after the other)
1954+ const comp = comps [ 0 ] , { h, v, blocksX, blocksY, offset } = layout [ comp ] ;
1955+ const table = slot ( comp ) ;
1956+ for ( let by = 0 ; by < blocksY ; by ++ )
1957+ for ( let bx = 0 ; bx < blocksX ; bx ++ ) {
1958+ const n = ( ( by / v | 0 ) * mcusPerLine + ( bx / h | 0 ) ) * blocksPerMcu + offset + by % v * h + bx % h ;
1959+ if ( ah === 0 ) coder . acFirst ( coefficients , n * 64 , ends [ n ] , table , ss , se , al ) ;
1960+ else coder . acRefine ( coefficients , n * 64 , ends [ n ] , table , ss , se , al ) ;
1961+ }
1962+ coder . finish ( table ) ;
1963+ } ;
1964+
1965+ for ( const scan of scans ) {
1966+ const { comps, ss, se, ah, al } = scan ;
1967+ const dcScan = ss === 0 ;
1968+
1969+ // pass 1: the symbols' frequencies
1970+ const counts = [ new Int32Array ( 257 ) , new Int32Array ( 257 ) ] ;
1971+ run ( new ScanCoder ( writer , counts , null ) , scan ) ;
1972+
1973+ // (a table once per scan, none for a DC refinement: it holds bits only)
1974+ const used : number [ ] = [ ] ;
1975+ if ( ! ( dcScan && ah !== 0 ) ) for ( const comp of comps ) if ( ! used . includes ( slot ( comp ) ) ) used . push ( slot ( comp ) ) ;
1976+ const tables : OptimalTable [ ] = [ ] ;
1977+ for ( const table of used ) tables [ table ] = buildOptimalTable ( counts [ table ] ) ;
1978+
1979+ for ( const table of used ) {
1980+ const { bits, values } = tables [ table ] ;
1981+ writer . bytes ( 0xff , 0xc4 , 19 + values . length >> 8 , 19 + values . length & 0xff , table | ( dcScan ? 0x00 : 0x10 ) ) ;
1982+ for ( let i = 1 ; i <= 16 ; i ++ ) writer . bytes ( bits [ i ] ) ;
1983+ for ( const value of values ) writer . bytes ( value ) ;
1984+ }
1985+
1986+ // SOS: the components and their tables (a DC scan names the DC one, an AC scan the AC one, a refinement of DC none)
1987+ writer . bytes ( 0xff , 0xda , 0x00 , 2 * comps . length + 6 , comps . length ) ;
1988+ for ( const comp of comps ) writer . bytes ( comp + 1 , dcScan ? ( ah === 0 ? slot ( comp ) << 4 : 0 ) : slot ( comp ) ) ;
1989+ writer . bytes ( ss , se , ah << 4 | al ) ;
1990+
1991+ // pass 2: the scan
1992+ run ( new ScanCoder ( writer , null , tables ) , scan ) ;
1993+ writer . flush ( ) ;
1994+ }
1995+ }
1996+
17331997// tables: 0 luma DC, 1 luma AC, 2 chroma DC, 3 chroma AC
17341998interface Blocks {
17351999 coefficients : Int16Array ;
0 commit comments