You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1862 lines
78KB

  1. /*
  2. * JPEG2000 image encoder
  3. * Copyright (c) 2007 Kamil Nowosad
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * **********************************************************************************************************************
  22. *
  23. *
  24. *
  25. * This source code incorporates work covered by the following copyright and
  26. * permission notice:
  27. *
  28. * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
  29. * Copyright (c) 2002-2007, Professor Benoit Macq
  30. * Copyright (c) 2001-2003, David Janssens
  31. * Copyright (c) 2002-2003, Yannick Verschueren
  32. * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
  33. * Copyright (c) 2005, Herve Drolon, FreeImage Team
  34. * Copyright (c) 2007, Callum Lerwick <seg@haxxed.com>
  35. * Copyright (c) 2020, Gautam Ramakrishnan <gautamramk@gmail.com>
  36. * All rights reserved.
  37. *
  38. * Redistribution and use in source and binary forms, with or without
  39. * modification, are permitted provided that the following conditions
  40. * are met:
  41. * 1. Redistributions of source code must retain the above copyright
  42. * notice, this list of conditions and the following disclaimer.
  43. * 2. Redistributions in binary form must reproduce the above copyright
  44. * notice, this list of conditions and the following disclaimer in the
  45. * documentation and/or other materials provided with the distribution.
  46. *
  47. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
  48. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  49. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  50. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  51. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  52. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  53. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  54. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  55. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  56. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  57. * POSSIBILITY OF SUCH DAMAGE.
  58. */
  59. /**
  60. * JPEG2000 image encoder
  61. * @file
  62. * @author Kamil Nowosad
  63. */
  64. #include <float.h>
  65. #include "avcodec.h"
  66. #include "internal.h"
  67. #include "bytestream.h"
  68. #include "jpeg2000.h"
  69. #include "libavutil/common.h"
  70. #include "libavutil/pixdesc.h"
  71. #include "libavutil/opt.h"
  72. #include "libavutil/intreadwrite.h"
  73. #include "libavutil/avstring.h"
  74. #define NMSEDEC_BITS 7
  75. #define NMSEDEC_FRACBITS (NMSEDEC_BITS-1)
  76. #define WMSEDEC_SHIFT 13 ///< must be >= 13
  77. #define LAMBDA_SCALE (100000000LL << (WMSEDEC_SHIFT - 13))
  78. #define CODEC_JP2 1
  79. #define CODEC_J2K 0
  80. static int lut_nmsedec_ref [1<<NMSEDEC_BITS],
  81. lut_nmsedec_ref0[1<<NMSEDEC_BITS],
  82. lut_nmsedec_sig [1<<NMSEDEC_BITS],
  83. lut_nmsedec_sig0[1<<NMSEDEC_BITS];
  84. static const int dwt_norms[2][4][10] = { // [dwt_type][band][rlevel] (multiplied by 10000)
  85. {{10000, 19650, 41770, 84030, 169000, 338400, 676900, 1353000, 2706000, 5409000},
  86. {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
  87. {20220, 39890, 83550, 170400, 342700, 686300, 1373000, 2746000, 5490000},
  88. {20800, 38650, 83070, 171800, 347100, 695900, 1393000, 2786000, 5572000}},
  89. {{10000, 15000, 27500, 53750, 106800, 213400, 426700, 853300, 1707000, 3413000},
  90. {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
  91. {10380, 15920, 29190, 57030, 113300, 226400, 452500, 904800, 1809000},
  92. { 7186, 9218, 15860, 30430, 60190, 120100, 240000, 479700, 959300}}
  93. };
  94. typedef struct {
  95. Jpeg2000Component *comp;
  96. double *layer_rates;
  97. } Jpeg2000Tile;
  98. typedef struct {
  99. AVClass *class;
  100. AVCodecContext *avctx;
  101. const AVFrame *picture;
  102. int width, height; ///< image width and height
  103. uint8_t cbps[4]; ///< bits per sample in particular components
  104. int chroma_shift[2];
  105. uint8_t planar;
  106. int ncomponents;
  107. int tile_width, tile_height; ///< tile size
  108. int numXtiles, numYtiles;
  109. uint8_t *buf_start;
  110. uint8_t *buf;
  111. uint8_t *buf_end;
  112. int bit_index;
  113. int64_t lambda;
  114. Jpeg2000CodingStyle codsty;
  115. Jpeg2000QuantStyle qntsty;
  116. Jpeg2000Tile *tile;
  117. int layer_rates[100];
  118. uint8_t compression_rate_enc; ///< Is compression done using compression ratio?
  119. int format;
  120. int pred;
  121. int sop;
  122. int eph;
  123. int prog;
  124. int nlayers;
  125. char *lr_str;
  126. } Jpeg2000EncoderContext;
  127. /* debug */
  128. #if 0
  129. #undef ifprintf
  130. #undef printf
  131. static void nspaces(FILE *fd, int n)
  132. {
  133. while(n--) putc(' ', fd);
  134. }
  135. static void printcomp(Jpeg2000Component *comp)
  136. {
  137. int i;
  138. for (i = 0; i < comp->y1 - comp->y0; i++)
  139. ff_jpeg2000_printv(comp->i_data + i * (comp->x1 - comp->x0), comp->x1 - comp->x0);
  140. }
  141. static void dump(Jpeg2000EncoderContext *s, FILE *fd)
  142. {
  143. int tileno, compno, reslevelno, bandno, precno;
  144. fprintf(fd, "XSiz = %d, YSiz = %d, tile_width = %d, tile_height = %d\n"
  145. "numXtiles = %d, numYtiles = %d, ncomponents = %d\n"
  146. "tiles:\n",
  147. s->width, s->height, s->tile_width, s->tile_height,
  148. s->numXtiles, s->numYtiles, s->ncomponents);
  149. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
  150. Jpeg2000Tile *tile = s->tile + tileno;
  151. nspaces(fd, 2);
  152. fprintf(fd, "tile %d:\n", tileno);
  153. for(compno = 0; compno < s->ncomponents; compno++){
  154. Jpeg2000Component *comp = tile->comp + compno;
  155. nspaces(fd, 4);
  156. fprintf(fd, "component %d:\n", compno);
  157. nspaces(fd, 4);
  158. fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d\n",
  159. comp->x0, comp->x1, comp->y0, comp->y1);
  160. for(reslevelno = 0; reslevelno < s->nreslevels; reslevelno++){
  161. Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
  162. nspaces(fd, 6);
  163. fprintf(fd, "reslevel %d:\n", reslevelno);
  164. nspaces(fd, 6);
  165. fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d, nbands = %d\n",
  166. reslevel->x0, reslevel->x1, reslevel->y0,
  167. reslevel->y1, reslevel->nbands);
  168. for(bandno = 0; bandno < reslevel->nbands; bandno++){
  169. Jpeg2000Band *band = reslevel->band + bandno;
  170. nspaces(fd, 8);
  171. fprintf(fd, "band %d:\n", bandno);
  172. nspaces(fd, 8);
  173. fprintf(fd, "x0 = %d, x1 = %d, y0 = %d, y1 = %d,"
  174. "codeblock_width = %d, codeblock_height = %d cblknx = %d cblkny = %d\n",
  175. band->x0, band->x1,
  176. band->y0, band->y1,
  177. band->codeblock_width, band->codeblock_height,
  178. band->cblknx, band->cblkny);
  179. for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
  180. Jpeg2000Prec *prec = band->prec + precno;
  181. nspaces(fd, 10);
  182. fprintf(fd, "prec %d:\n", precno);
  183. nspaces(fd, 10);
  184. fprintf(fd, "xi0 = %d, xi1 = %d, yi0 = %d, yi1 = %d\n",
  185. prec->xi0, prec->xi1, prec->yi0, prec->yi1);
  186. }
  187. }
  188. }
  189. }
  190. }
  191. }
  192. #endif
  193. /* bitstream routines */
  194. /** put n times val bit */
  195. static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: optimize
  196. {
  197. while (n-- > 0){
  198. if (s->bit_index == 8)
  199. {
  200. s->bit_index = *s->buf == 0xff;
  201. *(++s->buf) = 0;
  202. }
  203. *s->buf |= val << (7 - s->bit_index++);
  204. }
  205. }
  206. /** put n least significant bits of a number num */
  207. static void put_num(Jpeg2000EncoderContext *s, int num, int n)
  208. {
  209. while(--n >= 0)
  210. put_bits(s, (num >> n) & 1, 1);
  211. }
  212. /** flush the bitstream */
  213. static void j2k_flush(Jpeg2000EncoderContext *s)
  214. {
  215. if (s->bit_index){
  216. s->bit_index = 0;
  217. s->buf++;
  218. }
  219. }
  220. /* tag tree routines */
  221. /** code the value stored in node */
  222. static void tag_tree_code(Jpeg2000EncoderContext *s, Jpeg2000TgtNode *node, int threshold)
  223. {
  224. Jpeg2000TgtNode *stack[30];
  225. int sp = -1, curval = 0;
  226. while(node->parent){
  227. stack[++sp] = node;
  228. node = node->parent;
  229. }
  230. while (1) {
  231. if (curval > node->temp_val)
  232. node->temp_val = curval;
  233. else {
  234. curval = node->temp_val;
  235. }
  236. if (node->val >= threshold) {
  237. put_bits(s, 0, threshold - curval);
  238. curval = threshold;
  239. } else {
  240. put_bits(s, 0, node->val - curval);
  241. curval = node->val;
  242. if (!node->vis) {
  243. put_bits(s, 1, 1);
  244. node->vis = 1;
  245. }
  246. }
  247. node->temp_val = curval;
  248. if (sp < 0)
  249. break;
  250. node = stack[sp--];
  251. }
  252. }
  253. /** update the value in node */
  254. static void tag_tree_update(Jpeg2000TgtNode *node)
  255. {
  256. int lev = 0;
  257. while (node->parent){
  258. if (node->parent->val <= node->val)
  259. break;
  260. node->parent->val = node->val;
  261. node = node->parent;
  262. lev++;
  263. }
  264. }
  265. static int put_siz(Jpeg2000EncoderContext *s)
  266. {
  267. int i;
  268. if (s->buf_end - s->buf < 40 + 3 * s->ncomponents)
  269. return -1;
  270. bytestream_put_be16(&s->buf, JPEG2000_SIZ);
  271. bytestream_put_be16(&s->buf, 38 + 3 * s->ncomponents); // Lsiz
  272. bytestream_put_be16(&s->buf, 0); // Rsiz
  273. bytestream_put_be32(&s->buf, s->width); // width
  274. bytestream_put_be32(&s->buf, s->height); // height
  275. bytestream_put_be32(&s->buf, 0); // X0Siz
  276. bytestream_put_be32(&s->buf, 0); // Y0Siz
  277. bytestream_put_be32(&s->buf, s->tile_width); // XTSiz
  278. bytestream_put_be32(&s->buf, s->tile_height); // YTSiz
  279. bytestream_put_be32(&s->buf, 0); // XT0Siz
  280. bytestream_put_be32(&s->buf, 0); // YT0Siz
  281. bytestream_put_be16(&s->buf, s->ncomponents); // CSiz
  282. for (i = 0; i < s->ncomponents; i++){ // Ssiz_i XRsiz_i, YRsiz_i
  283. bytestream_put_byte(&s->buf, s->cbps[i] - 1);
  284. bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[0]:1);
  285. bytestream_put_byte(&s->buf, i?1<<s->chroma_shift[1]:1);
  286. }
  287. return 0;
  288. }
  289. static int put_cod(Jpeg2000EncoderContext *s)
  290. {
  291. Jpeg2000CodingStyle *codsty = &s->codsty;
  292. uint8_t scod = 0;
  293. if (s->buf_end - s->buf < 14)
  294. return -1;
  295. bytestream_put_be16(&s->buf, JPEG2000_COD);
  296. bytestream_put_be16(&s->buf, 12); // Lcod
  297. if (s->sop)
  298. scod |= JPEG2000_CSTY_SOP;
  299. if (s->eph)
  300. scod |= JPEG2000_CSTY_EPH;
  301. bytestream_put_byte(&s->buf, scod); // Scod
  302. // SGcod
  303. bytestream_put_byte(&s->buf, s->prog); // progression level
  304. bytestream_put_be16(&s->buf, s->nlayers); // num of layers
  305. if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){
  306. bytestream_put_byte(&s->buf, 0); // unspecified
  307. }else{
  308. bytestream_put_byte(&s->buf, 0); // unspecified
  309. }
  310. // SPcod
  311. bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels
  312. bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width
  313. bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height
  314. bytestream_put_byte(&s->buf, 0); // cblk style
  315. bytestream_put_byte(&s->buf, codsty->transform == FF_DWT53); // transformation
  316. return 0;
  317. }
  318. static int put_qcd(Jpeg2000EncoderContext *s, int compno)
  319. {
  320. int i, size;
  321. Jpeg2000CodingStyle *codsty = &s->codsty;
  322. Jpeg2000QuantStyle *qntsty = &s->qntsty;
  323. if (qntsty->quantsty == JPEG2000_QSTY_NONE)
  324. size = 4 + 3 * (codsty->nreslevels-1);
  325. else // QSTY_SE
  326. size = 5 + 6 * (codsty->nreslevels-1);
  327. if (s->buf_end - s->buf < size + 2)
  328. return -1;
  329. bytestream_put_be16(&s->buf, JPEG2000_QCD);
  330. bytestream_put_be16(&s->buf, size); // LQcd
  331. bytestream_put_byte(&s->buf, (qntsty->nguardbits << 5) | qntsty->quantsty); // Sqcd
  332. if (qntsty->quantsty == JPEG2000_QSTY_NONE)
  333. for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
  334. bytestream_put_byte(&s->buf, qntsty->expn[i] << 3);
  335. else // QSTY_SE
  336. for (i = 0; i < codsty->nreslevels * 3 - 2; i++)
  337. bytestream_put_be16(&s->buf, (qntsty->expn[i] << 11) | qntsty->mant[i]);
  338. return 0;
  339. }
  340. static int put_com(Jpeg2000EncoderContext *s, int compno)
  341. {
  342. int size = 4 + strlen(LIBAVCODEC_IDENT);
  343. if (s->avctx->flags & AV_CODEC_FLAG_BITEXACT)
  344. return 0;
  345. if (s->buf_end - s->buf < size + 2)
  346. return -1;
  347. bytestream_put_be16(&s->buf, JPEG2000_COM);
  348. bytestream_put_be16(&s->buf, size);
  349. bytestream_put_be16(&s->buf, 1); // General use (ISO/IEC 8859-15 (Latin) values)
  350. bytestream_put_buffer(&s->buf, LIBAVCODEC_IDENT, strlen(LIBAVCODEC_IDENT));
  351. return 0;
  352. }
  353. static uint8_t *put_sot(Jpeg2000EncoderContext *s, int tileno)
  354. {
  355. uint8_t *psotptr;
  356. if (s->buf_end - s->buf < 12)
  357. return NULL;
  358. bytestream_put_be16(&s->buf, JPEG2000_SOT);
  359. bytestream_put_be16(&s->buf, 10); // Lsot
  360. bytestream_put_be16(&s->buf, tileno); // Isot
  361. psotptr = s->buf;
  362. bytestream_put_be32(&s->buf, 0); // Psot (filled in later)
  363. bytestream_put_byte(&s->buf, 0); // TPsot
  364. bytestream_put_byte(&s->buf, 1); // TNsot
  365. return psotptr;
  366. }
  367. static void compute_rates(Jpeg2000EncoderContext* s)
  368. {
  369. int i, j;
  370. int layno, compno;
  371. for (i = 0; i < s->numYtiles; i++) {
  372. for (j = 0; j < s->numXtiles; j++) {
  373. Jpeg2000Tile *tile = &s->tile[s->numXtiles * i + j];
  374. for (compno = 0; compno < s->ncomponents; compno++) {
  375. int tilew = tile->comp[compno].coord[0][1] - tile->comp[compno].coord[0][0];
  376. int tileh = tile->comp[compno].coord[1][1] - tile->comp[compno].coord[1][0];
  377. int scale = (compno?1 << s->chroma_shift[0]:1) * (compno?1 << s->chroma_shift[1]:1);
  378. for (layno = 0; layno < s->nlayers; layno++) {
  379. if (s->layer_rates[layno] > 0) {
  380. tile->layer_rates[layno] += (double)(tilew * tileh) * s->ncomponents * s->cbps[compno] /
  381. (double)(s->layer_rates[layno] * 8 * scale);
  382. } else {
  383. tile->layer_rates[layno] = 0.0;
  384. }
  385. }
  386. }
  387. }
  388. }
  389. }
  390. /**
  391. * compute the sizes of tiles, resolution levels, bands, etc.
  392. * allocate memory for them
  393. * divide the input image into tile-components
  394. */
  395. static int init_tiles(Jpeg2000EncoderContext *s)
  396. {
  397. int tileno, tilex, tiley, compno;
  398. Jpeg2000CodingStyle *codsty = &s->codsty;
  399. Jpeg2000QuantStyle *qntsty = &s->qntsty;
  400. s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);
  401. s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);
  402. s->tile = av_calloc(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));
  403. if (!s->tile)
  404. return AVERROR(ENOMEM);
  405. for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)
  406. for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){
  407. Jpeg2000Tile *tile = s->tile + tileno;
  408. tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));
  409. if (!tile->comp)
  410. return AVERROR(ENOMEM);
  411. tile->layer_rates = av_mallocz_array(s->nlayers, sizeof(*tile->layer_rates));
  412. if (!tile->layer_rates)
  413. return AVERROR(ENOMEM);
  414. for (compno = 0; compno < s->ncomponents; compno++){
  415. Jpeg2000Component *comp = tile->comp + compno;
  416. int ret, i, j;
  417. comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;
  418. comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);
  419. comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;
  420. comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);
  421. if (compno > 0)
  422. for (i = 0; i < 2; i++)
  423. for (j = 0; j < 2; j++)
  424. comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);
  425. if ((ret = ff_jpeg2000_init_component(comp,
  426. codsty,
  427. qntsty,
  428. s->cbps[compno],
  429. compno?1<<s->chroma_shift[0]:1,
  430. compno?1<<s->chroma_shift[1]:1,
  431. s->avctx
  432. )) < 0)
  433. return ret;
  434. }
  435. }
  436. compute_rates(s);
  437. return 0;
  438. }
  439. #define COPY_FRAME(D, PIXEL) \
  440. static void copy_frame_ ##D(Jpeg2000EncoderContext *s) \
  441. { \
  442. int tileno, compno, i, y, x; \
  443. PIXEL *line; \
  444. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){ \
  445. Jpeg2000Tile *tile = s->tile + tileno; \
  446. if (s->planar){ \
  447. for (compno = 0; compno < s->ncomponents; compno++){ \
  448. Jpeg2000Component *comp = tile->comp + compno; \
  449. int *dst = comp->i_data; \
  450. int cbps = s->cbps[compno]; \
  451. line = (PIXEL*)s->picture->data[compno] \
  452. + comp->coord[1][0] * (s->picture->linesize[compno] / sizeof(PIXEL)) \
  453. + comp->coord[0][0]; \
  454. for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){ \
  455. PIXEL *ptr = line; \
  456. for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++) \
  457. *dst++ = *ptr++ - (1 << (cbps - 1)); \
  458. line += s->picture->linesize[compno] / sizeof(PIXEL); \
  459. } \
  460. } \
  461. } else{ \
  462. line = (PIXEL*)s->picture->data[0] + tile->comp[0].coord[1][0] * (s->picture->linesize[0] / sizeof(PIXEL)) \
  463. + tile->comp[0].coord[0][0] * s->ncomponents; \
  464. \
  465. i = 0; \
  466. for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){ \
  467. PIXEL *ptr = line; \
  468. for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){ \
  469. for (compno = 0; compno < s->ncomponents; compno++){ \
  470. int cbps = s->cbps[compno]; \
  471. tile->comp[compno].i_data[i] = *ptr++ - (1 << (cbps - 1)); \
  472. } \
  473. } \
  474. line += s->picture->linesize[0] / sizeof(PIXEL); \
  475. } \
  476. } \
  477. } \
  478. }
  479. COPY_FRAME(8, uint8_t)
  480. COPY_FRAME(16, uint16_t)
  481. static void init_quantization(Jpeg2000EncoderContext *s)
  482. {
  483. int compno, reslevelno, bandno;
  484. Jpeg2000QuantStyle *qntsty = &s->qntsty;
  485. Jpeg2000CodingStyle *codsty = &s->codsty;
  486. for (compno = 0; compno < s->ncomponents; compno++){
  487. int gbandno = 0;
  488. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
  489. int nbands, lev = codsty->nreslevels - reslevelno - 1;
  490. nbands = reslevelno ? 3 : 1;
  491. for (bandno = 0; bandno < nbands; bandno++, gbandno++){
  492. int expn, mant = 0;
  493. if (codsty->transform == FF_DWT97_INT){
  494. int bandpos = bandno + (reslevelno>0),
  495. ss = 81920000 / dwt_norms[0][bandpos][lev],
  496. log = av_log2(ss);
  497. mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;
  498. expn = s->cbps[compno] - log + 13;
  499. } else
  500. expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];
  501. qntsty->expn[gbandno] = expn;
  502. qntsty->mant[gbandno] = mant;
  503. }
  504. }
  505. }
  506. }
  507. static void init_luts(void)
  508. {
  509. int i, a,
  510. mask = ~((1<<NMSEDEC_FRACBITS)-1);
  511. for (i = 0; i < (1 << NMSEDEC_BITS); i++){
  512. lut_nmsedec_sig[i] = FFMAX((3 * i << (13 - NMSEDEC_FRACBITS)) - (9 << 11), 0);
  513. lut_nmsedec_sig0[i] = FFMAX((i*i + (1<<NMSEDEC_FRACBITS-1) & mask) << 1, 0);
  514. a = (i >> (NMSEDEC_BITS-2)&2) + 1;
  515. lut_nmsedec_ref[i] = FFMAX((a - 2) * (i << (13 - NMSEDEC_FRACBITS)) +
  516. (1 << 13) - (a * a << 11), 0);
  517. lut_nmsedec_ref0[i] = FFMAX(((i * i - (i << NMSEDEC_BITS) + (1 << 2 * NMSEDEC_FRACBITS) + (1 << (NMSEDEC_FRACBITS - 1))) & mask)
  518. << 1, 0);
  519. }
  520. }
  521. /* tier-1 routines */
  522. static int getnmsedec_sig(int x, int bpno)
  523. {
  524. if (bpno > NMSEDEC_FRACBITS)
  525. return lut_nmsedec_sig[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
  526. return lut_nmsedec_sig0[x & ((1 << NMSEDEC_BITS) - 1)];
  527. }
  528. static int getnmsedec_ref(int x, int bpno)
  529. {
  530. if (bpno > NMSEDEC_FRACBITS)
  531. return lut_nmsedec_ref[(x >> (bpno - NMSEDEC_FRACBITS)) & ((1 << NMSEDEC_BITS) - 1)];
  532. return lut_nmsedec_ref0[x & ((1 << NMSEDEC_BITS) - 1)];
  533. }
  534. static void encode_sigpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
  535. {
  536. int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
  537. for (y0 = 0; y0 < height; y0 += 4)
  538. for (x = 0; x < width; x++)
  539. for (y = y0; y < height && y < y0+4; y++){
  540. if (!(t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG) && (t1->flags[(y+1) * t1->stride + x+1] & JPEG2000_T1_SIG_NB)){
  541. int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno),
  542. bit = t1->data[(y) * t1->stride + x] & mask ? 1 : 0;
  543. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, bit);
  544. if (bit){
  545. int xorbit;
  546. int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
  547. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
  548. *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
  549. ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
  550. }
  551. t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_VIS;
  552. }
  553. }
  554. }
  555. static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)
  556. {
  557. int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
  558. for (y0 = 0; y0 < height; y0 += 4)
  559. for (x = 0; x < width; x++)
  560. for (y = y0; y < height && y < y0+4; y++)
  561. if ((t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){
  562. int ctxno = ff_jpeg2000_getrefctxno(t1->flags[(y+1) * t1->stride + x+1]);
  563. *nmsedec += getnmsedec_ref(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
  564. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
  565. t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_REF;
  566. }
  567. }
  568. static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)
  569. {
  570. int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);
  571. for (y0 = 0; y0 < height; y0 += 4)
  572. for (x = 0; x < width; x++){
  573. if (y0 + 3 < height && !(
  574. (t1->flags[(y0+1) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  575. (t1->flags[(y0+2) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  576. (t1->flags[(y0+3) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
  577. (t1->flags[(y0+4) * t1->stride + x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))
  578. {
  579. // aggregation mode
  580. int rlen;
  581. for (rlen = 0; rlen < 4; rlen++)
  582. if (t1->data[(y0+rlen) * t1->stride + x] & mask)
  583. break;
  584. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);
  585. if (rlen == 4)
  586. continue;
  587. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);
  588. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);
  589. for (y = y0 + rlen; y < y0 + 4; y++){
  590. if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
  591. int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
  592. if (y > y0 + rlen)
  593. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
  594. if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
  595. int xorbit;
  596. int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
  597. *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
  598. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
  599. ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
  600. }
  601. }
  602. t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
  603. }
  604. } else{
  605. for (y = y0; y < y0 + 4 && y < height; y++){
  606. if (!(t1->flags[(y+1) * t1->stride + x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){
  607. int ctxno = ff_jpeg2000_getsigctxno(t1->flags[(y+1) * t1->stride + x+1], bandno);
  608. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[(y) * t1->stride + x] & mask ? 1:0);
  609. if (t1->data[(y) * t1->stride + x] & mask){ // newly significant
  610. int xorbit;
  611. int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[(y+1) * t1->stride + x+1], &xorbit);
  612. *nmsedec += getnmsedec_sig(t1->data[(y) * t1->stride + x], bpno + NMSEDEC_FRACBITS);
  613. ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[(y+1) * t1->stride + x+1] >> 15) ^ xorbit);
  614. ff_jpeg2000_set_significance(t1, x, y, t1->flags[(y+1) * t1->stride + x+1] >> 15);
  615. }
  616. }
  617. t1->flags[(y+1) * t1->stride + x+1] &= ~JPEG2000_T1_VIS;
  618. }
  619. }
  620. }
  621. }
  622. static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,
  623. int width, int height, int bandpos, int lev)
  624. {
  625. int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;
  626. int64_t wmsedec = 0;
  627. memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));
  628. for (y = 0; y < height; y++){
  629. for (x = 0; x < width; x++){
  630. if (t1->data[(y) * t1->stride + x] < 0){
  631. t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;
  632. t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];
  633. }
  634. max = FFMAX(max, t1->data[(y) * t1->stride + x]);
  635. }
  636. }
  637. if (max == 0){
  638. cblk->nonzerobits = 0;
  639. bpno = 0;
  640. } else{
  641. cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;
  642. bpno = cblk->nonzerobits - 1;
  643. }
  644. cblk->data[0] = 0;
  645. ff_mqc_initenc(&t1->mqc, cblk->data + 1);
  646. for (passno = 0; bpno >= 0; passno++){
  647. nmsedec=0;
  648. switch(pass_t){
  649. case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);
  650. break;
  651. case 1: encode_refpass(t1, width, height, &nmsedec, bpno);
  652. break;
  653. case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);
  654. break;
  655. }
  656. cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);
  657. cblk->passes[passno].rate -= cblk->passes[passno].flushed_len;
  658. wmsedec += (int64_t)nmsedec << (2*bpno);
  659. cblk->passes[passno].disto = wmsedec;
  660. if (++pass_t == 3){
  661. pass_t = 0;
  662. bpno--;
  663. }
  664. }
  665. cblk->npasses = passno;
  666. cblk->ninclpasses = passno;
  667. if (passno) {
  668. cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);
  669. cblk->passes[passno-1].rate -= cblk->passes[passno-1].flushed_len;
  670. }
  671. }
  672. /* tier-2 routines: */
  673. static void putnumpasses(Jpeg2000EncoderContext *s, int n)
  674. {
  675. if (n == 1)
  676. put_num(s, 0, 1);
  677. else if (n == 2)
  678. put_num(s, 2, 2);
  679. else if (n <= 5)
  680. put_num(s, 0xc | (n-3), 4);
  681. else if (n <= 36)
  682. put_num(s, 0x1e0 | (n-6), 9);
  683. else
  684. put_num(s, 0xff80 | (n-37), 16);
  685. }
  686. static int encode_packet(Jpeg2000EncoderContext *s, Jpeg2000ResLevel *rlevel, int layno,
  687. int precno, uint8_t *expn, int numgbits, int packetno,
  688. int nlayers)
  689. {
  690. int bandno, empty = 1;
  691. int i;
  692. // init bitstream
  693. *s->buf = 0;
  694. s->bit_index = 0;
  695. if (s->sop) {
  696. bytestream_put_be16(&s->buf, JPEG2000_SOP);
  697. bytestream_put_be16(&s->buf, 4);
  698. bytestream_put_be16(&s->buf, packetno);
  699. }
  700. // header
  701. if (!layno) {
  702. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  703. Jpeg2000Band *band = rlevel->band + bandno;
  704. if (band->coord[0][0] < band->coord[0][1]
  705. && band->coord[1][0] < band->coord[1][1]) {
  706. Jpeg2000Prec *prec = band->prec + precno;
  707. int nb_cblks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
  708. int pos;
  709. ff_tag_tree_zero(prec->zerobits, prec->nb_codeblocks_width, prec->nb_codeblocks_height, 99);
  710. ff_tag_tree_zero(prec->cblkincl, prec->nb_codeblocks_width, prec->nb_codeblocks_height, 99);
  711. for (pos = 0; pos < nb_cblks; pos++) {
  712. Jpeg2000Cblk *cblk = &prec->cblk[pos];
  713. prec->zerobits[pos].val = expn[bandno] + numgbits - 1 - cblk->nonzerobits;
  714. cblk->incl = 0;
  715. cblk->lblock = 3;
  716. tag_tree_update(prec->zerobits + pos);
  717. for (i = 0; i < nlayers; i++) {
  718. if (cblk->layers[i].npasses > 0) {
  719. prec->cblkincl[pos].val = i;
  720. break;
  721. }
  722. }
  723. if (i == nlayers)
  724. prec->cblkincl[pos].val = i;
  725. tag_tree_update(prec->cblkincl + pos);
  726. }
  727. }
  728. }
  729. }
  730. // is the packet empty?
  731. for (bandno = 0; bandno < rlevel->nbands; bandno++){
  732. Jpeg2000Band *band = rlevel->band + bandno;
  733. if (band->coord[0][0] < band->coord[0][1]
  734. && band->coord[1][0] < band->coord[1][1]) {
  735. Jpeg2000Prec *prec = band->prec + precno;
  736. int nb_cblks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
  737. int pos;
  738. for (pos = 0; pos < nb_cblks; pos++) {
  739. Jpeg2000Cblk *cblk = &prec->cblk[pos];
  740. if (cblk->layers[layno].npasses) {
  741. empty = 0;
  742. break;
  743. }
  744. }
  745. if (!empty)
  746. break;
  747. }
  748. }
  749. put_bits(s, !empty, 1);
  750. if (empty){
  751. j2k_flush(s);
  752. if (s->eph)
  753. bytestream_put_be16(&s->buf, JPEG2000_EPH);
  754. return 0;
  755. }
  756. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  757. Jpeg2000Band *band = rlevel->band + bandno;
  758. Jpeg2000Prec *prec = band->prec + precno;
  759. int yi, xi, pos;
  760. int cblknw = prec->nb_codeblocks_width;
  761. if (band->coord[0][0] == band->coord[0][1]
  762. || band->coord[1][0] == band->coord[1][1])
  763. continue;
  764. for (pos=0, yi = 0; yi < prec->nb_codeblocks_height; yi++) {
  765. for (xi = 0; xi < cblknw; xi++, pos++){
  766. int llen = 0, length;
  767. Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
  768. if (s->buf_end - s->buf < 20) // approximately
  769. return -1;
  770. // inclusion information
  771. if (!cblk->incl)
  772. tag_tree_code(s, prec->cblkincl + pos, layno + 1);
  773. else {
  774. put_bits(s, cblk->layers[layno].npasses > 0, 1);
  775. }
  776. if (!cblk->layers[layno].npasses)
  777. continue;
  778. // zerobits information
  779. if (!cblk->incl) {
  780. tag_tree_code(s, prec->zerobits + pos, 100);
  781. cblk->incl = 1;
  782. }
  783. // number of passes
  784. putnumpasses(s, cblk->layers[layno].npasses);
  785. length = cblk->layers[layno].data_len;
  786. if (layno == nlayers - 1 && cblk->layers[layno].cum_passes){
  787. length += cblk->passes[cblk->layers[layno].cum_passes-1].flushed_len;
  788. }
  789. if (cblk->lblock + av_log2(cblk->layers[layno].npasses) < av_log2(length) + 1) {
  790. llen = av_log2(length) + 1 - cblk->lblock - av_log2(cblk->layers[layno].npasses);
  791. }
  792. // length of code block
  793. cblk->lblock += llen;
  794. put_bits(s, 1, llen);
  795. put_bits(s, 0, 1);
  796. put_num(s, length, cblk->lblock + av_log2(cblk->layers[layno].npasses));
  797. }
  798. }
  799. }
  800. j2k_flush(s);
  801. if (s->eph) {
  802. bytestream_put_be16(&s->buf, JPEG2000_EPH);
  803. }
  804. for (bandno = 0; bandno < rlevel->nbands; bandno++) {
  805. Jpeg2000Band *band = rlevel->band + bandno;
  806. Jpeg2000Prec *prec = band->prec + precno;
  807. int yi, cblknw = prec->nb_codeblocks_width;
  808. for (yi =0; yi < prec->nb_codeblocks_height; yi++) {
  809. int xi;
  810. for (xi = 0; xi < cblknw; xi++){
  811. Jpeg2000Cblk *cblk = prec->cblk + yi * cblknw + xi;
  812. if (cblk->layers[layno].npasses) {
  813. if (s->buf_end - s->buf < cblk->layers[layno].data_len + 2)
  814. return -1;
  815. bytestream_put_buffer(&s->buf, cblk->layers[layno].data_start + 1, cblk->layers[layno].data_len);
  816. if (layno == nlayers - 1 && cblk->layers[layno].cum_passes) {
  817. bytestream_put_buffer(&s->buf, cblk->passes[cblk->layers[layno].cum_passes-1].flushed,
  818. cblk->passes[cblk->layers[layno].cum_passes-1].flushed_len);
  819. }
  820. }
  821. }
  822. }
  823. }
  824. return 0;
  825. }
  826. static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno, int nlayers)
  827. {
  828. int compno, reslevelno, layno, ret;
  829. Jpeg2000CodingStyle *codsty = &s->codsty;
  830. Jpeg2000QuantStyle *qntsty = &s->qntsty;
  831. int packetno = 0;
  832. int step_x, step_y;
  833. int x, y;
  834. int tile_coord[2][2];
  835. int col = tileno % s->numXtiles;
  836. int row = tileno / s->numXtiles;
  837. tile_coord[0][0] = col * s->tile_width;
  838. tile_coord[0][1] = FFMIN(tile_coord[0][0] + s->tile_width, s->width);
  839. tile_coord[1][0] = row * s->tile_height;
  840. tile_coord[1][1] = FFMIN(tile_coord[1][0] + s->tile_height, s->height);
  841. av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");
  842. // lay-rlevel-comp-pos progression
  843. switch (s->prog) {
  844. case JPEG2000_PGOD_LRCP:
  845. for (layno = 0; layno < nlayers; layno++) {
  846. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
  847. for (compno = 0; compno < s->ncomponents; compno++){
  848. int precno;
  849. Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
  850. for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
  851. if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
  852. qntsty->nguardbits, packetno++, nlayers)) < 0)
  853. return ret;
  854. }
  855. }
  856. }
  857. }
  858. break;
  859. case JPEG2000_PGOD_RLCP:
  860. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
  861. for (layno = 0; layno < nlayers; layno++) {
  862. for (compno = 0; compno < s->ncomponents; compno++){
  863. int precno;
  864. Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;
  865. for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
  866. if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
  867. qntsty->nguardbits, packetno++, nlayers)) < 0)
  868. return ret;
  869. }
  870. }
  871. }
  872. }
  873. break;
  874. case JPEG2000_PGOD_RPCL:
  875. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  876. int precno;
  877. step_x = 30;
  878. step_y = 30;
  879. for (compno = 0; compno < s->ncomponents; compno++) {
  880. Jpeg2000Component *comp = tile->comp + compno;
  881. if (reslevelno < codsty->nreslevels) {
  882. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  883. Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  884. step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
  885. step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
  886. }
  887. }
  888. step_x = 1<<step_x;
  889. step_y = 1<<step_y;
  890. for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
  891. for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
  892. for (compno = 0; compno < s->ncomponents; compno++) {
  893. Jpeg2000Component *comp = tile->comp + compno;
  894. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  895. Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
  896. int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
  897. unsigned prcx, prcy;
  898. int trx0, try0;
  899. trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
  900. try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
  901. if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
  902. (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
  903. continue;
  904. if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
  905. (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
  906. continue;
  907. // check if a precinct exists
  908. prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
  909. prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
  910. prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
  911. prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
  912. precno = prcx + reslevel->num_precincts_x * prcy;
  913. if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
  914. av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
  915. prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
  916. continue;
  917. }
  918. for (layno = 0; layno < nlayers; layno++) {
  919. if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
  920. qntsty->nguardbits, packetno++, nlayers)) < 0)
  921. return ret;
  922. }
  923. }
  924. }
  925. }
  926. }
  927. break;
  928. case JPEG2000_PGOD_PCRL:
  929. step_x = 32;
  930. step_y = 32;
  931. for (compno = 0; compno < s->ncomponents; compno++) {
  932. Jpeg2000Component *comp = tile->comp + compno;
  933. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  934. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  935. Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  936. step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
  937. step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
  938. }
  939. }
  940. if (step_x >= 31 || step_y >= 31){
  941. avpriv_request_sample(s->avctx, "PCRL with large step");
  942. return AVERROR_PATCHWELCOME;
  943. }
  944. step_x = 1<<step_x;
  945. step_y = 1<<step_y;
  946. for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
  947. for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
  948. for (compno = 0; compno < s->ncomponents; compno++) {
  949. Jpeg2000Component *comp = tile->comp + compno;
  950. int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
  951. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  952. unsigned prcx, prcy;
  953. int precno;
  954. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  955. Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
  956. int trx0, try0;
  957. trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
  958. try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
  959. if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
  960. (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
  961. continue;
  962. if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
  963. (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
  964. continue;
  965. // check if a precinct exists
  966. prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
  967. prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
  968. prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
  969. prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
  970. precno = prcx + reslevel->num_precincts_x * prcy;
  971. if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
  972. av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
  973. prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
  974. continue;
  975. }
  976. for (layno = 0; layno < nlayers; layno++) {
  977. if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
  978. qntsty->nguardbits, packetno++, nlayers)) < 0)
  979. return ret;
  980. }
  981. }
  982. }
  983. }
  984. }
  985. break;
  986. case JPEG2000_PGOD_CPRL:
  987. for (compno = 0; compno < s->ncomponents; compno++) {
  988. Jpeg2000Component *comp = tile->comp + compno;
  989. int log_subsampling[2] = { compno?s->chroma_shift[0]:0, compno?s->chroma_shift[1]:0};
  990. step_x = 32;
  991. step_y = 32;
  992. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  993. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  994. Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
  995. step_x = FFMIN(step_x, rlevel->log2_prec_width + reducedresno);
  996. step_y = FFMIN(step_y, rlevel->log2_prec_height + reducedresno);
  997. }
  998. if (step_x >= 31 || step_y >= 31){
  999. avpriv_request_sample(s->avctx, "CPRL with large step");
  1000. return AVERROR_PATCHWELCOME;
  1001. }
  1002. step_x = 1<<step_x;
  1003. step_y = 1<<step_y;
  1004. for (y = tile_coord[1][0]; y < tile_coord[1][1]; y = (y/step_y + 1)*step_y) {
  1005. for (x = tile_coord[0][0]; x < tile_coord[0][1]; x = (x/step_x + 1)*step_x) {
  1006. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
  1007. unsigned prcx, prcy;
  1008. int precno;
  1009. int trx0, try0;
  1010. uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
  1011. Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
  1012. trx0 = ff_jpeg2000_ceildivpow2(tile_coord[0][0], log_subsampling[0] + reducedresno);
  1013. try0 = ff_jpeg2000_ceildivpow2(tile_coord[1][0], log_subsampling[1] + reducedresno);
  1014. if (!(y % ((uint64_t)1 << (reslevel->log2_prec_height + reducedresno + log_subsampling[1])) == 0 ||
  1015. (y == tile_coord[1][0] && (try0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_height)))))
  1016. continue;
  1017. if (!(x % ((uint64_t)1 << (reslevel->log2_prec_width + reducedresno + log_subsampling[0])) == 0 ||
  1018. (x == tile_coord[0][0] && (trx0 << reducedresno) % (1U << (reducedresno + reslevel->log2_prec_width)))))
  1019. continue;
  1020. // check if a precinct exists
  1021. prcx = ff_jpeg2000_ceildivpow2(x, log_subsampling[0] + reducedresno) >> reslevel->log2_prec_width;
  1022. prcy = ff_jpeg2000_ceildivpow2(y, log_subsampling[1] + reducedresno) >> reslevel->log2_prec_height;
  1023. prcx -= ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], reducedresno) >> reslevel->log2_prec_width;
  1024. prcy -= ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], reducedresno) >> reslevel->log2_prec_height;
  1025. precno = prcx + reslevel->num_precincts_x * prcy;
  1026. if (prcx >= reslevel->num_precincts_x || prcy >= reslevel->num_precincts_y) {
  1027. av_log(s->avctx, AV_LOG_WARNING, "prc %d %d outside limits %d %d\n",
  1028. prcx, prcy, reslevel->num_precincts_x, reslevel->num_precincts_y);
  1029. continue;
  1030. }
  1031. for (layno = 0; layno < nlayers; layno++) {
  1032. if ((ret = encode_packet(s, reslevel, layno, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),
  1033. qntsty->nguardbits, packetno++, nlayers)) < 0)
  1034. return ret;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. }
  1040. }
  1041. av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");
  1042. return 0;
  1043. }
  1044. static void makelayer(Jpeg2000EncoderContext *s, int layno, double thresh, Jpeg2000Tile* tile, int final)
  1045. {
  1046. int compno, resno, bandno, precno, cblkno;
  1047. int passno;
  1048. for (compno = 0; compno < s->ncomponents; compno++) {
  1049. Jpeg2000Component *comp = &tile->comp[compno];
  1050. for (resno = 0; resno < s->codsty.nreslevels; resno++) {
  1051. Jpeg2000ResLevel *reslevel = comp->reslevel + resno;
  1052. for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
  1053. for (bandno = 0; bandno < reslevel->nbands ; bandno++){
  1054. Jpeg2000Band *band = reslevel->band + bandno;
  1055. Jpeg2000Prec *prec = band->prec + precno;
  1056. for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
  1057. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  1058. Jpeg2000Layer *layer = &cblk->layers[layno];
  1059. int n;
  1060. if (layno == 0) {
  1061. cblk->ninclpasses = 0;
  1062. }
  1063. n = cblk->ninclpasses;
  1064. if (thresh < 0) {
  1065. n = cblk->npasses;
  1066. } else {
  1067. for (passno = cblk->ninclpasses; passno < cblk->npasses; passno++) {
  1068. int32_t dr;
  1069. double dd;
  1070. Jpeg2000Pass *pass = &cblk->passes[passno];
  1071. if (n == 0) {
  1072. dr = pass->rate;
  1073. dd = pass->disto;
  1074. } else {
  1075. dr = pass->rate - cblk->passes[n - 1].rate;
  1076. dd = pass->disto - cblk->passes[n-1].disto;
  1077. }
  1078. if (!dr) {
  1079. if (dd != 0.0) {
  1080. n = passno + 1;
  1081. }
  1082. continue;
  1083. }
  1084. if (thresh - (dd / dr) < DBL_EPSILON)
  1085. n = passno + 1;
  1086. }
  1087. }
  1088. layer->npasses = n - cblk->ninclpasses;
  1089. layer->cum_passes = n;
  1090. if (layer->npasses == 0) {
  1091. layer->disto = 0;
  1092. layer->data_len = 0;
  1093. continue;
  1094. }
  1095. if (cblk->ninclpasses == 0) {
  1096. layer->data_len = cblk->passes[n - 1].rate;
  1097. layer->data_start = cblk->data;
  1098. layer->disto = cblk->passes[n - 1].disto;
  1099. } else {
  1100. layer->data_len = cblk->passes[n - 1].rate - cblk->passes[cblk->ninclpasses - 1].rate;
  1101. layer->data_start = cblk->data + cblk->passes[cblk->ninclpasses - 1].rate;
  1102. layer->disto = cblk->passes[n - 1].disto -
  1103. cblk->passes[cblk->ninclpasses - 1].disto;
  1104. }
  1105. if (final) {
  1106. cblk->ninclpasses = n;
  1107. }
  1108. }
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. static void makelayers(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
  1115. {
  1116. int precno, compno, reslevelno, bandno, cblkno, lev, passno, layno;
  1117. int i;
  1118. double min = DBL_MAX;
  1119. double max = 0;
  1120. double thresh;
  1121. int tile_disto = 0;
  1122. Jpeg2000CodingStyle *codsty = &s->codsty;
  1123. for (compno = 0; compno < s->ncomponents; compno++){
  1124. Jpeg2000Component *comp = tile->comp + compno;
  1125. for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
  1126. Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
  1127. for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
  1128. for (bandno = 0; bandno < reslevel->nbands ; bandno++){
  1129. Jpeg2000Band *band = reslevel->band + bandno;
  1130. Jpeg2000Prec *prec = band->prec + precno;
  1131. for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
  1132. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  1133. for (passno = 0; passno < cblk->npasses; passno++) {
  1134. Jpeg2000Pass *pass = &cblk->passes[passno];
  1135. int dr;
  1136. double dd, drslope;
  1137. tile_disto += pass->disto;
  1138. if (passno == 0) {
  1139. dr = (int32_t)pass->rate;
  1140. dd = pass->disto;
  1141. } else {
  1142. dr = (int32_t)(pass->rate - cblk->passes[passno - 1].rate);
  1143. dd = pass->disto - cblk->passes[passno - 1].disto;
  1144. }
  1145. if (dr <= 0)
  1146. continue;
  1147. drslope = dd / dr;
  1148. if (drslope < min)
  1149. min = drslope;
  1150. if (drslope > max)
  1151. max = drslope;
  1152. }
  1153. }
  1154. }
  1155. }
  1156. }
  1157. }
  1158. for (layno = 0; layno < s->nlayers; layno++) {
  1159. double lo = min;
  1160. double hi = max;
  1161. double stable_thresh = 0.0;
  1162. double good_thresh = 0.0;
  1163. if (!s->layer_rates[layno]) {
  1164. good_thresh = -1.0;
  1165. } else {
  1166. for (i = 0; i < 128; i++) {
  1167. uint8_t *stream_pos = s->buf;
  1168. int ret;
  1169. thresh = (lo + hi) / 2;
  1170. makelayer(s, layno, thresh, tile, 0);
  1171. ret = encode_packets(s, tile, (int)(tile - s->tile), layno + 1);
  1172. memset(stream_pos, 0, s->buf - stream_pos);
  1173. if ((s->buf - stream_pos > ceil(tile->layer_rates[layno])) || ret < 0) {
  1174. lo = thresh;
  1175. s->buf = stream_pos;
  1176. continue;
  1177. }
  1178. hi = thresh;
  1179. stable_thresh = thresh;
  1180. s->buf = stream_pos;
  1181. }
  1182. }
  1183. if (good_thresh >= 0.0)
  1184. good_thresh = stable_thresh == 0.0 ? thresh : stable_thresh;
  1185. makelayer(s, layno, good_thresh, tile, 1);
  1186. }
  1187. }
  1188. static int getcut(Jpeg2000Cblk *cblk, int64_t lambda, int dwt_norm)
  1189. {
  1190. int passno, res = 0;
  1191. for (passno = 0; passno < cblk->npasses; passno++){
  1192. int dr;
  1193. int64_t dd;
  1194. dr = cblk->passes[passno].rate
  1195. - (res ? cblk->passes[res-1].rate : 0);
  1196. dd = cblk->passes[passno].disto
  1197. - (res ? cblk->passes[res-1].disto : 0);
  1198. if (((dd * dwt_norm) >> WMSEDEC_SHIFT) * dwt_norm >= dr * lambda)
  1199. res = passno+1;
  1200. }
  1201. return res;
  1202. }
  1203. static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)
  1204. {
  1205. int precno, compno, reslevelno, bandno, cblkno, lev;
  1206. Jpeg2000CodingStyle *codsty = &s->codsty;
  1207. for (compno = 0; compno < s->ncomponents; compno++){
  1208. Jpeg2000Component *comp = tile->comp + compno;
  1209. for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){
  1210. Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
  1211. for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){
  1212. for (bandno = 0; bandno < reslevel->nbands ; bandno++){
  1213. int bandpos = bandno + (reslevelno > 0);
  1214. Jpeg2000Band *band = reslevel->band + bandno;
  1215. Jpeg2000Prec *prec = band->prec + precno;
  1216. for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){
  1217. Jpeg2000Cblk *cblk = prec->cblk + cblkno;
  1218. cblk->ninclpasses = getcut(cblk, s->lambda,
  1219. (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 15);
  1220. cblk->layers[0].data_start = cblk->data;
  1221. cblk->layers[0].cum_passes = cblk->ninclpasses;
  1222. cblk->layers[0].npasses = cblk->ninclpasses;
  1223. if (cblk->ninclpasses)
  1224. cblk->layers[0].data_len = cblk->passes[cblk->ninclpasses - 1].rate;
  1225. }
  1226. }
  1227. }
  1228. }
  1229. }
  1230. }
  1231. static int encode_tile(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)
  1232. {
  1233. int compno, reslevelno, bandno, ret;
  1234. Jpeg2000T1Context t1;
  1235. Jpeg2000CodingStyle *codsty = &s->codsty;
  1236. for (compno = 0; compno < s->ncomponents; compno++){
  1237. Jpeg2000Component *comp = s->tile[tileno].comp + compno;
  1238. t1.stride = (1<<codsty->log2_cblk_width) + 2;
  1239. av_log(s->avctx, AV_LOG_DEBUG,"dwt\n");
  1240. if ((ret = ff_dwt_encode(&comp->dwt, comp->i_data)) < 0)
  1241. return ret;
  1242. av_log(s->avctx, AV_LOG_DEBUG,"after dwt -> tier1\n");
  1243. for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){
  1244. Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
  1245. for (bandno = 0; bandno < reslevel->nbands ; bandno++){
  1246. Jpeg2000Band *band = reslevel->band + bandno;
  1247. Jpeg2000Prec *prec = band->prec; // we support only 1 precinct per band ATM in the encoder
  1248. int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;
  1249. yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];
  1250. y0 = yy0;
  1251. yy1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[1][0] + 1, band->log2_cblk_height) << band->log2_cblk_height,
  1252. band->coord[1][1]) - band->coord[1][0] + yy0;
  1253. if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])
  1254. continue;
  1255. bandpos = bandno + (reslevelno > 0);
  1256. for (cblky = 0; cblky < prec->nb_codeblocks_height; cblky++){
  1257. if (reslevelno == 0 || bandno == 1)
  1258. xx0 = 0;
  1259. else
  1260. xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];
  1261. x0 = xx0;
  1262. xx1 = FFMIN(ff_jpeg2000_ceildivpow2(band->coord[0][0] + 1, band->log2_cblk_width) << band->log2_cblk_width,
  1263. band->coord[0][1]) - band->coord[0][0] + xx0;
  1264. for (cblkx = 0; cblkx < prec->nb_codeblocks_width; cblkx++, cblkno++){
  1265. int y, x;
  1266. if (codsty->transform == FF_DWT53){
  1267. for (y = yy0; y < yy1; y++){
  1268. int *ptr = t1.data + (y-yy0)*t1.stride;
  1269. for (x = xx0; x < xx1; x++){
  1270. *ptr++ = comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] * (1 << NMSEDEC_FRACBITS);
  1271. }
  1272. }
  1273. } else{
  1274. for (y = yy0; y < yy1; y++){
  1275. int *ptr = t1.data + (y-yy0)*t1.stride;
  1276. for (x = xx0; x < xx1; x++){
  1277. *ptr = (comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * y + x]);
  1278. *ptr = (int64_t)*ptr * (int64_t)(16384 * 65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
  1279. ptr++;
  1280. }
  1281. }
  1282. }
  1283. if (!prec->cblk[cblkno].data)
  1284. prec->cblk[cblkno].data = av_malloc(1 + 8192);
  1285. if (!prec->cblk[cblkno].passes)
  1286. prec->cblk[cblkno].passes = av_malloc_array(JPEG2000_MAX_PASSES, sizeof (*prec->cblk[cblkno].passes));
  1287. if (!prec->cblk[cblkno].data || !prec->cblk[cblkno].passes)
  1288. return AVERROR(ENOMEM);
  1289. encode_cblk(s, &t1, prec->cblk + cblkno, tile, xx1 - xx0, yy1 - yy0,
  1290. bandpos, codsty->nreslevels - reslevelno - 1);
  1291. xx0 = xx1;
  1292. xx1 = FFMIN(xx1 + (1 << band->log2_cblk_width), band->coord[0][1] - band->coord[0][0] + x0);
  1293. }
  1294. yy0 = yy1;
  1295. yy1 = FFMIN(yy1 + (1 << band->log2_cblk_height), band->coord[1][1] - band->coord[1][0] + y0);
  1296. }
  1297. }
  1298. }
  1299. av_log(s->avctx, AV_LOG_DEBUG, "after tier1\n");
  1300. }
  1301. av_log(s->avctx, AV_LOG_DEBUG, "rate control\n");
  1302. if (s->compression_rate_enc)
  1303. makelayers(s, tile);
  1304. else
  1305. truncpasses(s, tile);
  1306. if ((ret = encode_packets(s, tile, tileno, s->nlayers)) < 0)
  1307. return ret;
  1308. av_log(s->avctx, AV_LOG_DEBUG, "after rate control\n");
  1309. return 0;
  1310. }
  1311. static void cleanup(Jpeg2000EncoderContext *s)
  1312. {
  1313. int tileno, compno;
  1314. Jpeg2000CodingStyle *codsty = &s->codsty;
  1315. if (!s->tile)
  1316. return;
  1317. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
  1318. if (s->tile[tileno].comp) {
  1319. for (compno = 0; compno < s->ncomponents; compno++){
  1320. Jpeg2000Component *comp = s->tile[tileno].comp + compno;
  1321. ff_jpeg2000_cleanup(comp, codsty);
  1322. }
  1323. av_freep(&s->tile[tileno].comp);
  1324. }
  1325. av_freep(&s->tile[tileno].layer_rates);
  1326. }
  1327. av_freep(&s->tile);
  1328. }
  1329. static void reinit(Jpeg2000EncoderContext *s)
  1330. {
  1331. int tileno, compno;
  1332. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
  1333. Jpeg2000Tile *tile = s->tile + tileno;
  1334. for (compno = 0; compno < s->ncomponents; compno++)
  1335. ff_jpeg2000_reinit(tile->comp + compno, &s->codsty);
  1336. }
  1337. }
  1338. static void update_size(uint8_t *size, const uint8_t *end)
  1339. {
  1340. AV_WB32(size, end-size);
  1341. }
  1342. static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1343. const AVFrame *pict, int *got_packet)
  1344. {
  1345. int tileno, ret;
  1346. Jpeg2000EncoderContext *s = avctx->priv_data;
  1347. uint8_t *chunkstart, *jp2cstart, *jp2hstart;
  1348. if ((ret = ff_alloc_packet2(avctx, pkt, avctx->width*avctx->height*9 + AV_INPUT_BUFFER_MIN_SIZE, 0)) < 0)
  1349. return ret;
  1350. // init:
  1351. s->buf = s->buf_start = pkt->data;
  1352. s->buf_end = pkt->data + pkt->size;
  1353. s->picture = pict;
  1354. s->lambda = s->picture->quality * LAMBDA_SCALE;
  1355. if (avctx->pix_fmt == AV_PIX_FMT_BGR48 || avctx->pix_fmt == AV_PIX_FMT_GRAY16)
  1356. copy_frame_16(s);
  1357. else
  1358. copy_frame_8(s);
  1359. reinit(s);
  1360. if (s->format == CODEC_JP2) {
  1361. av_assert0(s->buf == pkt->data);
  1362. bytestream_put_be32(&s->buf, 0x0000000C);
  1363. bytestream_put_be32(&s->buf, 0x6A502020);
  1364. bytestream_put_be32(&s->buf, 0x0D0A870A);
  1365. chunkstart = s->buf;
  1366. bytestream_put_be32(&s->buf, 0);
  1367. bytestream_put_buffer(&s->buf, "ftyp", 4);
  1368. bytestream_put_buffer(&s->buf, "jp2\040\040", 4);
  1369. bytestream_put_be32(&s->buf, 0);
  1370. bytestream_put_buffer(&s->buf, "jp2\040", 4);
  1371. update_size(chunkstart, s->buf);
  1372. jp2hstart = s->buf;
  1373. bytestream_put_be32(&s->buf, 0);
  1374. bytestream_put_buffer(&s->buf, "jp2h", 4);
  1375. chunkstart = s->buf;
  1376. bytestream_put_be32(&s->buf, 0);
  1377. bytestream_put_buffer(&s->buf, "ihdr", 4);
  1378. bytestream_put_be32(&s->buf, avctx->height);
  1379. bytestream_put_be32(&s->buf, avctx->width);
  1380. bytestream_put_be16(&s->buf, s->ncomponents);
  1381. bytestream_put_byte(&s->buf, s->cbps[0]);
  1382. bytestream_put_byte(&s->buf, 7);
  1383. bytestream_put_byte(&s->buf, 0);
  1384. bytestream_put_byte(&s->buf, 0);
  1385. update_size(chunkstart, s->buf);
  1386. chunkstart = s->buf;
  1387. bytestream_put_be32(&s->buf, 0);
  1388. bytestream_put_buffer(&s->buf, "colr", 4);
  1389. bytestream_put_byte(&s->buf, 1);
  1390. bytestream_put_byte(&s->buf, 0);
  1391. bytestream_put_byte(&s->buf, 0);
  1392. if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  1393. bytestream_put_be32(&s->buf, 16);
  1394. } else if (s->ncomponents == 1) {
  1395. bytestream_put_be32(&s->buf, 17);
  1396. } else {
  1397. bytestream_put_be32(&s->buf, 18);
  1398. }
  1399. update_size(chunkstart, s->buf);
  1400. if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {
  1401. int i;
  1402. uint8_t *palette = pict->data[1];
  1403. chunkstart = s->buf;
  1404. bytestream_put_be32(&s->buf, 0);
  1405. bytestream_put_buffer(&s->buf, "pclr", 4);
  1406. bytestream_put_be16(&s->buf, AVPALETTE_COUNT);
  1407. bytestream_put_byte(&s->buf, 3); // colour channels
  1408. bytestream_put_be24(&s->buf, 0x070707); //colour depths
  1409. for (i = 0; i < AVPALETTE_COUNT; i++) {
  1410. bytestream_put_be24(&s->buf, HAVE_BIGENDIAN ? AV_RB24(palette + 1) : AV_RL24(palette));
  1411. palette += 4;
  1412. }
  1413. update_size(chunkstart, s->buf);
  1414. chunkstart = s->buf;
  1415. bytestream_put_be32(&s->buf, 0);
  1416. bytestream_put_buffer(&s->buf, "cmap", 4);
  1417. for (i = 0; i < 3; i++) {
  1418. bytestream_put_be16(&s->buf, 0); // component
  1419. bytestream_put_byte(&s->buf, 1); // palette mapping
  1420. bytestream_put_byte(&s->buf, i); // index
  1421. }
  1422. update_size(chunkstart, s->buf);
  1423. }
  1424. update_size(jp2hstart, s->buf);
  1425. jp2cstart = s->buf;
  1426. bytestream_put_be32(&s->buf, 0);
  1427. bytestream_put_buffer(&s->buf, "jp2c", 4);
  1428. }
  1429. if (s->buf_end - s->buf < 2)
  1430. return -1;
  1431. bytestream_put_be16(&s->buf, JPEG2000_SOC);
  1432. if ((ret = put_siz(s)) < 0)
  1433. return ret;
  1434. if ((ret = put_cod(s)) < 0)
  1435. return ret;
  1436. if ((ret = put_qcd(s, 0)) < 0)
  1437. return ret;
  1438. if ((ret = put_com(s, 0)) < 0)
  1439. return ret;
  1440. for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){
  1441. uint8_t *psotptr;
  1442. if (!(psotptr = put_sot(s, tileno)))
  1443. return -1;
  1444. if (s->buf_end - s->buf < 2)
  1445. return -1;
  1446. bytestream_put_be16(&s->buf, JPEG2000_SOD);
  1447. if ((ret = encode_tile(s, s->tile + tileno, tileno)) < 0)
  1448. return ret;
  1449. bytestream_put_be32(&psotptr, s->buf - psotptr + 6);
  1450. }
  1451. if (s->buf_end - s->buf < 2)
  1452. return -1;
  1453. bytestream_put_be16(&s->buf, JPEG2000_EOC);
  1454. if (s->format == CODEC_JP2)
  1455. update_size(jp2cstart, s->buf);
  1456. av_log(s->avctx, AV_LOG_DEBUG, "end\n");
  1457. pkt->size = s->buf - s->buf_start;
  1458. pkt->flags |= AV_PKT_FLAG_KEY;
  1459. *got_packet = 1;
  1460. return 0;
  1461. }
  1462. static int parse_layer_rates(Jpeg2000EncoderContext *s)
  1463. {
  1464. int i;
  1465. char *token;
  1466. char *saveptr = NULL;
  1467. int rate;
  1468. int nlayers = 0;
  1469. if (!s->lr_str) {
  1470. s->nlayers = 1;
  1471. s->layer_rates[0] = 0;
  1472. s->compression_rate_enc = 0;
  1473. return 0;
  1474. }
  1475. token = av_strtok(s->lr_str, ",", &saveptr);
  1476. if (rate = strtol(token, NULL, 10)) {
  1477. s->layer_rates[0] = rate <= 1 ? 0:rate;
  1478. nlayers++;
  1479. } else {
  1480. return AVERROR_INVALIDDATA;
  1481. }
  1482. while (1) {
  1483. token = av_strtok(NULL, ",", &saveptr);
  1484. if (!token)
  1485. break;
  1486. if (rate = strtol(token, NULL, 10)) {
  1487. if (nlayers >= 100) {
  1488. return AVERROR_INVALIDDATA;
  1489. }
  1490. s->layer_rates[nlayers] = rate <= 1 ? 0:rate;
  1491. nlayers++;
  1492. } else {
  1493. return AVERROR_INVALIDDATA;
  1494. }
  1495. }
  1496. for (i = 1; i < nlayers; i++) {
  1497. if (s->layer_rates[i] >= s->layer_rates[i-1]) {
  1498. return AVERROR_INVALIDDATA;
  1499. }
  1500. }
  1501. s->nlayers = nlayers;
  1502. s->compression_rate_enc = 1;
  1503. return 0;
  1504. }
  1505. static av_cold int j2kenc_init(AVCodecContext *avctx)
  1506. {
  1507. int i, ret;
  1508. Jpeg2000EncoderContext *s = avctx->priv_data;
  1509. Jpeg2000CodingStyle *codsty = &s->codsty;
  1510. Jpeg2000QuantStyle *qntsty = &s->qntsty;
  1511. s->avctx = avctx;
  1512. av_log(s->avctx, AV_LOG_DEBUG, "init\n");
  1513. if (parse_layer_rates(s)) {
  1514. av_log(s, AV_LOG_WARNING, "Layer rates invalid. Encoding with 1 layer based on quality metric.\n");
  1515. s->nlayers = 1;
  1516. s->layer_rates[0] = 0;
  1517. s->compression_rate_enc = 0;
  1518. }
  1519. #if FF_API_PRIVATE_OPT
  1520. FF_DISABLE_DEPRECATION_WARNINGS
  1521. if (avctx->prediction_method)
  1522. s->pred = avctx->prediction_method;
  1523. FF_ENABLE_DEPRECATION_WARNINGS
  1524. #endif
  1525. if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && (s->pred != FF_DWT97_INT || s->format != CODEC_JP2)) {
  1526. av_log(s->avctx, AV_LOG_WARNING, "Forcing lossless jp2 for pal8\n");
  1527. s->pred = FF_DWT97_INT;
  1528. s->format = CODEC_JP2;
  1529. }
  1530. // defaults:
  1531. // TODO: implement setting non-standard precinct size
  1532. memset(codsty->log2_prec_widths , 15, sizeof(codsty->log2_prec_widths ));
  1533. memset(codsty->log2_prec_heights, 15, sizeof(codsty->log2_prec_heights));
  1534. codsty->nreslevels2decode=
  1535. codsty->nreslevels = 7;
  1536. codsty->nlayers = s->nlayers;
  1537. codsty->log2_cblk_width = 4;
  1538. codsty->log2_cblk_height = 4;
  1539. codsty->transform = s->pred ? FF_DWT53 : FF_DWT97_INT;
  1540. qntsty->nguardbits = 1;
  1541. if ((s->tile_width & (s->tile_width -1)) ||
  1542. (s->tile_height & (s->tile_height-1))) {
  1543. av_log(avctx, AV_LOG_WARNING, "Tile dimension not a power of 2\n");
  1544. }
  1545. if (codsty->transform == FF_DWT53)
  1546. qntsty->quantsty = JPEG2000_QSTY_NONE;
  1547. else
  1548. qntsty->quantsty = JPEG2000_QSTY_SE;
  1549. s->width = avctx->width;
  1550. s->height = avctx->height;
  1551. for (i = 0; i < 3; i++) {
  1552. if (avctx->pix_fmt == AV_PIX_FMT_GRAY16 || avctx->pix_fmt == AV_PIX_FMT_RGB48)
  1553. s->cbps[i] = 16;
  1554. else
  1555. s->cbps[i] = 8;
  1556. }
  1557. if (avctx->pix_fmt == AV_PIX_FMT_RGB24 || avctx->pix_fmt == AV_PIX_FMT_RGB48){
  1558. s->ncomponents = 3;
  1559. } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 || avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY16){
  1560. s->ncomponents = 1;
  1561. } else{ // planar YUV
  1562. s->planar = 1;
  1563. s->ncomponents = 3;
  1564. ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt,
  1565. s->chroma_shift, s->chroma_shift + 1);
  1566. if (ret)
  1567. return ret;
  1568. }
  1569. ff_jpeg2000_init_tier1_luts();
  1570. ff_mqc_init_context_tables();
  1571. init_luts();
  1572. init_quantization(s);
  1573. if ((ret=init_tiles(s)) < 0)
  1574. return ret;
  1575. av_log(s->avctx, AV_LOG_DEBUG, "after init\n");
  1576. return 0;
  1577. }
  1578. static int j2kenc_destroy(AVCodecContext *avctx)
  1579. {
  1580. Jpeg2000EncoderContext *s = avctx->priv_data;
  1581. cleanup(s);
  1582. return 0;
  1583. }
  1584. // taken from the libopenjpeg wraper so it matches
  1585. #define OFFSET(x) offsetof(Jpeg2000EncoderContext, x)
  1586. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  1587. static const AVOption options[] = {
  1588. { "format", "Codec Format", OFFSET(format), AV_OPT_TYPE_INT, { .i64 = CODEC_JP2 }, CODEC_J2K, CODEC_JP2, VE, "format" },
  1589. { "j2k", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CODEC_J2K }, 0, 0, VE, "format" },
  1590. { "jp2", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CODEC_JP2 }, 0, 0, VE, "format" },
  1591. { "tile_width", "Tile Width", OFFSET(tile_width), AV_OPT_TYPE_INT, { .i64 = 256 }, 1, 1<<30, VE, },
  1592. { "tile_height", "Tile Height", OFFSET(tile_height), AV_OPT_TYPE_INT, { .i64 = 256 }, 1, 1<<30, VE, },
  1593. { "pred", "DWT Type", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, "pred" },
  1594. { "dwt97int", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
  1595. { "dwt53", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "pred" },
  1596. { "sop", "SOP marker", OFFSET(sop), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, },
  1597. { "eph", "EPH marker", OFFSET(eph), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE, },
  1598. { "prog", "Progression Order", OFFSET(prog), AV_OPT_TYPE_INT, { .i64 = 0 }, JPEG2000_PGOD_LRCP, JPEG2000_PGOD_CPRL, VE, "prog" },
  1599. { "lrcp", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_LRCP }, 0, 0, VE, "prog" },
  1600. { "rlcp", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_RLCP }, 0, 0, VE, "prog" },
  1601. { "rpcl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_RPCL }, 0, 0, VE, "prog" },
  1602. { "pcrl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_PCRL }, 0, 0, VE, "prog" },
  1603. { "cprl", NULL, OFFSET(prog), AV_OPT_TYPE_CONST, { .i64 = JPEG2000_PGOD_CPRL }, 0, 0, VE, "prog" },
  1604. { "layer_rates", "Layer Rates", OFFSET(lr_str), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
  1605. { NULL }
  1606. };
  1607. static const AVClass j2k_class = {
  1608. .class_name = "jpeg 2000 encoder",
  1609. .item_name = av_default_item_name,
  1610. .option = options,
  1611. .version = LIBAVUTIL_VERSION_INT,
  1612. };
  1613. AVCodec ff_jpeg2000_encoder = {
  1614. .name = "jpeg2000",
  1615. .long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
  1616. .type = AVMEDIA_TYPE_VIDEO,
  1617. .id = AV_CODEC_ID_JPEG2000,
  1618. .priv_data_size = sizeof(Jpeg2000EncoderContext),
  1619. .init = j2kenc_init,
  1620. .encode2 = encode_frame,
  1621. .close = j2kenc_destroy,
  1622. .pix_fmts = (const enum AVPixelFormat[]) {
  1623. AV_PIX_FMT_RGB24, AV_PIX_FMT_YUV444P, AV_PIX_FMT_GRAY8,
  1624. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
  1625. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
  1626. AV_PIX_FMT_PAL8,
  1627. AV_PIX_FMT_RGB48, AV_PIX_FMT_GRAY16,
  1628. AV_PIX_FMT_NONE
  1629. },
  1630. .priv_class = &j2k_class,
  1631. .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
  1632. };