improve delays created by vicon drawing locks, reset_cache segv fix, gang track toolt...
[goodguy/cinelerra.git] / cinelerra-5.1 / guicast / vframe.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2011 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include <errno.h>
23 #include <png.h>
24 #include <jpeglib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdint.h>
28 #include <fcntl.h>
29 #include <sys/shm.h>
30 #include <sys/mman.h>
31
32 #include "bcbitmap.h"
33 #include "bchash.h"
34 #include "bcpbuffer.h"
35 #include "bcresources.h"
36 #include "bcsignals.h"
37 #include "bcsynchronous.h"
38 #include "bctexture.h"
39 #include "bcwindowbase.h"
40 #include "clip.h"
41 #include "bccmodels.h"
42 #include "vframe.h"
43
44 class PngReadFunction
45 {
46 public:
47         static void png_read_function(png_structp png_ptr,
48                         png_bytep data, png_size_t length)
49         {
50                 VFrame *frame = (VFrame*)png_get_io_ptr(png_ptr);
51                 if(frame->image_size - frame->image_offset < (long)length)
52                 {
53                         printf("PngReadFunction::png_read_function %d: overrun\n", __LINE__);
54                         length = frame->image_size - frame->image_offset;
55                 }
56
57                 memcpy(data, &frame->image[frame->image_offset], length);
58                 frame->image_offset += length;
59         };
60 };
61
62
63
64
65
66
67
68 VFrameScene::VFrameScene()
69 {
70 }
71
72 VFrameScene::~VFrameScene()
73 {
74 }
75
76
77 //static BCCounter counter;
78
79 VFramePng::VFramePng(unsigned char *png_data, double s)
80 {
81         long image_size =
82                 ((long)png_data[0] << 24) | ((long)png_data[1] << 16) |
83                 ((long)png_data[2] << 8)  |  (long)png_data[3];
84         if( !s ) s = BC_WindowBase::get_resources()->icon_scale;
85         read_png(png_data+4, image_size, s, s);
86 }
87
88 VFramePng::VFramePng(unsigned char *png_data, long image_size, double xs, double ys)
89 {
90         if( !xs ) xs = BC_WindowBase::get_resources()->icon_scale;
91         if( !ys ) ys = BC_WindowBase::get_resources()->icon_scale;
92         read_png(png_data, image_size, xs, ys);
93 }
94
95 VFramePng::~VFramePng()
96 {
97 }
98
99 VFrame *VFramePng::vframe_png(int fd, double xs, double ys)
100 {
101         struct stat st;
102         if( fstat(fd, &st) ) return 0;
103         long len = st.st_size;
104         if( !len ) return 0;
105         int w = 0, h = 0;
106         unsigned char *bfr = (unsigned char *)
107                 ::mmap (NULL, len, PROT_READ, MAP_SHARED, fd, 0);
108         if( bfr == MAP_FAILED ) return 0;
109         VFrame *vframe = new VFramePng(bfr, len, xs, ys);
110         if( (w=vframe->get_w()) <= 0 || (h=vframe->get_h()) <= 0 ||
111             vframe->get_data() == 0 ) { delete vframe;  vframe = 0; }
112         ::munmap(bfr, len);
113         return vframe;
114 }
115 VFrame *VFramePng::vframe_png(const char *png_path, double xs, double ys)
116 {
117         VFrame *vframe = 0;
118         int fd = ::open(png_path, O_RDONLY);
119         if( fd >= 0 ) {
120                 vframe = vframe_png(fd, xs, ys);
121                 ::close(fd);
122         }
123         return vframe;
124 }
125
126 VFrame::VFrame(VFrame &frame)
127 {
128         reset_parameters(1);
129         params = new BC_Hash;
130         use_shm = frame.use_shm;
131         allocate_data(0, -1, 0, 0, 0, frame.w, frame.h,
132                 frame.color_model, frame.bytes_per_line);
133         copy_vframe(&frame);
134 }
135
136
137 VFrame::VFrame(int w, int h, int color_model, long bytes_per_line)
138 {
139         reset_parameters(1);
140 //  use bytes_per_line == 0 to allocate default unshared
141         if( !bytes_per_line ) { bytes_per_line = -1;  use_shm = 0; }
142         params = new BC_Hash;
143         allocate_data(data, -1, 0, 0, 0, w, h,
144                 color_model, bytes_per_line);
145 }
146
147 VFrame::VFrame(unsigned char *data, int shmid, int w, int h,
148         int color_model, long bytes_per_line)
149 {
150         reset_parameters(1);
151         params = new BC_Hash;
152         allocate_data(data, shmid, 0, 0, 0, w, h,
153                 color_model, bytes_per_line);
154 }
155
156 VFrame::VFrame(unsigned char *data, int shmid,
157                 long y_offset, long u_offset, long v_offset,
158                 int w, int h, int color_model, long bytes_per_line)
159 {
160         reset_parameters(1);
161         params = new BC_Hash;
162         allocate_data(data, shmid, y_offset, u_offset, v_offset, w, h,
163                 color_model, bytes_per_line);
164 }
165
166 VFrame::VFrame(BC_Bitmap *bitmap, int w, int h,
167                  int color_model, long bytes_per_line)
168 {
169         reset_parameters(1);
170         params = new BC_Hash;
171         int shmid = 0;
172         unsigned char *data = 0;
173         if( bitmap->is_shared() )
174                 shmid = bitmap->get_shmid();
175         else
176                 data = bitmap->get_data();
177         allocate_data(data, shmid,
178                 bitmap->get_y_offset(),
179                 bitmap->get_u_offset(),
180                 bitmap->get_v_offset(),
181                 w, h, color_model, bytes_per_line);
182 }
183
184 VFrame::VFrame()
185 {
186         reset_parameters(1);
187         params = new BC_Hash;
188         this->color_model = BC_COMPRESSED;
189 }
190
191
192
193 VFrame::~VFrame()
194 {
195         clear_objects(1);
196 // Delete effect stack
197         prev_effects.remove_all_objects();
198         next_effects.remove_all_objects();
199         delete params;
200         delete scene;
201 }
202
203 int VFrame::equivalent(VFrame *src, int test_stacks)
204 {
205         return (src->get_color_model() == get_color_model() &&
206                 src->get_w() == get_w() &&
207                 src->get_h() == get_h() &&
208                 src->bytes_per_line == bytes_per_line &&
209                 (!test_stacks || equal_stacks(src)));
210 }
211
212 int VFrame::data_matches(VFrame *frame)
213 {
214         if(data && frame->get_data() &&
215                 frame->params_match(get_w(), get_h(), get_color_model()) &&
216                 get_data_size() == frame->get_data_size())
217         {
218                 int data_size = get_data_size();
219                 unsigned char *ptr1 = get_data();
220                 unsigned char *ptr2 = frame->get_data();
221                 for(int i = 0; i < data_size; i++)
222                 {
223                         if(*ptr1++ != *ptr2++) return 0;
224                 }
225                 return 1;
226         }
227         return 0;
228 }
229
230 // long VFrame::set_shm_offset(long offset)
231 // {
232 //      shm_offset = offset;
233 //      return 0;
234 // }
235 //
236 // long VFrame::get_shm_offset()
237 // {
238 //      return shm_offset;
239 // }
240 //
241 int VFrame::get_memory_type()
242 {
243         return memory_type;
244 }
245
246 int VFrame::params_match(int w, int h, int color_model)
247 {
248         return (this->w == w &&
249                 this->h == h &&
250                 this->color_model == color_model);
251 }
252
253
254 int VFrame::reset_parameters(int do_opengl)
255 {
256         status = 1;
257         scene = 0;
258         field2_offset = -1;
259         memory_type = VFrame::PRIVATE;
260 //      shm_offset = 0;
261         shmid = -1;
262         use_shm = 1;
263         bytes_per_line = 0;
264         data = 0;
265         rows = 0;
266         color_model = 0;
267         compressed_allocated = 0;
268         compressed_size = 0;   // Size of current image
269         w = 0;
270         h = 0;
271         y = u = v = a = 0;
272         y_offset = 0;
273         u_offset = 0;
274         v_offset = 0;
275         sequence_number = -1;
276         timestamp = -1.;
277         is_keyframe = 0;
278         pixel_rgb = 0x000000; // BLACK
279         pixel_yuv = 0x008080;
280         draw_alpha = 1.f;
281         draw_flags = ALIAS_OFF;
282         stipple = 0;
283         clear_color = 0x000000;
284         clear_alpha = 0x00;
285
286         if(do_opengl)
287         {
288 // By default, anything is going to be done in RAM
289                 opengl_state = VFrame::RAM;
290                 pbuffer = 0;
291                 texture = 0;
292         }
293
294         prev_effects.set_array_delete();
295         next_effects.set_array_delete();
296         return 0;
297 }
298
299 int VFrame::clear_objects(int do_opengl)
300 {
301 // Remove texture
302         if(do_opengl)
303         {
304                 delete texture;
305                 texture = 0;
306
307                 delete pbuffer;
308                 pbuffer = 0;
309         }
310
311 #ifdef LEAKER
312 if( memory_type != VFrame::SHARED )
313   printf("==del %p from %p\n", data, __builtin_return_address(0));
314 #endif
315
316 // Delete data
317         switch(memory_type)
318         {
319                 case VFrame::PRIVATE:
320 // Memory check
321 // if(this->w * this->h > 1500 * 1100)
322 // printf("VFrame::clear_objects 2 this=%p data=%p\n", this, data);
323                         if(data)
324                         {
325 //printf("VFrame::clear_objects %d this=%p shmid=%p data=%p\n", __LINE__, this, shmid, data);
326                                 if(shmid >= 0)
327                                         shmdt(data);
328                                 else
329                                         free(data);
330 //PRINT_TRACE
331                         }
332
333                         data = 0;
334                         shmid = -1;
335                         break;
336
337                 case VFrame::SHMGET:
338                         if(data)
339                                 shmdt(data);
340                         data = 0;
341                         shmid = -1;
342                         break;
343         }
344
345 // Delete row pointers
346         switch(color_model)
347         {
348                 case BC_COMPRESSED:
349                 case BC_YUV410P:
350                 case BC_YUV411P:
351                 case BC_YUV420P:
352                 case BC_YUV420PI:
353                 case BC_YUV422P:
354                 case BC_YUV444P:
355                 case BC_RGB_FLOATP:
356                 case BC_RGBA_FLOATP:
357                 case BC_GBRP:
358                         break;
359
360                 default:
361                         delete [] rows;
362                         rows = 0;
363                         break;
364         }
365
366
367         return 0;
368 }
369
370 int VFrame::get_field2_offset()
371 {
372         return field2_offset;
373 }
374
375 int VFrame::set_field2_offset(int value)
376 {
377         this->field2_offset = value;
378         return 0;
379 }
380
381 void VFrame::set_keyframe(int value)
382 {
383         this->is_keyframe = value;
384 }
385
386 int VFrame::get_keyframe()
387 {
388         return is_keyframe;
389 }
390
391 void VFrame::get_temp(VFrame *&vfrm, int w, int h, int color_model)
392 {
393         if( vfrm && ( vfrm->color_model != color_model ||
394             vfrm->get_w() != w || vfrm->get_h() != h ) ) {
395                 delete vfrm;  vfrm = 0;
396         }
397         if( !vfrm ) vfrm = new VFrame(w, h, color_model, 0);
398 }
399
400
401
402 VFrameScene* VFrame::get_scene()
403 {
404         return scene;
405 }
406
407 int VFrame::calculate_bytes_per_pixel(int color_model)
408 {
409         return BC_CModels::calculate_pixelsize(color_model);
410 }
411
412 long VFrame::get_bytes_per_line()
413 {
414         return bytes_per_line;
415 }
416
417 long VFrame::get_data_size()
418 {
419         return calculate_data_size(w, h, bytes_per_line, color_model) - 4;
420 }
421
422 long VFrame::calculate_data_size(int w, int h, int bytes_per_line, int color_model)
423 {
424         return BC_CModels::calculate_datasize(w, h, bytes_per_line, color_model);
425 }
426
427 void VFrame::create_row_pointers()
428 {
429         int sz = w * h;
430         switch(color_model) {
431         case BC_YUV410P:
432                 if( this->v_offset ) break;
433                 this->y_offset = 0;
434                 this->u_offset = sz;
435                 this->v_offset = sz + w / 4 * h / 4;
436                 break;
437
438         case BC_YUV420P:
439         case BC_YUV420PI:
440         case BC_YUV411P:
441                 if( this->v_offset ) break;
442                 this->y_offset = 0;
443                 this->u_offset = sz;
444                 this->v_offset = sz + sz / 4;
445                 break;
446
447         case BC_YUV422P:
448                 if( this->v_offset ) break;
449                 this->y_offset = 0;
450                 this->u_offset = sz;
451                 this->v_offset = sz + sz / 2;
452                 break;
453         case BC_YUV444P:
454                 if( this->v_offset ) break;
455                 this->y_offset = 0;
456                 this->u_offset = sz;
457                 this->v_offset = sz + sz;
458                 break;
459         case BC_GBRP:
460                 if( this->v_offset ) break;
461                 this->y_offset = 0;
462                 this->u_offset = sz * sizeof(uint8_t);
463                 this->v_offset = 2 * sz * sizeof(uint8_t);
464                 break;
465         case BC_RGBA_FLOATP:
466                 if( this->v_offset || a ) break;
467                 a = this->data + 3 * sz * sizeof(float);
468         case BC_RGB_FLOATP:
469                 if( this->v_offset ) break;
470                 this->y_offset = 0;
471                 this->u_offset = sz * sizeof(float);
472                 this->v_offset = 2 * sz * sizeof(float);
473                 break;
474
475         default:
476                 rows = new unsigned char*[h];
477                 for(int i = 0; i < h; i++)
478                         rows[i] = &this->data[i * this->bytes_per_line];
479                 return;
480         }
481         y = this->data + this->y_offset;
482         u = this->data + this->u_offset;
483         v = this->data + this->v_offset;
484 }
485
486 int VFrame::allocate_data(unsigned char *data, int shmid,
487                 long y_offset, long u_offset, long v_offset, int w, int h,
488                 int color_model, long bytes_per_line)
489 {
490         this->w = w;
491         this->h = h;
492         this->color_model = color_model;
493         this->bytes_per_pixel = calculate_bytes_per_pixel(color_model);
494         this->y_offset = this->u_offset = this->v_offset = 0;
495 //      if(shmid == 0) {
496 //              printf("VFrame::allocate_data %d shmid == 0\n", __LINE__, shmid);
497 //      }
498
499         this->bytes_per_line = bytes_per_line >= 0 ?
500                 bytes_per_line : this->bytes_per_pixel * w;
501
502 // Allocate data + padding for MMX
503         if(data) {
504 //printf("VFrame::allocate_data %d %p\n", __LINE__, this->data);
505                 memory_type = VFrame::SHARED;
506                 this->data = data;
507                 this->shmid = -1;
508                 this->y_offset = y_offset;
509                 this->u_offset = u_offset;
510                 this->v_offset = v_offset;
511         }
512         else if(shmid >= 0) {
513                 memory_type = VFrame::SHMGET;
514                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
515 //printf("VFrame::allocate_data %d shmid=%d data=%p\n", __LINE__, shmid, this->data);
516                 this->shmid = shmid;
517                 this->y_offset = y_offset;
518                 this->u_offset = u_offset;
519                 this->v_offset = v_offset;
520         }
521         else {
522                 memory_type = VFrame::PRIVATE;
523                 this->data = 0;
524                 int size = calculate_data_size(this->w, this->h,
525                         this->bytes_per_line, this->color_model);
526                 if( use_shm && size >= SHM_MIN_SIZE &&
527                     BC_WindowBase::get_resources()->use_vframe_shm() ) {
528                         this->shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
529                         if( this->shmid >= 0 ) {
530                                 this->data = (unsigned char*)shmat(this->shmid, NULL, 0);
531 //printf("VFrame::allocate_data %d %d %d %p\n", __LINE__, size, this->shmid, this->data);
532 // This causes it to automatically delete when the program exits.
533                                 shmctl(this->shmid, IPC_RMID, 0);
534                         }
535                         else {
536                                 printf("VFrame::allocate_data %d could not allocate"
537                                         " shared memory, %dx%d (model %d) size=0x%08x\n",
538                                         __LINE__, w, h, color_model, size);
539                                 BC_Trace::dump_shm_stats(stdout);
540                         }
541                 }
542 // Have to use malloc for libpng
543                 if( !this->data ) {
544                         this->data = (unsigned char *)malloc(size);
545                         this->shmid = -1;
546                 }
547 // Memory check
548 // if(this->w * this->h > 1500 * 1100)
549 // printf("VFrame::allocate_data 2 this=%p w=%d h=%d this->data=%p\n",
550 // this, this->w, this->h, this->data);
551
552                 if(!this->data)
553                         printf("VFrame::allocate_data %dx%d: memory exhausted.\n", this->w, this->h);
554 #ifdef LEAKER
555 printf("==new %p from %p sz %d\n", this->data, __builtin_return_address(0), size);
556 #endif
557
558 //printf("VFrame::allocate_data %d %p data=%p %d %d\n", __LINE__, this, this->data, this->w, this->h);
559 //if(size > 1000000) printf("VFrame::allocate_data %d\n", size);
560         }
561
562 // Create row pointers
563         create_row_pointers();
564         return 0;
565 }
566
567 void VFrame::set_memory(unsigned char *data,
568         int shmid,
569         long y_offset,
570         long u_offset,
571         long v_offset)
572 {
573         clear_objects(0);
574
575         if(data)
576         {
577                 memory_type = VFrame::SHARED;
578                 this->data = data;
579                 this->shmid = -1;
580                 this->y_offset = y_offset;
581                 this->u_offset = u_offset;
582                 this->v_offset = v_offset;
583         }
584         else
585         if(shmid >= 0)
586         {
587                 memory_type = VFrame::SHMGET;
588                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
589                 this->shmid = shmid;
590         }
591
592         y = this->data + this->y_offset;
593         u = this->data + this->u_offset;
594         v = this->data + this->v_offset;
595
596         create_row_pointers();
597 }
598
599 void VFrame::set_memory(BC_Bitmap *bitmap)
600 {
601         int shmid = 0;
602         unsigned char *data = 0;
603         if( bitmap->is_shared() && !bitmap->is_zombie() )
604                 shmid = bitmap->get_shmid();
605         else
606                 data = bitmap->get_data();
607         set_memory(data, shmid,
608                 bitmap->get_y_offset(),
609                 bitmap->get_u_offset(),
610                 bitmap->get_v_offset());
611 }
612
613 void VFrame::set_compressed_memory(unsigned char *data,
614         int shmid,
615         int data_size,
616         int data_allocated)
617 {
618         clear_objects(0);
619
620         if(data)
621         {
622                 memory_type = VFrame::SHARED;
623                 this->data = data;
624                 this->shmid = -1;
625         }
626         else
627         if(shmid >= 0)
628         {
629                 memory_type = VFrame::SHMGET;
630                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
631                 this->shmid = shmid;
632         }
633
634         this->compressed_allocated = data_allocated;
635         this->compressed_size = data_size;
636 }
637
638
639 // Reallocate uncompressed buffer with or without alpha
640 int VFrame::reallocate(
641         unsigned char *data,
642         int shmid,
643         long y_offset,
644         long u_offset,
645         long v_offset,
646         int w,
647         int h,
648         int color_model,
649         long bytes_per_line)
650 {
651 //      if(shmid == 0) printf("VFrame::reallocate %d shmid=%d\n", __LINE__, shmid);
652         clear_objects(0);
653 //      reset_parameters(0);
654         allocate_data(data,
655                 shmid,
656                 y_offset,
657                 u_offset,
658                 v_offset,
659                 w,
660                 h,
661                 color_model,
662                 bytes_per_line);
663         return 0;
664 }
665
666 int VFrame::allocate_compressed_data(long bytes)
667 {
668         if(bytes < 1) return 1;
669
670 // Want to preserve original contents
671         if(data && compressed_allocated < bytes)
672         {
673                 int new_shmid = -1;
674                 unsigned char *new_data = 0;
675                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
676                 {
677                         new_shmid = shmget(IPC_PRIVATE,
678                                 bytes,
679                                 IPC_CREAT | 0777);
680                         new_data = (unsigned char*)shmat(new_shmid, NULL, 0);
681                         shmctl(new_shmid, IPC_RMID, 0);
682                 }
683                 else
684                 {
685 // Have to use malloc for libpng
686                         new_data = (unsigned char *)malloc(bytes);
687                 }
688
689                 bcopy(data, new_data, compressed_allocated);
690 UNBUFFER(data);
691
692                 if(memory_type == VFrame::PRIVATE)
693                 {
694                         if(shmid > 0) {
695                                 if(data)
696                                         shmdt(data);
697                         }
698                         else
699                                 free(data);
700                 }
701                 else
702                 if(memory_type == VFrame::SHMGET)
703                 {
704                         if(data)
705                                 shmdt(data);
706                 }
707
708                 data = new_data;
709                 shmid = new_shmid;
710                 compressed_allocated = bytes;
711         }
712         else
713         if(!data)
714         {
715                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
716                 {
717                         shmid = shmget(IPC_PRIVATE,
718                                 bytes,
719                                 IPC_CREAT | 0777);
720                         data = (unsigned char*)shmat(shmid, NULL, 0);
721                         shmctl(shmid, IPC_RMID, 0);
722                 }
723                 else
724                 {
725 // Have to use malloc for libpng
726                         data = (unsigned char *)malloc(bytes);
727                 }
728
729                 compressed_allocated = bytes;
730                 compressed_size = 0;
731         }
732
733         return 0;
734 }
735
736 int VFramePng::read_png(const unsigned char *data, long sz, double xscale, double yscale)
737 {
738 // Test for RAW format
739         if(data[0] == 'R' && data[1] == 'A' && data[2] == 'W' && data[3] == ' ') {
740                 int new_color_model = BC_RGBA8888;
741                 w = data[4] | (data[5] << 8) | (data[6]  << 16) | (data[7]  << 24);
742                 h = data[8] | (data[9] << 8) | (data[10] << 16) | (data[11] << 24);
743                 int components = data[12];
744                 new_color_model = components == 3 ? BC_RGB888 : BC_RGBA8888;
745 // This shares the data directly
746 //              reallocate(data + 20, 0, 0, 0, w, h, new_color_model, -1);
747
748 // Can't use shared data for theme since button constructions overlay the
749 // images directly.
750                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
751                 memcpy(get_data(), data + 16, w * h * components);
752
753         }
754         else if(data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') {
755                 int have_alpha = 0;
756                 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
757                 png_infop info_ptr = png_create_info_struct(png_ptr);
758                 int new_color_model;
759
760                 image_offset = 0;
761                 image = data;  image_size = sz;
762                 png_set_read_fn(png_ptr, this, PngReadFunction::png_read_function);
763                 png_read_info(png_ptr, info_ptr);
764
765                 w = png_get_image_width(png_ptr, info_ptr);
766                 h = png_get_image_height(png_ptr, info_ptr);
767
768                 int src_color_model = png_get_color_type(png_ptr, info_ptr);
769
770                 /* tell libpng to strip 16 bit/color files down to 8 bits/color */
771                 png_set_strip_16(png_ptr);
772
773                 /* extract multiple pixels with bit depths of 1, 2, and 4 from a single
774                  * byte into separate bytes (useful for paletted and grayscale images).
775                  */
776                 png_set_packing(png_ptr);
777
778                 /* expand paletted colors into true RGB triplets */
779                 if (src_color_model == PNG_COLOR_TYPE_PALETTE)
780                         png_set_expand(png_ptr);
781
782                 /* expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
783                 if (src_color_model == PNG_COLOR_TYPE_GRAY && png_get_bit_depth(png_ptr, info_ptr) < 8)
784                         png_set_expand(png_ptr);
785
786                 if (src_color_model == PNG_COLOR_TYPE_GRAY_ALPHA)
787                         png_set_gray_to_rgb(png_ptr);
788
789                 /* expand paletted or RGB images with transparency to full alpha channels
790                  * so the data will be available as RGBA quartets */
791                 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)){
792                         have_alpha = 1;
793                         png_set_expand(png_ptr);
794                 }
795
796                 switch(src_color_model) {
797                 case PNG_COLOR_TYPE_GRAY:
798                         new_color_model = BC_GREY8;
799                         break;
800                 case PNG_COLOR_TYPE_RGB:
801                         new_color_model = BC_RGB888;
802                         break;
803                 case PNG_COLOR_TYPE_PALETTE:
804                         new_color_model = have_alpha ? BC_RGBA8888 : BC_RGB888;
805                         break;
806                 case PNG_COLOR_TYPE_GRAY_ALPHA:
807                 case PNG_COLOR_TYPE_RGB_ALPHA:
808                 default:
809                         new_color_model = BC_RGBA8888;
810                         break;
811                 }
812                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
813
814 //printf("VFrame::read_png %d %d %d %p\n", __LINE__, w, h, get_rows());
815                 png_read_image(png_ptr, get_rows());
816                 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
817         }
818         else {
819                 printf("VFrame::read_png %d: unknown file format"
820                         " 0x%02x 0x%02x 0x%02x 0x%02x\n",
821                         __LINE__, data[4], data[5], data[6], data[7]);
822                 return 1;
823         }
824         int ww = w * xscale, hh = h * yscale;
825         if( ww < 1 ) ww = 1;
826         if( hh < 1 ) hh = 1;
827         if( ww != w || hh != h ) {
828                 VFrame vframe(*this);
829                 reallocate(NULL, -1, 0, 0, 0, ww, hh, color_model, -1);
830                 transfer_from(&vframe);
831         }
832         return 0;
833 }
834
835 int VFrame::write_png(const char *path)
836 {
837         VFrame *vframe = this;
838         png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
839         png_infop info_ptr = png_create_info_struct(png_ptr);
840         FILE *out_fd = fopen(path, "w");
841         if(!out_fd) {
842                 printf("VFrame::write_png %d %s %s\n", __LINE__, path, strerror(errno));
843                 return 1;
844         }
845
846         int png_cmodel = PNG_COLOR_TYPE_RGB;
847         int bc_cmodel = get_color_model();
848         switch( bc_cmodel ) {
849         case BC_RGB888:                                          break;
850         case BC_RGBA8888: png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA; break;
851         case BC_A8:       png_cmodel = PNG_COLOR_TYPE_GRAY;      break;
852         default:
853                 bc_cmodel = BC_RGB888;
854                 if( BC_CModels::has_alpha(bc_cmodel) ) {
855                         bc_cmodel = BC_RGBA8888;
856                         png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA;
857                 }
858                 vframe = new VFrame(get_w(), get_h(), bc_cmodel, 0);
859                 vframe->transfer_from(this);
860                 break;
861         }
862         png_init_io(png_ptr, out_fd);
863         png_set_compression_level(png_ptr, 9);
864         png_set_IHDR(png_ptr, info_ptr, get_w(), get_h(), 8, png_cmodel,
865                 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
866         png_write_info(png_ptr, info_ptr);
867         png_write_image(png_ptr, vframe->get_rows());
868         png_write_end(png_ptr, info_ptr);
869         png_destroy_write_struct(&png_ptr, &info_ptr);
870         fclose(out_fd);
871         if( vframe != this ) delete vframe;
872         return 0;
873 }
874
875 void VFrame::write_ppm(VFrame *vfrm, const char *fmt, ...)
876 {
877         va_list ap;
878         va_start(ap, fmt);
879         char fn[BCTEXTLEN];
880         vsnprintf(fn, sizeof(fn), fmt, ap);
881         va_end(ap);
882         FILE *fp = fopen(fn,"w");
883         if( !fp ) { perror("write_ppm"); return; }
884         VFrame *frm = vfrm;
885         if( frm->get_color_model() != BC_RGB888 ) {
886                 frm = new VFrame(frm->get_w(), frm->get_h(), BC_RGB888);
887                 frm->transfer_from(vfrm);
888         }
889         int w = frm->get_w(), h = frm->get_h();
890         fprintf(fp,"P6\n%d %d\n255\n",w,h);
891         unsigned char **rows = frm->get_rows();
892         for( int i=0; i<h; ++i ) fwrite(rows[i],3,w,fp);
893         fclose(fp);
894         if( frm != vfrm ) delete frm;
895 }
896
897
898 #define ZERO_YUV(components, type, max) \
899 { \
900         for(int i = 0; i < h; i++) \
901         { \
902                 type *row = (type*)get_rows()[i]; \
903                 for(int j = 0; j < w; j++) \
904                 { \
905                         row[j * components] = 0; \
906                         row[j * components + 1] = (max + 1) / 2; \
907                         row[j * components + 2] = (max + 1) / 2; \
908                         if(components == 4) row[j * components + 3] = 0; \
909                 } \
910         } \
911 }
912
913 void VFrame::black_frame()
914 {
915         int sz = w * h;
916 //printf("VFrame::black_frame %d\n", __LINE__);
917         switch(color_model) {
918         case BC_COMPRESSED:
919                 break;
920
921         case BC_YUV410P:
922                 bzero(get_y(), sz);
923                 memset(get_u(), 0x80, w / 4 * h / 4);
924                 memset(get_v(), 0x80, w / 4 * h / 4);
925                 break;
926
927         case BC_YUV411P:
928         case BC_YUV420P:
929         case BC_YUV420PI:
930                 bzero(get_y(), sz);
931                 memset(get_u(), 0x80, sz / 4);
932                 memset(get_v(), 0x80, sz / 4);
933                 break;
934
935         case BC_YUV422P:
936                 bzero(get_y(), sz);
937                 memset(get_u(), 0x80, sz / 2);
938                 memset(get_v(), 0x80, sz / 2);
939                 break;
940
941         case BC_GBRP:
942                 bzero(get_y(), sz);
943                 bzero(get_u(), sz);
944                 bzero(get_b(), sz);
945                 break;
946
947         case BC_RGBA_FLOATP: if( a ) {
948                 float *ap = (float *)a;
949                 for( int i=sz; --i>=0; ++ap ) *ap = 0.f; }
950         case BC_RGB_FLOATP: {
951                 float *rp = (float *)y;
952                 for( int i=sz; --i>=0; ++rp ) *rp = 0.f;
953                 float *gp = (float *)u;
954                 for( int i=sz; --i>=0; ++gp ) *gp = 0.f;
955                 float *bp = (float *)v;
956                 for( int i=sz; --i>=0; ++bp ) *bp = 0.f;
957                 break; }
958         case BC_YUV444P:
959                 bzero(get_y(), sz);
960                 memset(get_u(), 0x80, sz);
961                 memset(get_v(), 0x80, sz);
962                 break;
963
964         case BC_YUV888:
965                 ZERO_YUV(3, unsigned char, 0xff);
966                 break;
967
968         case BC_YUVA8888:
969                 ZERO_YUV(4, unsigned char, 0xff);
970                 break;
971
972         case BC_YUV161616:
973                 ZERO_YUV(3, uint16_t, 0xffff);
974                 break;
975
976         case BC_YUVA16161616:
977                 ZERO_YUV(4, uint16_t, 0xffff);
978                 break;
979
980         default:
981                 bzero(data, calculate_data_size(w, h, bytes_per_line, color_model));
982                 break;
983         }
984 }
985
986 void VFrame::set_clear_color(int color, int alpha)
987 {
988         clear_color = color;
989         clear_alpha = alpha;
990 }
991 int VFrame::get_clear_color() { return clear_color; }
992 int VFrame::get_clear_alpha() { return clear_alpha; }
993
994 void VFrame::clear_frame()
995 {
996         if( clear_color >= 0 &&
997             !BC_CModels::init_color(clear_color, clear_alpha,
998                         get_rows(), get_color_model(), get_y(), get_u(), get_v(),
999                         0,0, get_w(),get_h(), get_bytes_per_line()) )
1000                 return;
1001         black_frame();
1002 }
1003
1004 void VFrame::rotate90()
1005 {
1006 // Allocate new frame
1007         int new_w = h, new_h = w;
1008         VFrame new_frame(new_w, new_h, color_model);
1009         unsigned char **new_rows = new_frame.get_rows();
1010 // Copy data
1011         for(int in_y = 0, out_x = new_w - 1; in_y < h; in_y++, out_x--)
1012         {
1013                 for(int in_x = 0, out_y = 0; in_x < w; in_x++, out_y++)
1014                 {
1015                         for(int k = 0; k < bytes_per_pixel; k++)
1016                         {
1017                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
1018                                         rows[in_y][in_x * bytes_per_pixel + k];
1019                         }
1020                 }
1021         }
1022
1023 // Swap frames
1024 // swap memory
1025         unsigned char *new_data = new_frame.data;
1026         new_frame.data = data;
1027         data = new_data;
1028 // swap rows
1029         new_rows = new_frame.rows;
1030         new_frame.rows = rows;
1031         rows = new_rows;
1032 // swap shmid
1033         int new_shmid = new_frame.shmid;
1034         new_frame.shmid = shmid;
1035         shmid = new_shmid;
1036 // swap bytes_per_line
1037         int new_bpl = new_frame.bytes_per_line;
1038         new_frame.bytes_per_line = bytes_per_line;
1039         bytes_per_line = new_bpl;
1040         new_frame.clear_objects(0);
1041
1042         w = new_frame.w;
1043         h = new_frame.h;
1044 }
1045
1046 void VFrame::rotate270()
1047 {
1048 // Allocate new frame
1049         int new_w = h, new_h = w;
1050         VFrame new_frame(new_w, new_h, color_model);
1051         unsigned char **new_rows = new_frame.get_rows();
1052 // Copy data
1053         for(int in_y = 0, out_x = 0; in_y < h; in_y++, out_x++)
1054         {
1055                 for(int in_x = 0, out_y = new_h - 1; in_x < w; in_x++, out_y--)
1056                 {
1057                         for(int k = 0; k < bytes_per_pixel; k++)
1058                         {
1059                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
1060                                         rows[in_y][in_x * bytes_per_pixel + k];
1061                         }
1062                 }
1063         }
1064
1065 // Swap frames
1066 // swap memory
1067         unsigned char *new_data = new_frame.data;
1068         new_frame.data = data;
1069         data = new_data;
1070 // swap rows
1071         new_rows = new_frame.rows;
1072         new_frame.rows = rows;
1073         rows = new_rows;
1074 // swap shmid
1075         int new_shmid = new_frame.shmid;
1076         new_frame.shmid = shmid;
1077         shmid = new_shmid;
1078 // swap bytes_per_line
1079         int new_bpl = new_frame.bytes_per_line;
1080         new_frame.bytes_per_line = bytes_per_line;
1081         bytes_per_line = new_bpl;
1082         new_frame.clear_objects(0);
1083
1084         w = new_frame.w;
1085         h = new_frame.h;
1086 }
1087
1088 void VFrame::flip_vert()
1089 {
1090         unsigned char temp[bytes_per_line];
1091         for( int i=0, j=h; --j>i; ++i ) {
1092                 memcpy(temp, rows[j], bytes_per_line);
1093                 memcpy(rows[j], rows[i], bytes_per_line);
1094                 memcpy(rows[i], temp, bytes_per_line);
1095         }
1096 }
1097
1098 void VFrame::flip_horiz()
1099 {
1100         unsigned char temp[32];
1101         for(int i = 0; i < h; i++)
1102         {
1103                 unsigned char *row = rows[i];
1104                 for(int j = 0; j < bytes_per_line / 2; j += bytes_per_pixel)
1105                 {
1106                         memcpy(temp, row + j, bytes_per_pixel);
1107                         memcpy(row + j, row + bytes_per_line - j - bytes_per_pixel, bytes_per_pixel);
1108                         memcpy(row + bytes_per_line - j - bytes_per_pixel, temp, bytes_per_pixel);
1109                 }
1110         }
1111 }
1112
1113
1114
1115 int VFrame::copy_from(VFrame *frame)
1116 {
1117         if(this->w != frame->get_w() ||
1118                 this->h != frame->get_h())
1119         {
1120                 printf("VFrame::copy_from %d sizes differ src %dx%d != dst %dx%d\n",
1121                         __LINE__,
1122                         frame->get_w(),
1123                         frame->get_h(),
1124                         get_w(),
1125                         get_h());
1126                 return 1;
1127         }
1128
1129         int w = MIN(this->w, frame->get_w());
1130         int h = MIN(this->h, frame->get_h());
1131         timestamp = frame->timestamp;
1132
1133         switch(frame->color_model)
1134         {
1135                 case BC_COMPRESSED:
1136                         allocate_compressed_data(frame->compressed_size);
1137                         memcpy(data, frame->data, frame->compressed_size);
1138                         this->compressed_size = frame->compressed_size;
1139                         break;
1140
1141                 case BC_YUV410P:
1142                         memcpy(get_y(), frame->get_y(), w * h);
1143                         memcpy(get_u(), frame->get_u(), w / 4 * h / 4);
1144                         memcpy(get_v(), frame->get_v(), w / 4 * h / 4);
1145                         break;
1146
1147                 case BC_YUV420P:
1148                 case BC_YUV420PI:
1149                 case BC_YUV411P:
1150 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1151                         memcpy(get_y(), frame->get_y(), w * h);
1152                         memcpy(get_u(), frame->get_u(), w * h / 4);
1153                         memcpy(get_v(), frame->get_v(), w * h / 4);
1154                         break;
1155
1156                 case BC_YUV422P:
1157 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1158                         memcpy(get_y(), frame->get_y(), w * h);
1159                         memcpy(get_u(), frame->get_u(), w * h / 2);
1160                         memcpy(get_v(), frame->get_v(), w * h / 2);
1161                         break;
1162
1163                 case BC_YUV444P:
1164 //printf("%d %d %p %p %p %p %p %p\n", w, h, get_y(), get_u(), get_v(), frame->get_y(), frame->get_u(), frame->get_v());
1165                         memcpy(get_y(), frame->get_y(), w * h);
1166                         memcpy(get_u(), frame->get_u(), w * h);
1167                         memcpy(get_v(), frame->get_v(), w * h);
1168                         break;
1169                 default:
1170 // printf("VFrame::copy_from %d\n", calculate_data_size(w,
1171 //                              h,
1172 //                              -1,
1173 //                              frame->color_model));
1174 // Copy without extra 4 bytes in case the source is a hardware device
1175                         memmove(data, frame->data, get_data_size());
1176                         break;
1177         }
1178
1179         return 0;
1180 }
1181
1182 int VFrame::transfer_from(VFrame *that, int bg_color, int in_x, int in_y, int in_w, int in_h)
1183 {
1184         timestamp = that->timestamp;
1185         copy_params(that);
1186
1187         if( in_x == 0 && in_y == 0 && in_w == that->get_w() && in_h == that->get_h() &&
1188             bg_color == 0 && this->get_color_model() == that->get_color_model() &&
1189             this->get_w() == that->get_w() && this->get_h() == that->get_h() &&
1190             this->get_bytes_per_line() == that->get_bytes_per_line() )
1191                 return this->copy_from(that);
1192
1193 #if 0
1194         BC_CModels::transfer(
1195                 this->get_rows(), that->get_rows(),          // Packed data out/in
1196                 this->get_y(), this->get_u(), this->get_v(), // Planar data out/in
1197                 that->get_y(), that->get_u(), that->get_v(),
1198                 0, 0, that->get_w(), that->get_h(),          // Dimensions in/out
1199                 0, 0, this->get_w(), this->get_h(),
1200                 that->get_color_model(), this->get_color_model(), // Color models in/out
1201                 bg_color,                                    // alpha blend bg_color
1202                 that->get_bytes_per_line(),
1203                 this->get_bytes_per_line());                 // rowspans (of luma for YUV)
1204 #else
1205         unsigned char *in_ptrs[4], *out_ptrs[4];
1206         unsigned char **inp, **outp;
1207         if( BC_CModels::is_planar(that->get_color_model()) ) {
1208                 in_ptrs[0] = that->get_y();
1209                 in_ptrs[1] = that->get_u();
1210                 in_ptrs[2] = that->get_v();
1211                 in_ptrs[3] = that->get_a();
1212                 inp = in_ptrs;
1213         }
1214         else
1215                 inp = that->get_rows();
1216         if( BC_CModels::is_planar(this->get_color_model()) ) {
1217                 out_ptrs[0] = this->get_y();
1218                 out_ptrs[1] = this->get_u();
1219                 out_ptrs[2] = this->get_v();
1220                 out_ptrs[3] = this->get_a();
1221                 outp = out_ptrs;
1222         }
1223         else
1224                 outp = this->get_rows();
1225         BC_CModels::transfer(outp, this->get_color_model(),
1226                         0, 0, this->get_w(), this->get_h(),
1227                         this->get_bytes_per_line(),
1228                 inp, that->get_color_model(),
1229                         in_x, in_y, in_w, in_h,
1230                         that->get_bytes_per_line(),
1231                 bg_color);
1232 #endif
1233         return 0;
1234 }
1235
1236
1237 int VFrame::get_scale_tables(int *column_table, int *row_table,
1238                         int in_x1, int in_y1, int in_x2, int in_y2,
1239                         int out_x1, int out_y1, int out_x2, int out_y2)
1240 {
1241         int i;
1242         float w_in = in_x2 - in_x1;
1243         float h_in = in_y2 - in_y1;
1244         int w_out = out_x2 - out_x1;
1245         int h_out = out_y2 - out_y1;
1246
1247         float hscale = w_in / w_out;
1248         float vscale = h_in / h_out;
1249
1250         for(i = 0; i < w_out; i++)
1251         {
1252                 column_table[i] = (int)(hscale * i);
1253         }
1254
1255         for(i = 0; i < h_out; i++)
1256         {
1257                 row_table[i] = (int)(vscale * i) + in_y1;
1258         }
1259         return 0;
1260 }
1261
1262 void VFrame::push_prev_effect(const char *name)
1263 {
1264         char *ptr;
1265         prev_effects.append(ptr = new char[strlen(name) + 1]);
1266         strcpy(ptr, name);
1267         if(prev_effects.total > MAX_STACK_ELEMENTS) prev_effects.remove_object(0);
1268 }
1269
1270 void VFrame::pop_prev_effect()
1271 {
1272         if(prev_effects.total)
1273                 prev_effects.remove_object(prev_effects.last());
1274 }
1275
1276 void VFrame::push_next_effect(const char *name)
1277 {
1278         char *ptr;
1279         next_effects.append(ptr = new char[strlen(name) + 1]);
1280         strcpy(ptr, name);
1281         if(next_effects.total > MAX_STACK_ELEMENTS) next_effects.remove_object(0);
1282 }
1283
1284 void VFrame::pop_next_effect()
1285 {
1286         if(next_effects.total)
1287                 next_effects.remove_object(next_effects.last());
1288 }
1289
1290 const char* VFrame::get_next_effect(int number)
1291 {
1292         if(!next_effects.total) return "";
1293         else
1294         if(number > next_effects.total - 1) number = next_effects.total - 1;
1295
1296         return next_effects.values[next_effects.total - number - 1];
1297 }
1298
1299 const char* VFrame::get_prev_effect(int number)
1300 {
1301         if(!prev_effects.total) return "";
1302         else
1303         if(number > prev_effects.total - 1) number = prev_effects.total - 1;
1304
1305         return prev_effects.values[prev_effects.total - number - 1];
1306 }
1307
1308 BC_Hash* VFrame::get_params()
1309 {
1310         return params;
1311 }
1312
1313 void VFrame::clear_stacks()
1314 {
1315         next_effects.remove_all_objects();
1316         prev_effects.remove_all_objects();
1317         params->clear();
1318         status = 1;
1319 }
1320
1321 void VFrame::copy_params(VFrame *src)
1322 {
1323         status = src->status;
1324         params->copy_from(src->params);
1325 }
1326
1327 void VFrame::copy_stacks(VFrame *src)
1328 {
1329         clear_stacks();
1330
1331         for( int i=0; i < src->next_effects.total; ++i )
1332                 next_effects.append(cstrdup(src->next_effects[i]));
1333         for( int i=0; i < src->prev_effects.total; ++i )
1334                 prev_effects.append(cstrdup(src->prev_effects[i]));
1335
1336         copy_params(src);
1337 }
1338
1339 int VFrame::copy_vframe(VFrame *frame)
1340 {
1341         copy_stacks(frame);
1342         return copy_from(frame);
1343 }
1344
1345 int VFrame::equal_stacks(VFrame *src)
1346 {
1347         for(int i = 0; i < src->next_effects.total && i < next_effects.total; i++)
1348         {
1349                 if(strcmp(src->next_effects.values[i], next_effects.values[i])) return 0;
1350         }
1351
1352         for(int i = 0; i < src->prev_effects.total && i < prev_effects.total; i++)
1353         {
1354                 if(strcmp(src->prev_effects.values[i], prev_effects.values[i])) return 0;
1355         }
1356
1357         if(!params->equivalent(src->params)) return 0;
1358         return 1;
1359 }
1360
1361 void VFrame::dump_stacks()
1362 {
1363         printf("VFrame::dump_stacks\n");
1364         printf("        next_effects:\n");
1365         for(int i = next_effects.total - 1; i >= 0; i--)
1366                 printf("                %s\n", next_effects.values[i]);
1367         printf("        prev_effects:\n");
1368         for(int i = prev_effects.total - 1; i >= 0; i--)
1369                 printf("                %s\n", prev_effects.values[i]);
1370 }
1371
1372 void VFrame::dump_params()
1373 {
1374         params->dump();
1375 }
1376
1377 void VFrame::dump()
1378 {
1379         printf("VFrame::dump %d this=%p\n", __LINE__, this);
1380         printf("    w=%d h=%d colormodel=%d rows=%p use_shm=%d shmid=%d\n",
1381                 w, h, color_model, rows, use_shm, shmid);
1382 }
1383
1384
1385 int VFrame::get_memory_usage()
1386 {
1387         if(get_compressed_allocated()) return get_compressed_allocated();
1388         return get_h() * get_bytes_per_line();
1389 }
1390
1391 // rgb component colors (eg. from colors.h)
1392 // a (~alpha) transparency, 0x00==solid .. 0xff==transparent
1393 void VFrame::set_pixel_color(int rgb, int a)
1394 {
1395         pixel_rgb = (~a<<24) | (rgb&0xffffff);
1396         int ir = 0xff & (pixel_rgb >> 16);
1397         int ig = 0xff & (pixel_rgb >> 8);
1398         int ib = 0xff & (pixel_rgb >> 0);
1399         YUV::yuv.rgb_to_yuv_8(ir, ig, ib);
1400         pixel_yuv = (~a<<24) | (ir<<16) | (ig<<8) | (ib<<0);
1401 }
1402
1403 void VFrame::set_stiple(int mask)
1404 {
1405         stipple = mask;
1406 }
1407 void VFrame::set_draw_alpha(float alpha)
1408 {
1409         draw_alpha = alpha;
1410 }
1411 void VFrame::set_draw_flags(int flags)
1412 {
1413         draw_flags = flags;
1414 }
1415
1416 int VFrame::draw_pixel(float x, float y, float a)
1417 {
1418         int ix = x, iy = y;
1419         if( ix < 0 || iy < 0 || ix >= get_w() || iy >= get_h() ) return 1;
1420         if( a <= 0 ) return 0;
1421         if( a > 1 ) a = 1;
1422         int color = BC_CModels::is_yuv(color_model) ? pixel_yuv : pixel_rgb;
1423         float fr = 0, fg = 0, fb = 0, fa = 0;
1424         int ir = (0xff & (color >> 16));
1425         int ig = (0xff & (color >> 8));
1426         int ib = (0xff & (color >> 0));
1427         int ia = (0xff & ~(color >> 24));  // transparency, not opacity
1428         if( (ix+iy) & stipple ) {
1429                 ir = 255 - ir;  ig = 255 - ig;  ib = 255 - ib;
1430         }
1431         int rr = (ir<<8) | ir, gg = (ig<<8) | ig, bb = (ib<<8) | ib, aa = (ia<<8) | ia;
1432         float fmax = 65535.f;  fa = aa/fmax;
1433         if( BC_CModels::is_float(color_model) ) {
1434                 fr = rr/fmax;  fg = gg/fmax;  fb = bb/fmax;
1435         }
1436
1437 #define DRAW_PIXEL(cmdl, type, r, g, b, ofs, max, comps) \
1438 case cmdl: { \
1439  float src_a = fa*draw_alpha, src_1a = 1 - src_a; \
1440  type **rows = (type**)get_rows(); \
1441  type *rp = rows[iy], *bp = rp + ix*comps; \
1442  bp[0] = src_a * r + src_1a * bp[0]; \
1443  if( comps > 1 ) { \
1444   bp[1] = src_a * (g-ofs) + src_1a * (bp[1]-ofs) + ofs; \
1445   bp[2] = src_a * (b-ofs) + src_1a * (bp[2]-ofs) + ofs; \
1446  } \
1447  if( comps == 4 ) \
1448   bp[3] = src_a * max + src_1a * bp[3]; \
1449  break;\
1450 }
1451
1452         switch(get_color_model()) {
1453         DRAW_PIXEL(BC_A8,           uint8_t, ib,  0,  0, 0x00, 0xff, 1);
1454         DRAW_PIXEL(BC_RGB888,       uint8_t, ir, ig, ib, 0x00, 0xff, 3);
1455         DRAW_PIXEL(BC_YUV888,       uint8_t, ir, ig, ib, 0x80, 0xff, 3);
1456         DRAW_PIXEL(BC_RGBA8888,     uint8_t, ir, ig, ib, 0x00, 0xff, 4);
1457         DRAW_PIXEL(BC_YUVA8888,     uint8_t, ir, ig, ib, 0x80, 0xff, 4);
1458         DRAW_PIXEL(BC_RGB161616,    uint16_t, rr, gg, bb, 0x0000, 0xffff, 3);
1459         DRAW_PIXEL(BC_YUV161616,    uint16_t, rr, gg, bb, 0x8000, 0xffff, 3);
1460         DRAW_PIXEL(BC_RGBA16161616, uint16_t, rr, gg, bb, 0x0000, 0xffff, 4);
1461         DRAW_PIXEL(BC_YUVA16161616, uint16_t, rr, gg, bb, 0x8000, 0xffff, 4);
1462         DRAW_PIXEL(BC_RGB_FLOAT,    float, fr, fg, fb, 0., 1., 3);
1463         DRAW_PIXEL(BC_RGBA_FLOAT,   float, fr, fg, fb, 0., 1., 4);
1464         }
1465         return 0;
1466 }
1467
1468 int VFrame::draw_pixel(float x, float y, float frac, int axis)
1469 {
1470         if( draw_flags ) {
1471                 int xs = axis, ys = 1-axis;
1472                 if( draw_flags & ALIAS_TOP ) draw_pixel(x-xs, y-ys, 1-frac);
1473                 draw_pixel(x, y, draw_flags & ALIAS_CTR ? 1-frac : 1);
1474                 if( draw_flags & ALIAS_BOT ) draw_pixel(x+xs, y+ys, frac);
1475         }
1476         else
1477                 draw_pixel(x, y);
1478         return 0;
1479 }
1480
1481 void VFrame::draw_line(float x1, float y1, float x2, float y2)
1482 {
1483         if( y1 > y2 ) {
1484                 int tx = x1;  x1 = x2;  x2 = tx;
1485                 int ty = y1;  y1 = y2;  y2 = ty;
1486         }
1487         float dx = x2-x1, dy = y2-y1;
1488         float s = dx ? dy/dx : 1;
1489         float t = dy ? dx/dy : 0;
1490         int xs = dx < 0 ? -1 : 1;
1491         dx *= xs;
1492         int idx = (int)x2 - (int)x1;
1493         int idy = (int)y2 - (int)y1;
1494         int d = dx >= dy ? abs(idx) : idy;
1495         float x = x1, y = y1;
1496         if( dx > dy ) {
1497                 draw_pixel(x, y, y-(int)y, 0);
1498                 while( --d >= 0 ) {
1499                         y = y1 + ((x += xs) - x1) * s;
1500                         draw_pixel(x, y, y-(int)y, 0);
1501                 }
1502         }
1503         else {
1504                 draw_pixel(x, y, x-(int)x, 1);
1505                 while( --d >= 0 ) {
1506                         x = x1 + (++y - y1) * t;
1507                         draw_pixel(x, y, x-(int)x, 1);
1508                 }
1509         }
1510 }
1511
1512 // g++ -dD -E - < /dev/null | grep DBL_EPSILON
1513 #ifndef __DBL_EPSILON__
1514 #define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
1515 #endif
1516 // weakest fraction * graphics integer range
1517 #define RND_EPSILON (__DBL_EPSILON__*65536)
1518
1519 class smooth_line {
1520         int rnd(double v) { return round(v)+RND_EPSILON; }
1521         VFrame *vframe;
1522 public:
1523         int sx, sy, ex, ey;     /* current point, end point */
1524         int xs, ys;             /* x/y quadrant sign -1/1 */
1525         int64_t A, B, C;        /* quadratic coefficients */
1526         int64_t r, dx, dy;      /* residual, dr/dx and dr/dy */
1527         int xmxx, xmxy;         /* x,y at apex */
1528         int done;
1529
1530         void init0(int x1,int y1, int x2,int y2, int x3,int y3, int top);
1531         void init1(int x1,int y1, int x2,int y2, int x3,int y3);
1532         int64_t rx() { return r + xs*8*dx + 4*A; }
1533         void moveX(int64_t r) {
1534                 dx += xs*A;   dy -= xs*B;
1535                 this->r = r;  sx += xs;
1536         }
1537         int64_t ry() { return r + 8*dy + 4*C; }
1538         void moveY(int64_t r) {
1539                 dx -= B;      dy += C;
1540                 this->r = r;  ++sy;
1541         }
1542         void draw();
1543
1544         smooth_line(VFrame *vframe) { this->vframe = vframe; this->done = 0; }
1545 };
1546
1547
1548 void smooth_line::draw()
1549 {
1550         if( done ) return;
1551         if( abs(dy) >= abs(dx) ) {
1552                 if( xs*(sx-xmxx) >= 0 ) {
1553                         if( ys > 0 ) { done = 1;  return; }
1554                         if( dy < 0 || ry() < 0 ) { moveY(ry()); goto xit; }
1555                         xmxx = ex;  xmxy = ey;
1556                         ys = 1;  xs = -xs;
1557                 }
1558                 moveX(rx());
1559                 int64_t rr = ry();
1560                 if( abs(rr) < abs(r) )
1561                         moveY(rr);
1562         }
1563         else {
1564                 if( sy >= xmxy ) {
1565                         if( ys > 0 ) { done = 1;  return; }
1566                         xmxx = ex;  xmxy = ey;
1567                         ys = 1;  xs = -xs;
1568                 }
1569                 moveY(ry());
1570                 int64_t rr = rx();
1571                 if( abs(rr) < abs(r) )
1572                         moveX(rr);
1573         }
1574 xit:
1575 //      vframe->draw_pixel(sx, sy);
1576         float vx = abs(dx), vy = abs(dy);
1577         float vv = 4*(vx > vy ? dx : dy);
1578         float frac = vv ? -r / vv : 0;
1579         frac = (1+frac) / 2;
1580         bclamp(frac, 0, 1);
1581         int axis = abs(dx) >= abs(dy) ? 1 : 0;
1582         vframe->draw_pixel(sx, sy, frac, axis);
1583 }
1584
1585 void VFrame::draw_smooth(int x1, int y1, int x2, int y2, int x3, int y3)
1586 {
1587         if( (x1 == x2 && y1 == y2) || (x2 == x3 && y2 == y3) )
1588                 draw_line(x1,y1, x3,y3);
1589         else if( x1 == x3 && y1 == y3 )
1590                 draw_line(x1,y1, x2,y2);
1591         else if( (x2-x1) * (y2-y3) == (x2-x3) * (y2-y1) ) {
1592                 // co-linear, draw line from min to max
1593                 if( x1 < x3 ) {
1594                         if( x2 < x1 ) { x1 = x2;  y1 = y2; }
1595                         if( x2 > x3 ) { x3 = x2;  y3 = y2; }
1596                 }
1597                 else {
1598                         if( x2 > x1 ) { x1 = x2;  y1 = y2; }
1599                         if( x2 < x3 ) { x3 = x2;  y3 = y2; }
1600                 }
1601                 draw_line(x1,y1, x3,y3);
1602         }
1603         else
1604                 smooth_draw(x1, y1, x2, y2, x3, y3);
1605 }
1606
1607 /*
1608   Non-Parametric Smooth Curve Generation. Don Kelly 1984
1609
1610      P+-----+Q'= virtual
1611      /     /       origin
1612     /     /
1613   Q+-----+R
1614
1615    Let the starting point be P. the ending point R. and the tangent vertex Q.
1616    A general point Z on the curve is then
1617         Z = (P + R - Q) + (Q - P) sin t + (Q - R) cos t
1618
1619    Expanding the Cartesian coordinates around (P + R - Q) gives
1620         [x y] = Z - (P + R - Q)
1621         [a c] = Q - P
1622         [b d] = Q - R
1623         x = a*sin(t) + b*cos(t)
1624         y = c*sin(t) + d*cos(t)
1625
1626    from which t can now be eliminated via
1627         c*x - a*y = (c*b - a*d)*cos(t)
1628         d*x - b*y = (a*d - c*b)*sin(t)
1629
1630    giving the Cartesian equation for the ellipse as
1631         f(x, y) = (c*x - a*y)**2 + (d*x - b*y)**2 - (a*d - c*b)**2 = 0
1632
1633    or:  f(x, y) = A*x**2 - 2*B*x*y + C*y**2 + B**2 - A*C = 0
1634    where: A = c**2 + d**2,  B = a*c + b*d,  C = a**2 + b**2
1635
1636    The maximum y extent of the ellipse may now be derived as follows:
1637         let df/dx = 0,  2*A*x = 2*B*y,  x = y*B/A
1638         f(x, y) == B**2 * y**2 / A - 2*B**2 * y**2 / A + C*y**2 + B**2 - A*C = 0
1639            (A*C - B**2)*y = (A*C - B**2)*A
1640            max x = sqrt(C), at y = B/sqrt(C)
1641            max y = sqrt(A), at x = B/sqrt(A)
1642
1643  */
1644
1645
1646 /* x1,y1 = P, x2,y2 = Q, x3,y3=R,
1647  *  draw from P to Q to R   if top=0
1648  *    or from P to (x,ymax) if top>0
1649  *    or from Q to (x,ymax) if top<0
1650  */
1651 void smooth_line::init0(int x1,int y1, int x2,int y2, int x3,int y3, int top)
1652 {
1653         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1654
1655         int a = x2-x1,  c = y2-y1;
1656         int b = x2-x3,  d = y2-y3;
1657         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1658
1659         sx = top >= 0 ? x1 : x3;
1660         sy = top >= 0 ? y1 : y3;
1661         xs = x2 > sx || (x2==sx && (x1+x3-sx)>=x2) ? 1 : -1;
1662         int64_t px = sx-x0, py = sy-y0;
1663         dx = A*px - B*py;  dy = C*py - B*px;
1664         r = 0;
1665
1666         if( top ) {
1667                 double ymy = sqrt(A), ymx = B/ymy;
1668                 ex = x0 + rnd(ymx);
1669                 ey = y0 + rnd(ymy);
1670         }
1671         else {
1672                 ex = x3;  ey = y3;
1673         }
1674
1675         ys = a*b > 0 && (!top || top*xs*(b*c - a*d) > 0) ? -1 : 1;
1676         if( ys < 0 ) {
1677                 double xmx = xs*sqrt(C), xmy = B/xmx;
1678                 xmxx = x0 + rnd(xmx);
1679                 xmxy = y0 + rnd(xmy);
1680         }
1681         else {
1682                 xmxx = ex; xmxy = ey;
1683         }
1684 }
1685
1686 /*  x1,y1 = P, x2,y2 = Q, x3,y3=R,
1687  *  draw from (x,ymax) to P
1688  */
1689 void smooth_line::init1(int x1,int y1, int x2,int y2, int x3,int y3)
1690 {
1691         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1692
1693         int a = x2-x1,  c = y2-y1;
1694         int b = x2-x3,  d = y2-y3;
1695         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1696
1697         double ymy = -sqrt(A), ymx = B/ymy;
1698         int64_t px = rnd(ymx), py = rnd(ymy);
1699         sx = x0 + px;  ex = x1;
1700         sy = y0 + py;  ey = y1;
1701         xs = x2 > x1 || (x2==x1 && x3>=x2) ? 1 : -1;
1702         dx = A*px - B*py;  dy = C*py - B*px;
1703         r = 4 * (A*px*px - 2*B*px*py + C*py*py + B*B - A*C);
1704
1705         ys = a*b > 0 && xs*(b*c - a*d) < 0 ? -1 : 1;
1706         if( ys < 0 ) {
1707                 double xmx = xs*sqrt(C), xmy = B/xmx;
1708                 xmxx = x0 + rnd(xmx);
1709                 xmxy = y0 + rnd(xmy);
1710         }
1711         else {
1712                 xs = -xs;
1713                 xmxx = ex; xmxy = ey;
1714         }
1715         if( xs > 0 )
1716                 vframe->draw_pixel(sx, sy, 0, 0);
1717         while( xs*(sx-xmxx) < 0 && (xs*dx < 0 || rx() < 0) ) {
1718                 moveX(rx());
1719                 vframe->draw_pixel(sx, sy, 0, 0);
1720         }
1721 }
1722
1723
1724 void VFrame::smooth_draw(int x1, int y1, int x2, int y2, int x3, int y3)
1725 {
1726 //printf("p smooth_draw( %d,%d, %d,%d, %d,%d )\n", x1,y1,x2,y2,x3,y3);
1727         if( y1 > y3 ) {         // make y3 >= y1
1728                 int xt = x1;  x1 = x3;  x3 = xt;
1729                 int yt = y1;  y1 = y3;  y3 = yt;
1730         }
1731         if( y1 > y2 && y3 > y2 ) {
1732                 smooth_line lt(this), rt(this); // Q on bottom
1733                 lt.init1(x1, y1, x2, y2, x3, y3);
1734                 rt.init1(x3, y3, x2, y2, x1, y1);
1735                 while( !lt.done || !rt.done ) {
1736                         lt.draw();
1737                         rt.draw();
1738                 }
1739         }
1740         else if( y1 < y2 && y3 < y2 ) {
1741                 smooth_line lt(this), rt(this); // Q on top
1742                 lt.init0(x1, y1, x2, y2, x3, y3, 1);
1743                 draw_pixel(lt.sx, lt.sy, 0, 0);
1744                 rt.init0(x1, y1, x2, y2, x3, y3, -1);
1745                 draw_pixel(rt.sx, rt.sy, 0, 0);
1746                 while( !lt.done || !rt.done ) {
1747                         lt.draw();
1748                         rt.draw();
1749                 }
1750         }
1751         else {
1752                 smooth_line pt(this);           // Q in between
1753                 pt.init0(x1, y1, x2, y2, x3, y3, 0);
1754                 draw_pixel(pt.sx, pt.sy, 0, 1);
1755                 while( !pt.done ) {
1756                         pt.draw();
1757                 }
1758         }
1759 }
1760
1761
1762 void VFrame::draw_rect(int x1, int y1, int x2, int y2)
1763 {
1764         draw_line(x1, y1, x2, y1);
1765         draw_line(x2, y1 + 1, x2, y2);
1766         draw_line(x2 - 1, y2, x1, y2);
1767         draw_line(x1, y2 - 1, x1, y1 + 1);
1768 }
1769
1770
1771 void VFrame::draw_oval(int x1, int y1, int x2, int y2)
1772 {
1773         int w = x2 - x1;
1774         int h = y2 - y1;
1775         int center_x = (x2 + x1) / 2;
1776         int center_y = (y2 + y1) / 2;
1777         int x_table[h / 2];
1778
1779 //printf("VFrame::draw_oval %d %d %d %d %d\n", __LINE__, x1, y1, x2, y2);
1780
1781         for(int i = 0; i < h / 2; i++) {
1782 // A^2 = -(B^2) + C^2
1783                 x_table[i] = (int)(sqrt(-SQR(h / 2 - i) + SQR(h / 2)) * w / h);
1784 //printf("VFrame::draw_oval %d i=%d x=%d\n", __LINE__, i, x_table[i]);
1785         }
1786
1787         for(int i = 0; i < h / 2 - 1; i++) {
1788                 int x3 = x_table[i];
1789                 int x4 = x_table[i + 1];
1790
1791                 if(x4 > x3 + 1) {
1792                         for(int j = x3; j < x4; j++) {
1793                                 draw_pixel(center_x + j, y1 + i);
1794                                 draw_pixel(center_x - j, y1 + i);
1795                                 draw_pixel(center_x + j, y2 - i - 1);
1796                                 draw_pixel(center_x - j, y2 - i - 1);
1797                         }
1798                 }
1799                 else {
1800                         draw_pixel(center_x + x3, y1 + i);
1801                         draw_pixel(center_x - x3, y1 + i);
1802                         draw_pixel(center_x + x3, y2 - i - 1);
1803                         draw_pixel(center_x - x3, y2 - i - 1);
1804                 }
1805         }
1806         
1807         draw_pixel(center_x, y1);
1808         draw_pixel(center_x, y2 - 1);
1809         draw_pixel(x1, center_y);
1810         draw_pixel(x2 - 1, center_y);
1811         draw_pixel(x1, center_y - 1);
1812         draw_pixel(x2 - 1, center_y - 1);
1813 }
1814
1815
1816 void VFrame::draw_arrow(int x1, int y1, int x2, int y2, int sz)
1817 {
1818         double angle = atan((float)(y2 - y1) / (float)(x2 - x1));
1819         double angle1 = angle + (float)145 / 360 * 2 * M_PI;
1820         double angle2 = angle - (float)145 / 360 * 2 * M_PI;
1821         int s = x2 < x1 ? -1 : 1;
1822         int x3 = x2 + s * (int)(sz * cos(angle1));
1823         int y3 = y2 + s * (int)(sz * sin(angle1));
1824         int x4 = x2 + s * (int)(sz * cos(angle2));
1825         int y4 = y2 + s * (int)(sz * sin(angle2));
1826
1827 // Main vector
1828         draw_line(x1, y1, x2, y2);
1829 //      draw_line(x1, y1 + 1, x2, y2 + 1);
1830
1831 // Arrow line
1832         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x3, y3);
1833 // Arrow line
1834         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x4, y4);
1835 }
1836
1837 void VFrame::draw_x(int x, int y, int sz)
1838 {
1839         draw_line(x-sz,y-sz, x+sz,y+sz);
1840         draw_line(x+sz,y-sz, x-sz,y+sz);
1841 }
1842 void VFrame::draw_t(int x, int y, int sz)
1843 {
1844         draw_line(x,y-sz, x,y+sz);
1845         draw_line(x+sz,y, x-sz,y);
1846 }
1847
1848
1849 // jpeg decompress
1850 class jpeg_err : public jpeg_error_mgr
1851 {
1852         static void s_error_exit(j_common_ptr cp);
1853         static void s_output_message(j_common_ptr cp);
1854 public:
1855         jpeg_err() {
1856                 jpeg_std_error((jpeg_error_mgr *)this);
1857                 error_exit = s_error_exit;
1858                 output_message = s_output_message;
1859         }
1860         ~jpeg_err() {}
1861 };
1862
1863 class jpeg_src : public jpeg_source_mgr
1864 {
1865         static void s_init_source(j_decompress_ptr jp);
1866         static boolean s_fill_input_buffer(j_decompress_ptr jp);
1867         static void s_skip_input_data(j_decompress_ptr jp, long len);
1868         static void s_term_source(j_decompress_ptr jp);
1869         static boolean s_resync_to_restart(j_decompress_ptr jp, int v);
1870 public:
1871         jpeg_src();
1872         ~jpeg_src();
1873         int jpeg_file(int fd);
1874         int jpeg_mem(const unsigned char *bfr, long len);
1875
1876         int fd;
1877         unsigned char *mbfr;
1878         long mlen;
1879         enum { buffer_sz=0x10000, file_sz=0x100000, };
1880         unsigned char *buffer;
1881         boolean fill_buffer();
1882         void skip_data(long len);
1883 };
1884
1885 class JpegVFrame : public jpeg_decompress_struct
1886 {
1887 public:
1888         JpegVFrame();
1889         ~JpegVFrame();
1890         int read_jpeg(VFrame *vfrm, double xs, double ys, int jpeg_model);
1891
1892         jpeg_err jerr;
1893         jpeg_src jsrc;
1894         int debug, ret;
1895 };
1896
1897
1898 void jpeg_err:: s_error_exit(j_common_ptr cp)
1899 {
1900         JpegVFrame *jpeg = (JpegVFrame *)cp;
1901         jpeg->ret = 1;
1902         if( !jpeg->debug ) return;
1903         printf("s_error_exit()\n");
1904 }
1905
1906 void jpeg_err::
1907 s_output_message(j_common_ptr cp)
1908 {
1909         JpegVFrame *jpeg = (JpegVFrame *)cp;
1910         if( !jpeg->debug ) return;
1911         char msg[JMSG_LENGTH_MAX];
1912         (*cp->err->format_message)(cp, msg);
1913         printf("s_output_message() = %s\n",&msg[0]);
1914 }
1915
1916
1917 jpeg_src::jpeg_src()
1918 {
1919         init_source = s_init_source;
1920         fill_input_buffer = s_fill_input_buffer;
1921         skip_input_data = s_skip_input_data;
1922         resync_to_restart = s_resync_to_restart;
1923         term_source = s_term_source;
1924
1925         fd = -1;
1926         buffer = 0;
1927         mbfr = 0;
1928         mlen = -1;
1929 }
1930
1931 jpeg_src::~jpeg_src()
1932 {
1933         if( mbfr ) ::munmap(mbfr, mlen);
1934         delete [] buffer;
1935 }
1936
1937 int jpeg_src::jpeg_file(int fd)
1938 {
1939         this->fd = fd;
1940         struct stat st;
1941         if( fstat(fd, &st) || !st.st_size ) return 0;
1942         if( st.st_size < file_sz ) {
1943                 mbfr = (unsigned char *)::mmap(0, mlen = st.st_size,
1944                                 PROT_READ, MAP_SHARED, fd, 0);
1945                 if( mbfr == MAP_FAILED ) return 0;
1946                 next_input_byte = mbfr;
1947                 bytes_in_buffer = mlen;
1948         }
1949         else {
1950                 buffer = new unsigned char[buffer_sz];
1951                 next_input_byte = &buffer[0];
1952                 bytes_in_buffer = 0;
1953         }
1954         return 1;
1955 }
1956 int jpeg_src::jpeg_mem(const unsigned char *bfr, long len)
1957 {
1958         next_input_byte = bfr;
1959         bytes_in_buffer = len;
1960         return 1;
1961 }
1962
1963 void jpeg_src::s_init_source(j_decompress_ptr jp) {}
1964 void jpeg_src::s_term_source(j_decompress_ptr jp) {}
1965
1966 boolean jpeg_src::s_resync_to_restart(j_decompress_ptr jp, int v)
1967 {
1968         return jpeg_resync_to_restart(jp, v);
1969 }
1970
1971 boolean jpeg_src::s_fill_input_buffer(j_decompress_ptr jp)
1972 {
1973         JpegVFrame *jpeg = (JpegVFrame *)jp;
1974         return jpeg->jsrc.fill_buffer();
1975 }
1976
1977 boolean jpeg_src::fill_buffer()
1978 {
1979         if( mbfr || fd < 0 ) return 0;
1980         long n = ::read(fd, buffer, buffer_sz);
1981         if( n < 0 ) perror("jpeg read");
1982         if( !n ) return 0;
1983         next_input_byte = buffer;
1984         bytes_in_buffer = n;
1985         return 1;
1986 }
1987
1988 void jpeg_src::s_skip_input_data(j_decompress_ptr jp, long len)
1989 {
1990         JpegVFrame *jpeg = (JpegVFrame *)jp;
1991         jpeg->jsrc.skip_data(len);
1992 }
1993
1994 void jpeg_src::skip_data(long len)
1995 {
1996         while( len > (long) bytes_in_buffer ) {
1997                 len -= (long) bytes_in_buffer;
1998                 if( !fill_buffer() ) return;
1999         }
2000         next_input_byte += len;
2001         bytes_in_buffer -= len;
2002 }
2003
2004
2005 JpegVFrame::JpegVFrame()
2006 {
2007         jpeg_create_decompress(this);
2008         debug = 1; ret = 0;
2009         err = &jerr;  src = &jsrc;
2010 }
2011 JpegVFrame::~JpegVFrame()
2012 {
2013         jpeg_destroy_decompress(this);
2014 }
2015
2016 int JpegVFrame::read_jpeg(VFrame *vfrm, double xs, double ys, int jpeg_model)
2017 {
2018         VFrame *xfrm = vfrm;
2019         int color_model = xfrm->get_color_model();
2020         if( color_model == BC_COMPRESSED ) color_model = jpeg_model;
2021         jpeg_abort((jpeg_common_struct *)this);
2022         if( jpeg_read_header(this, TRUE) != JPEG_HEADER_OK ) return 0;
2023         jpeg_calc_output_dimensions(this);
2024         quantize_colors = FALSE;
2025         out_color_space =
2026                 jpeg_model == BC_YUV888 ? JCS_YCbCr :
2027                 jpeg_model == BC_GREY8 ? JCS_GRAYSCALE : JCS_RGB;
2028         jpeg_calc_output_dimensions(this);
2029         int w = bmax(image_width*xs, 1.);
2030         int h = bmax(image_height*ys, 1.);
2031         vfrm->reallocate(0, -1, 0, 0, 0, w, h, color_model, -1);
2032         if( w != (int)image_width || h != (int)image_height ||
2033             color_model != jpeg_model )
2034                 xfrm = new VFrame(image_width, image_height, jpeg_model);
2035         unsigned char *pic = xfrm->get_data();
2036         int linesz = xfrm->get_bytes_per_line();
2037         jpeg_start_decompress(this);
2038         while( !ret && output_scanline < image_height ) {
2039                 JSAMPROW rowptr = (JSAMPROW) &pic[output_scanline * linesz];
2040                 jpeg_read_scanlines(this, &rowptr, (JDIMENSION) 1);
2041         }
2042         jpeg_finish_decompress(this);
2043         if( vfrm != xfrm ) {
2044                 vfrm->transfer_from(xfrm);
2045                 delete xfrm;
2046         }
2047         return 1;
2048 }
2049
2050 int VFrameJpeg::read_jpeg(const unsigned char *data, long sz,
2051                 double xscale, double yscale, int jpeg_model)
2052 {
2053         JpegVFrame jpeg;
2054         jpeg.jsrc.jpeg_mem(data, sz);
2055         return jpeg.read_jpeg(this, xscale, yscale, jpeg_model);
2056 }
2057
2058 VFrameJpeg::VFrameJpeg(const unsigned char *jpeg_data, double s)
2059 {
2060         long image_size =
2061                 ((long)jpeg_data[0] << 24) | ((long)jpeg_data[1] << 16) |
2062                 ((long)jpeg_data[2] << 8)  |  (long)jpeg_data[3];
2063         if( !s ) s = BC_WindowBase::get_resources()->icon_scale;
2064         read_jpeg(jpeg_data+4, image_size, s, s, BC_RGB888);
2065 }
2066
2067 VFrameJpeg::VFrameJpeg(const unsigned char *jpeg_data, long image_size, double xs, double ys)
2068 {
2069         if( !xs ) xs = BC_WindowBase::get_resources()->icon_scale;
2070         if( !ys ) ys = BC_WindowBase::get_resources()->icon_scale;
2071         read_jpeg(jpeg_data, image_size, xs, ys, BC_RGB888);
2072 }
2073
2074 VFrameJpeg::~VFrameJpeg()
2075 {
2076 }
2077
2078
2079 VFrame *VFrameJpeg::vframe_jpeg(int fd, double xs, double ys, int jpeg_model)
2080 {
2081         JpegVFrame jpeg;
2082         jpeg.jsrc.jpeg_file(fd);
2083         VFrame *vfrm = new VFrame();
2084         if( !jpeg.read_jpeg(vfrm, xs, ys, jpeg_model) ) {
2085                 delete vfrm;  vfrm = 0;
2086         }
2087         return vfrm;
2088 }
2089
2090 VFrame *VFrameJpeg::vframe_jpeg(const char *jpeg_path, double xs, double ys, int jpeg_model)
2091 {
2092         VFrame *vframe = 0;
2093         int fd = ::open(jpeg_path, O_RDONLY);
2094         if( fd >= 0 ) {
2095                 vframe = vframe_jpeg(fd, xs, ys, jpeg_model);
2096                 ::close(fd);
2097         }
2098         return vframe;
2099 }
2100