/*
 * jcmainct.c
 *
 * Copyright (C) 1994, Thomas G. Lane.
 * This file is part of the Independent JPEG Group's software.
 * For conditions of distribution and use, see the accompanying README file.
 *
 * This file contains the main buffer controller for compression.
 * The main buffer lies between the pre-processor and the JPEG
 * compressor proper; it holds downsampled data in the JPEG colorspace.
 */

#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"


/* Private buffer controller object */

typedef struct {
  struct jpeg_c_main_controller pub; /* public fields */

  JDIMENSION cur_mcu_row;	/* number of current MCU row */
  JDIMENSION rowgroup_ctr;	/* counts row groups received in MCU row */
  JDIMENSION mcu_ctr;		/* counts MCUs output from current row */
  boolean suspended;		/* remember if we suspended output */
  J_BUF_MODE pass_mode;		/* current operating mode */

  /* If using full-image storage, this array holds pointers to virtual-array
   * control blocks for each component.  Unused if not full-image storage.
   */
  jvirt_sarray_ptr virtual[MAX_COMPONENTS];
  /* If using just a strip buffer, this points to the entire set of buffers
   * (we allocate one for each component).  In the virtual-array case, this
   * points to the currently accessible strips of the virtual arrays.
   */
  JSAMPARRAY buffer[MAX_COMPONENTS];
  /* This vector points to the current strips of the components being written
   * during the current scan.
   */
  JSAMPARRAY cur_buffer[MAX_COMPS_IN_SCAN];
} my_main_controller;

typedef my_main_controller * my_main_ptr;


/* Forward declarations */
METHODDEF void process_data_simple_main
	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
METHODDEF void process_data_buffer_main
	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));


/*
 * Initialize for a processing pass.
 */

METHODDEF void
start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
{
  my_main_ptr main = (my_main_ptr) cinfo->main;
  int ci, cindex;

  main->cur_mcu_row = 0;	/* initialize counters */
  main->rowgroup_ctr = 0;
  main->mcu_ctr = 0;
  main->suspended = FALSE;
  main->pass_mode = pass_mode;	/* save mode for use by process_data */

  switch (pass_mode) {
  case JBUF_PASS_THRU:
    if (main->virtual[0] != NULL)
      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
    main->pub.process_data = process_data_simple_main;
    /* The output-strip pointers can be set up once for the whole pass. */
    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
      cindex = cinfo->cur_comp_info[ci]->component_index;
      main->cur_buffer[ci] = main->buffer[cindex];
    }
    break;
  case JBUF_SAVE_SOURCE:
  case JBUF_CRANK_DEST:
  case JBUF_SAVE_AND_PASS:
    if (main->virtual[0] == NULL)
      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
    main->pub.process_data = process_data_buffer_main;
    break;
  default:
    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
    break;
  }
}


/*
 * Process some data.
 * This routine handles the simple pass-through mode,
 * where we have only a strip buffer.
 */

METHODDEF void
process_data_simple_main (j_compress_ptr cinfo,
			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
			  JDIMENSION in_rows_avail)
{
  my_main_ptr main = (my_main_ptr) cinfo->main;

  while (*in_row_ctr < in_rows_avail) {
    /* Read input data if we haven't filled the main buffer yet */
    if (main->rowgroup_ctr < DCTSIZE)
      (*cinfo->prep->pre_process_data) (cinfo,
					input_buf, in_row_ctr, in_rows_avail,
					main->buffer, &main->rowgroup_ctr,
					(JDIMENSION) DCTSIZE);

    /* If we have a full MCU row buffered, emit data. */
    /* Note that preprocessor ensures this will be true at bottom of image. */
    if (main->rowgroup_ctr == DCTSIZE) {
      (*cinfo->coef->compress_data) (cinfo, main->cur_buffer, &main->mcu_ctr);
      /* If compressor did not consume the whole row, then we must need to
       * suspend processing and return to the application.  In this situation
       * we pretend we didn't yet consume the last input row; otherwise, if
       * it happened to be the last row of the image, the application would
       * think we were done.
       */
      if (main->mcu_ctr < cinfo->MCUs_per_row) {
	if (! main->suspended) {
	  (*in_row_ctr)--;
	  main->suspended = TRUE;
	}
	return;
      }
      /* We did finish the row.  Undo our little suspension hack if a previous
       * call suspended; then mark the main buffer empty.
       */
      if (main->suspended) {
	(*in_row_ctr)++;
	main->suspended = FALSE;
      }
      main->mcu_ctr = 0;
      main->rowgroup_ctr = 0;
    }
  }
}


/*
 * Process some data.
 * This routine handles all of the modes that use a full-size buffer.
 */

METHODDEF void
process_data_buffer_main (j_compress_ptr cinfo,
			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
			  JDIMENSION in_rows_avail)
{
  my_main_ptr main = (my_main_ptr) cinfo->main;
  int ci, cindex;
  jpeg_component_info *compptr;
  boolean writing = (main->pass_mode != JBUF_CRANK_DEST);

  /* Realign the virtual buffers if at the start of an MCU row. */
  if (main->rowgroup_ctr == 0) {
    /* Note: during a read pass it is not necessary to reposition the
     * buffers of components not being output.  This could save some I/O,
     * but is not currently implemented.
     */
    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
	 ci++, compptr++) {
      main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
	((j_common_ptr) cinfo, main->virtual[ci],
	 main->cur_mcu_row * (compptr->v_samp_factor * DCTSIZE), writing);
    }
    /* Set the output-strip pointers too. */
    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
      cindex = cinfo->cur_comp_info[ci]->component_index;
      main->cur_buffer[ci] = main->buffer[cindex];
    }
    /* In a read pass, pretend we just read some source data. */
    if (! writing) {
      *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
      main->rowgroup_ctr = DCTSIZE;
    }
  }

  /* If a write pass, read input data until the current MCU strip is full. */
  /* Note: preprocessor will pad if necessary to fill the last MCU strip. */
  if (writing) {
    (*cinfo->prep->pre_process_data) (cinfo,
				      input_buf, in_row_ctr, in_rows_avail,
				      main->buffer, &main->rowgroup_ctr,
				      (JDIMENSION) DCTSIZE);
    /* Quit if we didn't yet fill the MCU strip. */
    if (main->rowgroup_ctr < DCTSIZE)
      return;
  }

  /* Emit data, unless this is a sink-only pass. */
  if (main->pass_mode != JBUF_SAVE_SOURCE) {
    (*cinfo->coef->compress_data) (cinfo, main->cur_buffer, &main->mcu_ctr);
    /* If compressor did not consume the whole row, then we must need to
     * suspend processing and return to the application.  In this situation
     * we pretend we didn't yet consume the last input row; otherwise, if
     * it happened to be the last row of the image, the application would
     * think we were done.
     */
    if (main->mcu_ctr < cinfo->MCUs_per_row) {
      if (! main->suspended) {
	(*in_row_ctr)--;
	main->suspended = TRUE;
      }
      return;
    }
    /* We did finish the row.  Undo our little suspension hack if a previous
     * call suspended; then mark the main buffer empty.
     */
    if (main->suspended) {
      (*in_row_ctr)++;
      main->suspended = FALSE;
    }
  }

  /* If get here, we are done with this MCU strip.  Mark buffer empty. */
  main->mcu_ctr = 0;
  main->rowgroup_ctr = 0;
  main->cur_mcu_row++;
}


/*
 * Initialize main buffer controller.
 */

GLOBAL void
jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
{
  my_main_ptr main;
  int ci;
  jpeg_component_info *compptr;

  main = (my_main_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
				SIZEOF(my_main_controller));
  cinfo->main = (struct jpeg_c_main_controller *) main;
  main->pub.start_pass = start_pass_main;

  /* Create the buffer.  It holds downsampled data, so each component
   * may be of a different size.
   */
  if (need_full_buffer) {
    /* Allocate a full-image virtual array for each component */
    /* Note we implicitly pad the bottom to a multiple of the MCU height */
    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
	 ci++, compptr++) {
      main->virtual[ci] = (*cinfo->mem->request_virt_sarray)
	((j_common_ptr) cinfo, JPOOL_IMAGE,
	 compptr->width_in_blocks * DCTSIZE,
	 compptr->height_in_blocks * DCTSIZE,
	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
    }
  } else {
    main->virtual[0] = NULL;	/* flag for no virtual arrays */
    /* Allocate a strip buffer for each component */
    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
	 ci++, compptr++) {
      main->buffer[ci] = (*cinfo->mem->alloc_sarray)
	((j_common_ptr) cinfo, JPOOL_IMAGE,
	 compptr->width_in_blocks * DCTSIZE,
	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
    }
  }
}
