/************************************************************************
 * dispatch frames                                                      *
 ************************************************************************/

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "splitstream.h"
#include "jpeg.h"
#include "fileString.h" //read video from string

#include "mjpeg.c"

void splitstream_init(DOLProcess *p) {
    p->local->port_count = 0;
    p->local->frame_number = 0;
    //p->local->fi = fopen("videoin.jpg", "", "r");
}

int splitstream_fire(DOLProcess *p) {
    int len = sizeof(_STR);
    unsigned char *ptr, *hptr, *fptr;
    int fLen = 0;
    hptr = _STR;
    fptr = hptr;

    int p_count = p->local->port_count;
    CREATEPORTVAR(port1); //size
    CREATEPORTVAR(port2); //frame
    CREATEPORT(port1, PORT_OUT1, 1, p_count, NUM_OF_PAR_PORTS);
    CREATEPORT(port2, PORT_OUT2, 1, p_count, NUM_OF_PAR_PORTS);

    while (len != 0) {
        ptr = (unsigned char *)memchr(hptr, 0xFF, len);
        if (*(ptr + 1) == (unsigned char) '\xD9') { //end of image 0xFFD9
            ptr += 2;
            fLen = ptr - fptr;

            //for testing
            //p->local->frame_number ++;
            //printf("frame: %d, len:%d\n", p->local->frame_number, fLen);

            DOL_write((void*)port1, &fLen, sizeof(fLen), p);
            DOL_write((void*)port2, fptr, MAX_ENCODED_FRAME, p);

            len -= (ptr - hptr);
            hptr = ptr;
            fptr = hptr;

            //create the next port for next picture
            p_count = (p_count + 1) % NUM_OF_PAR_PORTS;
            CREATEPORT(port1, PORT_OUT1, 1, p_count, NUM_OF_PAR_PORTS);
            CREATEPORT(port2, PORT_OUT2, 1, p_count, NUM_OF_PAR_PORTS);
        } else {
            ptr += 2;
            len -= (ptr - hptr);
            hptr = ptr;
        }

    }
    DOL_detach(p);
    dbgprintf(VERBOSE, "Traffic Generator : end of file reached");
    return 0;
}
