my code can run well, but when I check it with valgrind,there is a error " is 0 bytes after a " - valgrind

here is my code ( Mask_makeMask function) :
unsigned char *Mask_makeMask(int width, unsigned char *frame,
int *mask, HXecLevel level,int version,int autoMask)
{
unsigned char *masked;
unsigned char *tempmask;
int temp;
int maskv[4];
int maskval = *mask;
if(autoMask == 1)
{
tempmask = (unsigned char *)malloc(width * width);
if(tempmask == NULL) return NULL;
//>>>>>mask 00 process Mask_evaluate is to generate the marsk
maskv[0] = Mask_evaluate(width,frame);
//mask 01
maskMakers[0](width, frame, tempmask);
maskv[1] = Mask_evaluate(width,tempmask);
//mask 02
memset(tempmask,0,sizeof(tempmask));
maskMakers[1](width, frame, tempmask);
maskv[2]= Mask_evaluate(width,tempmask);
//mask 03
memset(tempmask,0,sizeof(tempmask));
maskMakers[2](width, frame, tempmask);
maskv[3] = Mask_evaluate(width,tempmask);
temp = maskv[0];
maskval = 0;
int i;
for(i= 1 ;i<4;i++)
{
if(temp >= maskv[i])
{
maskval = i;
temp = maskv[i];
}
}
}
else
{
tempmask = (unsigned char *)malloc(width * width);
if(tempmask == NULL) return NULL;
if(maskval ==0)
Mask_evaluate(width,frame);
else if( maskval >0 && maskval <=3)
{
maskMakers[maskval-1](width, frame, tempmask);
Mask_evaluate(width,tempmask);
}
free(tempmask);
}
>masked = (unsigned char *)malloc(width * width);#line 4319 valgrind
shows this is an error
>if(masked == NULL)
>{
> return NULL;
>}
if(maskval ==0 )
{
memcpy(masked,frame,width * width);
}
else
maskMakers[maskval-1](width, frame, masked);
Mask_writeInformation(width, masked, maskval, level,version);
*mask = maskval;
if(autoMask == 1)
free(tempmask);
return masked;
}
-------my code runs well but the valgrind log is blew:
==2570== Address 0x5c30429 is 0 bytes after a block of size 729 alloc'd
==2570== at 0x4024F20: malloc (vg_replace_malloc.c:236)
>==2570== by 0x410CB07: Mask_makeMask (barhanxin.c:4319)
==2570== by 0x410CF00: HXcode_encodeMask (barhanxin.c:4468)
1. I tried to initialize the masked by using memset(masked,0,width * width)
when the masked is not null, the HXcode_encodeMask called the
Mask_makeMask function,so I think the issue is Mask_makeMask, could anybody
give me some advice how to solve this issue?

Related

C/C++ Socket UDP Client Data Sending -> Keep sending only one peer

i faced a problem with Multi-UDP Socket.
Now I have a PC(192.168.58.200), and 3 MPU(STM32F4)(192.168.85.100~102).
and I Conncected RS232 With MPU.
When MPU got a messasge, it returns just 'X', and print out same thing with RS232, so i can distinguish when PC can not send message and when MPU can get a message but PC can not recieve the message.
below is my code, Especially "UdpClient[c].Write( TempStr, strlen(TempStr));" doesnt work.
when it send mesage, only one MPU can get a message, and keep reciving 30~40 sec, some times changed other MPU.
1:1 is fine, but problem is more 2 Peer. please share your experiences.
// udpclient.cpp
#include <stdio.h>
#include "UDPCLIENT.h"
#include "UDPServer.h"
struct sPeer
{
char IP[64];
int Port;
};
#define CUR_MPU 3
#define MAX_MPU 16
sPeer Peer[MAX_MPU];
unsigned long _stdcall ReadThread(void *Param)
{
UDPSERVERSOCKET UDPSocket;
int ID = (int)Param;
printf("Server ID %d\n", ID);
UDPSocket.Open(Peer[ID].Port);
while (1)
{
char ReadBuffer[1024];
char Addr[32];
UDPSocket.Read(Addr, ReadBuffer, 1024);
printf("%s>%s\n", Addr, ReadBuffer);
}
UDPSocket.Close();
return 0;
}
int main()
{
sprintf(Peer[0].IP, "192.168.58.100"); Peer[0].Port = 7726;
sprintf(Peer[1].IP, "192.168.58.101"); Peer[1].Port = 7727;
sprintf(Peer[2].IP, "192.168.58.102"); Peer[2].Port = 7728;
///////////////////////쓰레드를 연다./////////////////
for (int c = 0; c < CUR_MPU; c++)
{
DWORD ID;
HANDLE thread01 = CreateThread( NULL,//보안 속성
0,//스택의 크기
ReadThread,//함수
(void *)c,//인자
0,//생성플러그
&ID);// 아이디
}
UDPCLIENTSOCKET UdpClient[CUR_MPU];
for (int c = 0; c < CUR_MPU; c++)
{
UdpClient[c].Open(Peer[c].IP, Peer[c].Port);
}
while (1)
{
char TempStr[1024];
printf("보낼 메시지 ---");
scanf("%s", TempStr);
for (int c = 0; c < CUR_MPU; c++)
{
UdpClient[c].Write( TempStr, strlen(TempStr));
}
}
for (int c = 0; c < CUR_MPU; c++)
UdpClient[c].Close();
return 0;
}
Cleint.cpp
#include "UDPCLIENT.h"
int UDPCLIENTSOCKET::Open(char *Address , int Port)
{
unsigned int addr;
int nRtn = WSAStartup(MAKEWORD(1, 1), &wsaData);
if (nRtn != 0) {
perror("WSAStartup 오류\n");
return -1;
}
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
perror("소켓 오류\n");
WSACleanup();
return -2;
}
lpHostEnt = gethostbyname(Address);
if (lpHostEnt == NULL) {
addr = inet_addr(Address);
lpHostEnt = gethostbyaddr((char *)&addr, 4, AF_INET);
if (lpHostEnt == NULL) {
perror("서버를 찾을 수 없습니다.\n");
_getch();
return -3;
}
}
memset(&addrin, 0, sizeof(addrin));
memcpy(&(addrin.sin_addr),
lpHostEnt->h_addr_list[0],
lpHostEnt->h_length);
addrin.sin_port = htons(Port);
addrin.sin_family = AF_INET;
//addrin.sin_addr.s_addr =
// *((unsigned long *)lpHostEnt->h_addr);
return 1;
}
void UDPCLIENTSOCKET::Close()
{
closesocket(s);
WSACleanup();
}
int UDPCLIENTSOCKET::Write(char *Address, int Port, char *Buffer, int Size)
{
unsigned int addr;
lpHostEnt = gethostbyname(Address);
if (lpHostEnt == NULL) {
addr = inet_addr(Address);
lpHostEnt = gethostbyaddr((char *)&addr, 4, AF_INET);
if (lpHostEnt == NULL) {
perror("서버를 찾을 수 없습니다.\n");
_getch();
return -3;
}
}
memset(&addrin, 0, sizeof(addrin));
memcpy(&(addrin.sin_addr),
lpHostEnt->h_addr_list[0],
lpHostEnt->h_length);
addrin.sin_port = htons(Port);
addrin.sin_family = AF_INET;
int nRtn = sendto(s, Buffer, Size, 0,
(LPSOCKADDR)&addrin, sizeof(addrin));
return nRtn;
}
int UDPCLIENTSOCKET::Write(char *Buffer, int Size)
{
int nRtn = sendto(s, Buffer, Size, 0,
(LPSOCKADDR)&addrin, sizeof(addrin));
return nRtn;
}
Server.cpp
#include "UDPServer.h"
int UDPSERVERSOCKET::Open(u_short uport)
{
int nRtn;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
perror("WSAStartup Error\n");
return -1;
}
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0) {
perror("socket 오류\n");
WSACleanup();
return -2;
}
memset(&addrin, 0, sizeof(addrin));
addrin.sin_port = htons(uport);
addrin.sin_family = AF_INET;
addrin.sin_addr.s_addr = htonl(INADDR_ANY);
nRtn = bind(s, (LPSOCKADDR)&addrin, (int)sizeof(addrin));
if (nRtn == SOCKET_ERROR) {
perror("bind 오류\n");
closesocket(s);
WSACleanup();
return -3;
}
return 1;
}
int UDPSERVERSOCKET::Read(char *Addr, char *Buffer, int Length)
{
int fromlen = (int)sizeof(from);
int nRtn = recvfrom(s,
Buffer,
Length -1,
0,
(SOCKADDR *)&from,
&fromlen);
if (nRtn == SOCKET_ERROR)
{
Addr[0] = 0;
perror("recvform 오류\n");
closesocket(s);
WSACleanup();
return -4;
}
strcpy(Addr, inet_ntoa(from.sin_addr));
Buffer[nRtn] = '\0';
return 1;
}
int UDPSERVERSOCKET::Close()
{
closesocket(s);
WSACleanup();
printf("WSACleanup 완료\n");
return 1;
}
void UDPSERVERSOCKET::ShowErrorMessage(int i)
{
}
void UDPSERVERSOCKET::ReturnClientIP(char *Buffer)
{
}

Why does my structure assignment fail in C language?

Why does my structure assignment fail in C language?
I have a class A: define a structure
typedef struct{
int sockfd;
on_av_frame_cb av_frame_cb;
on_av_frame_cb rtp_cb;
on_error_cb error_cb;
uint8_t *p_buf;
uint8_t *v_buf;
uint8_t *a_buf;
int rtp_flag;
}udp_client_t;
Then I call in class B:
static udp_client_t client;
int jldv_create_client(int src_port,int port ,const char *dst_ip){
udp_client_t *udpClient = &client;
assert(udpClient != NULL);
const char *c_ip = dst_ip;
memset(udpClient, 0, sizeof(udp_client_t));
int ret = create_client(src_port, port, c_ip, &udpClient);
if (ret != 0) {
goto err_output;
}
udpClient->av_frame_cb = (on_av_frame_cb )onVideoFrame;
udpClient->error_cb = on_error;
if (rtp_create(&udpClient) < 0) { ///above problem
goto err_output;
}
printf("rtp_client:%d \n",udpClient->rtp_flag);
return 0;
err_output:
destroy_client(udpClient);
return -1;
}
In the above problem, I used the C class method:
int rtp_create(udp_client_t **data)
{
logi("%s", __func__);
udp_client_t *udpClient = *data;
if(udpClient)
{
udpClient->rtp_flag = 1;
memset(&rtp_cxt, 0, sizeof(rtp_context_t));
int ret = init_server();
if (ret < 0)
{
return -1;
}
rtp_cxt.nalu = alloc_nalu(MAX_FRAME_SIZE);//
if (!rtp_cxt.nalu)
{
loge("alloc nalu failed");
return -2;
}
}
else
{
loge("%s: data is null", __func__);
return -3;
}
printf("udpClient after==>%d \n",udpClient->rtp_flag);
return 0;
}
However, the result of printing is:
udpClient after==>1
rtp_client:0
supplement:
int create_client(int src_port, int dst_port, const char *dst_ip, udp_client_t **client)
{
udp_client_t *udpClient = *client;
assert(udpClient != NULL);
memset(udpClient, 0, sizeof(udp_client_t));
printf("create_client:%p\n",udpClient);
udpClient->port = src_port;
if (pthread_create(&udpClient->recv_tid, NULL, udp_receiver_runnable, (void *) udpClient) != 0)
{
loge("Failed to start new thread");
goto err_output;
}
return 0;
err_output:
memset(udpClient, 0, sizeof(udp_client_t));
return -10;
}
Why is that? Did i use something wrong?

encode .wav file using ffmpeg in objective c or c

I have to encode .wav file and write it into same file,or other file using
ffmpeg library,here is my code for encoding
-(void)audioencode:(const char *)fileName
{
AVFrame *frame;
AVPacket pkt;
int i, j, k, ret, got_output;
int buffer_size;
FILE *f;
uint16_t *samples;
const char *format_name = "wav",
const char *file_url = "/Users/xxxx/Downloads/simple-drum-beat.wav";
avcodec_register_all();
av_register_all();
AVOutputFormat *format = NULL;
for (AVOutputFormat *formatIter = av_oformat_next(NULL); formatIter != NULL; formatIter = av_oformat_next(formatIter)
{
int hasEncoder = NULL != avcodec_find_encoder(formatIter->audio_codec);
if (0 == strcmp(format_name, formatIter->name)) {
format = formatIter;
break;
}
}
AVCodec *codec = avcodec_find_encoder(format->audio_codec);
NSLog(#"tet test tststs");
AVCodecContext *c;
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate audio codec context\n");
exit(1);
}
c->sample_fmt = AV_SAMPLE_FMT_S16;
if (!check_sample_fmt(codec, c->sample_fmt)) {
fprintf(stderr, "Encoder does not support sample format %s",
av_get_sample_fmt_name(c->sample_fmt));
exit(1);
}
c->bit_rate = 64000;//705600;
c->sample_rate = select_sample_rate(codec);
c->channel_layout = select_channel_layout(codec);
c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
c->frame_size = av_get_audio_frame_duration(c, 16);
int bits_per_sample = av_get_bits_per_sample(c->codec_id);
int frameSize = av_get_audio_frame_duration(c,16);
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen(fileName, "wb");
if (!f) {
fprintf(stderr, "Could not open %s\n", fileName);
exit(1);
}
/* frame containing input raw audio */
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate audio frame\n");
exit(1);
}
frame->nb_samples = frameSize/*c->frame_size*/;
frame->format = c->sample_fmt;
frame->channel_layout = c->channel_layout;
buffer_size = av_samples_get_buffer_size(NULL, c->channels,frameSize /*c->frame_size*/,
c->sample_fmt, 0);
samples = av_malloc(buffer_size);
if (!samples) {
fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",
buffer_size);
exit(1);
}
/* setup the data pointers in the AVFrame */
ret = avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
(const uint8_t*)samples, buffer_size, 0);
if (ret < 0) {
fprintf(stderr, "Could not setup audio frame\n");
exit(1);
}
float t, tincr;
/* encode a single tone sound */
t = 0;
tincr = 2 * M_PI * 440.0 / c->sample_rate;
for(i=0;i<800;i++) {
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
for (j = 0; j < frameSize/*c->frame_size*/; j++) {
samples[2*j] = (int)(sin(t) * 10000);
for (k = 1; k < c->channels; k++)
samples[2*j + k] = samples[2*j];
t += tincr;
}
/* encode the samples */
ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding audio frame\n");
exit(1);
}
if (got_output) {
fwrite(pkt.data, 1, pkt.size, f);
av_free_packet(&pkt);
}
}
}
but after encoded file size is zero,
Please suggest what m doing wrong,any help will be appreciate, thanks in advance

mupdf render jpeg2000 lose color?

I am working on an android project, which use vudroid, which in turn use mupdf version 0.5.
Vudroid remove the original openjpeg support of mupdf, I have ported the mupdf version 1.5's openjpeg support.
But I encounter a new problem, color information in jpx image gone, the desired effect:
my effect:
the ported load-jpx code:
#include "fitz.h"
#include "mupdf.h"
/* Without the definition of OPJ_STATIC, compilation fails on windows
* due to the use of __stdcall. We believe it is required on some
* linux toolchains too. */
#define OPJ_STATIC
#ifndef _MSC_VER
#define OPJ_HAVE_STDINT_H
#endif
#include <openjpeg.h>
static void fz_opj_error_callback(const char *msg, void *client_data)
{
//fz_context *ctx = (fz_context *)client_data;
//fz_warn(ctx, "openjpeg error: %s", msg);
}
static void fz_opj_warning_callback(const char *msg, void *client_data)
{
//fz_context *ctx = (fz_context *)client_data;
//fz_warn(ctx, "openjpeg warning: %s", msg);
}
static void fz_opj_info_callback(const char *msg, void *client_data)
{
/* fz_warn("openjpeg info: %s", msg); */
}
typedef struct stream_block_s
{
unsigned char *data;
int size;
int pos;
} stream_block;
static OPJ_SIZE_T fz_opj_stream_read(void * p_buffer, OPJ_SIZE_T p_nb_bytes, void * p_user_data)
{
stream_block *sb = (stream_block *)p_user_data;
int len;
len = sb->size - sb->pos;
if (len < 0)
len = 0;
if (len == 0)
return (OPJ_SIZE_T)-1; /* End of file! */
if ((OPJ_SIZE_T)len > p_nb_bytes)
len = p_nb_bytes;
memcpy(p_buffer, sb->data + sb->pos, len);
sb->pos += len;
return len;
}
static OPJ_OFF_T fz_opj_stream_skip(OPJ_OFF_T skip, void * p_user_data)
{
stream_block *sb = (stream_block *)p_user_data;
if (skip > sb->size - sb->pos)
skip = sb->size - sb->pos;
sb->pos += skip;
return sb->pos;
}
static OPJ_BOOL fz_opj_stream_seek(OPJ_OFF_T seek_pos, void * p_user_data)
{
stream_block *sb = (stream_block *)p_user_data;
if (seek_pos > sb->size)
return OPJ_FALSE;
sb->pos = seek_pos;
return OPJ_TRUE;
}
fz_error
fz_load_jpx(pdf_image* img, unsigned char *data, int size, fz_colorspace *defcs, int indexed)
{
//fz_pixmap *img;
opj_dparameters_t params;
opj_codec_t *codec;
opj_image_t *jpx;
opj_stream_t *stream;
fz_colorspace *colorspace;
unsigned char *p;
OPJ_CODEC_FORMAT format;
int a, n, w, h, depth, sgnd;
int x, y, k, v;
stream_block sb;
if (size < 2)
fz_throw("not enough data to determine image format");
/* Check for SOC marker -- if found we have a bare J2K stream */
if (data[0] == 0xFF && data[1] == 0x4F)
format = OPJ_CODEC_J2K;
else
format = OPJ_CODEC_JP2;
opj_set_default_decoder_parameters(&params);
if (indexed)
params.flags |= OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
codec = opj_create_decompress(format);
opj_set_info_handler(codec, fz_opj_info_callback, 0);
opj_set_warning_handler(codec, fz_opj_warning_callback, 0);
opj_set_error_handler(codec, fz_opj_error_callback, 0);
if (!opj_setup_decoder(codec, &params))
{
fz_throw("j2k decode failed");
}
stream = opj_stream_default_create(OPJ_TRUE);
sb.data = data;
sb.pos = 0;
sb.size = size;
opj_stream_set_read_function(stream, fz_opj_stream_read);
opj_stream_set_skip_function(stream, fz_opj_stream_skip);
opj_stream_set_seek_function(stream, fz_opj_stream_seek);
opj_stream_set_user_data(stream, &sb);
/* Set the length to avoid an assert */
opj_stream_set_user_data_length(stream, size);
if (!opj_read_header(stream, codec, &jpx))
{
opj_stream_destroy(stream);
opj_destroy_codec(codec);
fz_throw("Failed to read JPX header");
}
if (!opj_decode(codec, stream, jpx))
{
opj_stream_destroy(stream);
opj_destroy_codec(codec);
opj_image_destroy(jpx);
fz_throw("Failed to decode JPX image");
}
opj_stream_destroy(stream);
opj_destroy_codec(codec);
/* jpx should never be NULL here, but check anyway */
if (!jpx)
fz_throw("opj_decode failed");
pdf_logimage("opj_decode succeeded");
for (k = 1; k < (int)jpx->numcomps; k++)
{
if (!jpx->comps[k].data)
{
opj_image_destroy(jpx);
fz_throw("image components are missing data");
}
if (jpx->comps[k].w != jpx->comps[0].w)
{
opj_image_destroy(jpx);
fz_throw("image components have different width");
}
if (jpx->comps[k].h != jpx->comps[0].h)
{
opj_image_destroy(jpx);
fz_throw("image components have different height");
}
if (jpx->comps[k].prec != jpx->comps[0].prec)
{
opj_image_destroy(jpx);
fz_throw("image components have different precision");
}
}
n = jpx->numcomps;
w = jpx->comps[0].w;
h = jpx->comps[0].h;
depth = jpx->comps[0].prec;
sgnd = jpx->comps[0].sgnd;
if (jpx->color_space == OPJ_CLRSPC_SRGB && n == 4) { n = 3; a = 1; }
else if (jpx->color_space == OPJ_CLRSPC_SYCC && n == 4) { n = 3; a = 1; }
else if (n == 2) { n = 1; a = 1; }
else if (n > 4) { n = 4; a = 1; }
else { a = 0; }
if (defcs)
{
if (defcs->n == n)
{
colorspace = defcs;
}
else
{
fz_warn("jpx file and dict colorspaces do not match");
defcs = NULL;
}
}
if (!defcs)
{
switch (n)
{
case 1: colorspace = pdf_devicegray; break;
case 3: colorspace = pdf_devicergb; break;
case 4: colorspace = pdf_devicecmyk; break;
}
}
//error = fz_new_pixmap(&img, colorspace, w, h);
//if (error)
// return error;
pdf_logimage("colorspace handled\n");
int bpc = 1;
if (colorspace) {
bpc = 1 + colorspace->n;
};
pdf_logimage("w = %d, bpc = %d, h = %d\n", w, bpc, h);
img->samples = fz_newbuffer(w * bpc * h);
//opj_image_destroy(jpx);
//fz_throw("out of memory loading jpx");
p = (char*)img->samples->bp;
pdf_logimage("start to deal with samples");
for (y = 0; y < h; y++)
{
for (x = 0; x < w; x++)
{
for (k = 0; k < n + a; k++)
{
v = jpx->comps[k].data[y * w + x];
if (sgnd)
v = v + (1 << (depth - 1));
if (depth > 8)
v = v >> (depth - 8);
*p++ = v;
}
if (!a)
*p++ = 255;
}
}
img->samples->wp = p;
pdf_logimage("start to deal with samples succeeded");
opj_image_destroy(jpx);
// if (a)
// {
// if (n == 4)
// {
// fz_pixmap *tmp = fz_new_pixmap(ctx, fz_device_rgb(ctx), w, h);
// fz_convert_pixmap(ctx, tmp, img);
// fz_drop_pixmap(ctx, img);
// img = tmp;
// }
// fz_premultiply_pixmap(ctx, img);
// }
return fz_okay;
}
The render code:
JNIEXPORT jbyteArray JNICALL Java_org_vudroid_pdfdroid_codec_PdfPage_drawPage
(JNIEnv *env, jclass clazz, jlong dochandle, jlong pagehandle)
{
renderdocument_t *doc = (renderdocument_t*) dochandle;
renderpage_t *page = (renderpage_t*) pagehandle;
//DEBUG("PdfView(%p).drawpage(%p, %p)", this, doc, page);
fz_error error;
fz_matrix ctm;
fz_irect viewbox;
fz_pixmap *pixmap;
jfloat *matrix;
jint *viewboxarr;
jint *dimen;
jint *buffer;
int length, val;
pixmap = nil;
/* initialize parameter arrays for MuPDF */
ctm.a = 1;
ctm.b = 0;
ctm.c = 0;
ctm.d = 1;
ctm.e = 0;
ctm.f = 0;
// matrix = (*env)->GetPrimitiveArrayCritical(env, matrixarray, 0);
// ctm.a = matrix[0];
// ctm.b = matrix[1];
// ctm.c = matrix[2];
// ctm.d = matrix[3];
// ctm.e = matrix[4];
// ctm.f = matrix[5];
// (*env)->ReleasePrimitiveArrayCritical(env, matrixarray, matrix, 0);
// DEBUG("Matrix: %f %f %f %f %f %f",
// ctm.a, ctm.b, ctm.c, ctm.d, ctm.e, ctm.f);
// viewboxarr = (*env)->GetPrimitiveArrayCritical(env, viewboxarray, 0);
// viewbox.x0 = viewboxarr[0];
// viewbox.y0 = viewboxarr[1];
// viewbox.x1 = viewboxarr[2];
// viewbox.y1 = viewboxarr[3];
// (*env)->ReleasePrimitiveArrayCritical(env, viewboxarray, viewboxarr, 0);
// DEBUG("Viewbox: %d %d %d %d",
// viewbox.x0, viewbox.y0, viewbox.x1, viewbox.y1);
viewbox.x0 = 0;
viewbox.y0 = 0;
viewbox.x1 = 595;
viewbox.y1 = 841;
/* do the rendering */
DEBUG("doing the rendering...");
//buffer = (*env)->GetPrimitiveArrayCritical(env, bufferarray, 0);
// do the actual rendering:
error = fz_rendertree(&pixmap, doc->rast, page->page->tree,
ctm, viewbox, 1);
/* evil magic: we transform the rendered image's byte order
*/
int x, y;
if (bmpdata)
fz_free(bmpdata);
bmpstride = ((pixmap->w * 3 + 3) / 4) * 4;
bmpdata = fz_malloc(pixmap->h * bmpstride);
DEBUG("inside drawpage, bmpstride = %d, pixmap->w = %d, pixmap->h = %d\n", bmpstride, pixmap->w, pixmap->h);
if (!bmpdata)
return;
for (y = 0; y < pixmap->h; y++)
{
unsigned char *p = bmpdata + y * bmpstride;
unsigned char *s = pixmap->samples + y * pixmap->w * 4;
for (x = 0; x < pixmap->w; x++)
{
p[x * 3 + 0] = s[x * 4 + 3];
p[x * 3 + 1] = s[x * 4 + 2];
p[x * 3 + 2] = s[x * 4 + 1];
}
}
FILE* fp = fopen("/sdcard/drawpage", "wb");
fwrite(bmpdata, pixmap->h * bmpstride, 1, fp);
fclose(fp);
jbyteArray array = (*env)->NewByteArray(env, pixmap->h * bmpstride);
(*env)->SetByteArrayRegion(env, array, 0, pixmap->h * bmpstride, bmpdata);
// if(!error) {
// DEBUG("Converting image buffer pixel order");
// length = pixmap->w * pixmap->h;
// unsigned int *col = pixmap->samples;
// int c = 0;
// for(val = 0; val < length; val++) {
// col[val] = ((col[val] & 0xFF000000) >> 24) |
// ((col[val] & 0x00FF0000) >> 8) |
// ((col[val] & 0x0000FF00) << 8);
// }
// winconvert(pixmap);
// }
// (*env)->ReleasePrimitiveArrayCritical(env, bufferarray, buffer, 0);
fz_free(pixmap);
if (error) {
DEBUG("error!");
throw_exception(env, "error rendering page");
}
DEBUG("PdfView.drawPage() done");
return array;
}
I have compare the jpx output samples to the mupdf-1.5 windows, it is the same, but the colorspace of original jpx have gone.
Could help me to get the colorspace back?
It seems you are trying to use an old version of MuPDF with some bits pulled in from a more recent version. TO be honest that's hardly likely to work. I would also guess that its not the OpenJPEG library causing your problem, since the image appears, but converted to grayscale.
Have you tried opening the file in the current version of MuPDF ? Does it work ?
If so then it seems to me your correct approach should be to use the current code, not try and bolt pieces onto an older version.

Arduino State Machine

This is a cross-post from someone who answered my original question here.
I'm not sure how to go about executing the 3 functions I'm after (as well as introducing even more than 3 in the future).
I am simply trying to Fade/Blink the selected Colour of an RGB LED (and perhaps introduce more functions in the future) where its RGB data is coming back from iOS and sent to an RFDuino BLE module.
Sends a "fade" string to the module picked up by RFduinoBLE_onReceive (char *data, int len) on the Arduino end.
- (IBAction)fadeButtonPressed:(id)sender {
[rfduino send:[#"fade" dataUsingEncoding:NSUTF8StringEncoding]];
}
- (IBAction)blinkButtonPressed:(id)sender {
[rfduino send:[#"blink" dataUsingEncoding:NSUTF8StringEncoding]];
}
Selected Color:
- (void)setColor
{
NSLog(#"colors: RGB %f %f %f", red, green, blue);
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
[colorSwatch setHighlighted:YES];
[colorSwatch setTintColor:color];
uint8_t tx[3] = { red * 255, green * 255, blue * 255 };
NSData *data = [NSData dataWithBytes:(void*)&tx length:3];
[rfduino send:data];
}
This is originally how I set the RGB colour:
void RFduinoBLE_onReceive (char *data, int len) {
if (len >= 3) {
// Get the RGB values.
uint8_t red = data[0];
uint8_t green = data[1];
uint8_t blue = data[2];
// Set PWM for each LED.
analogWrite(rgb2_pin, red);
analogWrite(rgb3_pin, green);
analogWrite(rgb4_pin, blue);
}
}
This was the provided answer that now compiles on Arduino, but I have no idea how to actually execute my functions and where?
#include <RFduinoBLE.h>
int state;
char command;
String hexstring;
// RGB pins.
int redPin = 2;
int grnPin = 3;
int bluPin = 4;
void setup () {
state = 1;
pinMode(redPin, OUTPUT);
pinMode(grnPin, OUTPUT);
pinMode(bluPin, OUTPUT);
// This is the data we want to appear in the advertisement
// (the deviceName length plus the advertisement length must be <= 18 bytes.
RFduinoBLE.deviceName = "iOS";
RFduinoBLE.advertisementInterval = MILLISECONDS(300);
RFduinoBLE.txPowerLevel = -20;
RFduinoBLE.advertisementData = "rgb";
// Start the BLE stack.
RFduinoBLE.begin();
}
void loop () {
//RFduino_ULPDelay(INFINITE);
}
void processCommand (int command, String hex) {
// hex ?
// command ?
}
void RFduinoBLE_onReceive (char *data, int len) {
for (int i = 0; i < len; i++) {
stateMachine(data[i]);
}
}
void stateMachine (char data) {
switch (state) {
case 1:
if (data == 1) {
state = 2;
}
break;
case 2:
if (data == 'b' || data == 'f' || data == 'c') {
command = data;
hexstring = "";
state = 3;
} else if (data != 1) { // Stay in state 2 if we received another 0x01.
state = 1;
}
break;
case 3:
if ((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) {
hexstring = hexstring + data;
if (hexstring.length() == 6) {
state = 4;
}
} else if (data == 1) {
state = 2;
} else {
state = 1;
}
break;
case 4:
if (data == 3) {
processCommand(command, hexstring);
state = 1;
} else if (data == 1) {
state = 2;
} else {
state = 1;
}
break;
}
}
EDIT: Final code
#include <RFduinoBLE.h>
// State properties.
int state = 1;
char command;
String hexstring;
// RGB pins.
int redPin = 2;
int grnPin = 3;
int bluPin = 4;
// Setup function to set RGB pins to OUTPUT pins.
void setup () {
pinMode(redPin, OUTPUT);
pinMode(grnPin, OUTPUT);
pinMode(bluPin, OUTPUT);
// This is the data we want to appear in the advertisement
// (the deviceName length plus the advertisement length must be <= 18 bytes.
RFduinoBLE.deviceName = "iOS";
RFduinoBLE.advertisementInterval = MILLISECONDS(300);
RFduinoBLE.txPowerLevel = -20;
RFduinoBLE.advertisementData = "rgb";
// Start the BLE stack.
RFduinoBLE.begin();
}
void loop () {
switch (command) {
case 1:
// Blink.
break;
case 2:
// Fade.
break;
}
//RFduino_ULPDelay(INFINITE);
}
// Converts HEX as a String to actual HEX values.
// This is needed to properly convert the ASCII value to the hex
// value of each character.
byte getVal (char c) {
if (c >= '0' && c <= '9') return (byte)(c - '0');
else return (byte)(c - 'a' + 10);
}
// Process each function/command.
void processCommand (int command, String hex) {
switch (command) {
case 'b':
command = 1; // Set blink mode.
break;
case 'f':
command = 2; // Set fade mode.
break;
case 'c':
// We put together 2 characters as is
// done with HEX notation and set the color.
byte red = getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) << 4);
byte green = getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) << 4);
byte blue = getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) << 4);
// Set the color.
setColor (red, green, blue);
break;
}
}
// Sets the color of each RGB pin.
void setColor (byte red, byte green, byte blue) {
analogWrite(redPin, red);
analogWrite(grnPin, green);
analogWrite(bluPin, blue);
}
// This function returns data from the radio.
void RFduinoBLE_onReceive (char *data, int len) {
for (int i = 0; i < len; i++) {
stateMachine(data[i]);
}
}
// Main state machine function, which processes
// data depending on the bytes received.
void stateMachine (char data) {
switch (state) {
case 1:
if (data == 1) {
state = 2;
}
break;
case 2:
if (data == 'b' || data == 'f' || data == 'c') {
command = data;
hexstring = "";
state = 3;
} else if (data != 1) { // Stay in state 2 if we received another 0x01.
state = 1;
}
break;
case 3:
if ((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) {
hexstring = hexstring + data;
if (hexstring.length() == 6) {
state = 4;
}
} else if (data == 1) {
state = 2;
} else {
state = 1;
}
break;
case 4:
if (data == 3) {
processCommand(command, hexstring);
state = 1;
} else if (data == 1) {
state = 2;
} else {
state = 1;
}
break;
}
}
There is some code here that you can use to convert hex characters to a byte.
So, you can add this to your existing code -
byte getVal(char c)
{
if (c >= '0' && c <= '9')
return (byte)(c - '0');
else
return (byte)(c-'a'+10)
}
void processCommand (int command, String hex)
{
switch (command) {
case 'b':
command = 1; // set blink mode
break;
case 'f':
command=2; // set fade mode
break;
case 'c':
byte red=getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) << 4);
byte green=getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) << 4);
byte blue=getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) << 4);
setColor(red,green,blue);
}
}
void setColor(byte red,byte green,byte blue)
{
// Set PWM for each LED.
analogWrite(rgb2_pin, red);
analogWrite(rgb3_pin, green);
analogWrite(rgb4_pin, blue);
}
On the iOS side you can use something like this -
-(void) sendCommand:(char)command arg1:(Byte)arg1 arg2:(Byte)arg2 arg3:(Byte) arg3 {
NSString *commandString=[NSString stringWithFormat:#"\001%c%02x%02x%02x\003",command,arg1,arg2,arg3];
NSData *commandData=[commandString dataUsingEncoding:NSASCIIStringEncoding];
[rfduino send:data];
}
- (IBAction)fadeButtonPressed:(id)sender {
[self sendCommand:'f' arg1:0 arg2:0 arg3:0];
}
- (IBAction)blinkButtonPressed:(id)sender {
[self sendCommand:'b' arg1:0 arg2:0 arg3:0];
}
- (void)setColor
{
NSLog(#"colors: RGB %f %f %f", red, green, blue);
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
[colorSwatch setHighlighted:YES];
[colorSwatch setTintColor:color];
[self sendCommand:c arg1:red*255 arg2:green*255 arg3:blue*255];
}