/************************************************************************
 * merge frames into stream                                             *
 ************************************************************************/

#ifdef VIEWER
#include "CImg.h"
using namespace cimg_library;
#endif

#include "mergestream.h"

void mergestream_init(DOLProcess *p) {
    p->local->port_count = 0;
    p->local->num_iter = 0;
#ifdef VIEWER
    p->local->main_disp = new CImgDisplay(320, 240, "DOL MJPEG");
#endif
}

int mergestream_fire(DOLProcess *p) {
    unsigned int i;
    unsigned int *x_size = &(p->local->x_size);
    unsigned int *y_size = &(p->local->y_size);
    CREATEPORTVAR(output_port1);
    CREATEPORTVAR(output_port2);

    dbgprintf(VERBOSE, "\tMERGESTREAM\tthread is alive !\n");

    // create port
    CREATEPORT(output_port1, PORT_IN1, 1, p->local->port_count, NUM_OF_PAR_PORTS);
    CREATEPORT(output_port2, PORT_IN2, 1, p->local->port_count, NUM_OF_PAR_PORTS);
    p->local->port_count = (p->local->port_count + 1) % NUM_OF_PAR_PORTS;

    // get the size
    DOL_read((void*)output_port2, x_size, sizeof(*x_size), p);
    DOL_read((void*)output_port2, y_size, sizeof(*y_size), p);

    //read picture row-by-row
    unsigned char *FrameBuffer = p->local->display_buffer;
    for (i=0; i < *y_size / MCU_sy; i++) {
        DOL_read((void*)output_port1,
                 &(FrameBuffer[i * *x_size * MCU_sy]),
                 *x_size * MCU_sy, p);
    }

#ifdef VIEWER
    //create image from display_buffer and display it
    CImg<unsigned char> img(p->local->display_buffer,
            p->local->x_size, p->local->y_size),
            visu(p->local->x_size, p->local->y_size, 1, 1, 0);
    p->local->main_disp->display(img);
    p->local->main_disp->paint();
#endif

    //end this process
    p->local->num_iter++;
    if (p->local->num_iter == NUMBER_OF_FRAMES) {
        DOL_detach(p);
        return 0;
    }

    return 0;
}
