6f0dfbb18e754e8afeed54fb846628a4df0e14e6
[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 <stdio.h>
25 #include <string.h>
26 #include <stdint.h>
27 #include <fcntl.h>
28 #include <sys/shm.h>
29 #include <sys/mman.h>
30
31 #include "bcbitmap.h"
32 #include "bchash.h"
33 #include "bcpbuffer.h"
34 #include "bcresources.h"
35 #include "bcsignals.h"
36 #include "bcsynchronous.h"
37 #include "bctexture.h"
38 #include "bcwindowbase.h"
39 #include "clip.h"
40 #include "bccmodels.h"
41 #include "vframe.h"
42
43 class PngReadFunction
44 {
45 public:
46         static void png_read_function(png_structp png_ptr,
47                    png_bytep data, png_size_t length)
48         {
49                 VFrame *frame = (VFrame*)png_get_io_ptr(png_ptr);
50                 if(frame->image_size - frame->image_offset < (long)length)
51                 {
52                         printf("PngReadFunction::png_read_function %d: overrun\n", __LINE__);
53                         length = frame->image_size - frame->image_offset;
54                 }
55
56                 memcpy(data, &frame->image[frame->image_offset], length);
57                 frame->image_offset += length;
58         };
59 };
60
61
62
63
64
65
66
67 VFrameScene::VFrameScene()
68 {
69 }
70
71 VFrameScene::~VFrameScene()
72 {
73 }
74
75
76
77
78
79
80
81 //static BCCounter counter;
82
83 VFramePng::VFramePng(unsigned char *png_data, double s)
84 {
85         long image_size =
86                 ((long)png_data[0] << 24) | ((long)png_data[1] << 16) |
87                 ((long)png_data[2] << 8)  |  (long)png_data[3];
88         if( !s ) s = BC_WindowBase::get_resources()->icon_scale;
89         read_png(png_data+4, image_size, s, s);
90 }
91
92 VFramePng::VFramePng(unsigned char *png_data, long image_size, double xs, double ys)
93 {
94         if( !xs ) xs = BC_WindowBase::get_resources()->icon_scale;
95         if( !ys ) ys = BC_WindowBase::get_resources()->icon_scale;
96         read_png(png_data, image_size, xs, ys);
97 }
98
99 VFramePng::~VFramePng()
100 {
101 }
102
103 VFrame *VFramePng::vframe_png(int fd, double xs, double ys)
104 {
105         struct stat st;
106         if( fstat(fd, &st) ) return 0;
107         long len = st.st_size;
108         if( !len ) return 0;
109         int w = 0, h = 0;
110         unsigned char *bfr = (unsigned char *)
111                 ::mmap (NULL, len, PROT_READ, MAP_SHARED, fd, 0);
112         if( bfr == MAP_FAILED ) return 0;
113         VFrame *vframe = new VFramePng(bfr, len, xs, ys);
114         if( (w=vframe->get_w()) <= 0 || (h=vframe->get_h()) <= 0 ||
115             vframe->get_data() == 0 ) { delete vframe;  vframe = 0; }
116         ::munmap(bfr, len);
117         return vframe;
118 }
119 VFrame *VFramePng::vframe_png(const char *png_path, double xs, double ys)
120 {
121         VFrame *vframe = 0;
122         int fd = ::open(png_path, O_RDONLY);
123         if( fd >= 0 ) {
124                 vframe = vframe_png(fd, xs, ys);
125                 ::close(fd);
126         }
127         return vframe;
128 }
129
130 VFrame::VFrame(VFrame &frame)
131 {
132         reset_parameters(1);
133         params = new BC_Hash;
134         use_shm = frame.use_shm;
135         allocate_data(0, -1, 0, 0, 0, frame.w, frame.h,
136                 frame.color_model, frame.bytes_per_line);
137         copy_vframe(&frame);
138 }
139
140
141 VFrame::VFrame(int w, int h, int color_model, long bytes_per_line)
142 {
143         reset_parameters(1);
144 //  use bytes_per_line == 0 to allocate default unshared
145         if( !bytes_per_line ) { bytes_per_line = -1;  use_shm = 0; }
146         params = new BC_Hash;
147         allocate_data(data, -1, 0, 0, 0, w, h,
148                 color_model, bytes_per_line);
149 }
150
151 VFrame::VFrame(unsigned char *data, int shmid, int w, int h,
152         int color_model, long bytes_per_line)
153 {
154         reset_parameters(1);
155         params = new BC_Hash;
156         allocate_data(data, shmid, 0, 0, 0, w, h,
157                 color_model, bytes_per_line);
158 }
159
160 VFrame::VFrame(unsigned char *data, int shmid,
161                 long y_offset, long u_offset, long v_offset,
162                 int w, int h, int color_model, long bytes_per_line)
163 {
164         reset_parameters(1);
165         params = new BC_Hash;
166         allocate_data(data, shmid, y_offset, u_offset, v_offset, w, h,
167                 color_model, bytes_per_line);
168 }
169
170 VFrame::VFrame(BC_Bitmap *bitmap, int w, int h,
171                  int color_model, long bytes_per_line)
172 {
173         reset_parameters(1);
174         params = new BC_Hash;
175         int shmid = 0;
176         unsigned char *data = 0;
177         if( bitmap->is_shared() )
178                 shmid = bitmap->get_shmid();
179         else
180                 data = bitmap->get_data();
181         allocate_data(data, shmid,
182                 bitmap->get_y_offset(),
183                 bitmap->get_u_offset(),
184                 bitmap->get_v_offset(),
185                 w, h, color_model, bytes_per_line);
186 }
187
188 VFrame::VFrame()
189 {
190         reset_parameters(1);
191         params = new BC_Hash;
192         this->color_model = BC_COMPRESSED;
193 }
194
195
196
197 VFrame::~VFrame()
198 {
199         clear_objects(1);
200 // Delete effect stack
201         prev_effects.remove_all_objects();
202         next_effects.remove_all_objects();
203         delete params;
204         delete scene;
205 }
206
207 int VFrame::equivalent(VFrame *src, int test_stacks)
208 {
209         return (src->get_color_model() == get_color_model() &&
210                 src->get_w() == get_w() &&
211                 src->get_h() == get_h() &&
212                 src->bytes_per_line == bytes_per_line &&
213                 (!test_stacks || equal_stacks(src)));
214 }
215
216 int VFrame::data_matches(VFrame *frame)
217 {
218         if(data && frame->get_data() &&
219                 frame->params_match(get_w(), get_h(), get_color_model()) &&
220                 get_data_size() == frame->get_data_size())
221         {
222                 int data_size = get_data_size();
223                 unsigned char *ptr1 = get_data();
224                 unsigned char *ptr2 = frame->get_data();
225                 for(int i = 0; i < data_size; i++)
226                 {
227                         if(*ptr1++ != *ptr2++) return 0;
228                 }
229                 return 1;
230         }
231         return 0;
232 }
233
234 // long VFrame::set_shm_offset(long offset)
235 // {
236 //      shm_offset = offset;
237 //      return 0;
238 // }
239 //
240 // long VFrame::get_shm_offset()
241 // {
242 //      return shm_offset;
243 // }
244 //
245 int VFrame::get_memory_type()
246 {
247         return memory_type;
248 }
249
250 int VFrame::params_match(int w, int h, int color_model)
251 {
252         return (this->w == w &&
253                 this->h == h &&
254                 this->color_model == color_model);
255 }
256
257
258 int VFrame::reset_parameters(int do_opengl)
259 {
260         status = 1;
261         scene = 0;
262         field2_offset = -1;
263         memory_type = VFrame::PRIVATE;
264 //      shm_offset = 0;
265         shmid = -1;
266         use_shm = 1;
267         bytes_per_line = 0;
268         data = 0;
269         rows = 0;
270         color_model = 0;
271         compressed_allocated = 0;
272         compressed_size = 0;   // Size of current image
273         w = 0;
274         h = 0;
275         y = u = v = a = 0;
276         y_offset = 0;
277         u_offset = 0;
278         v_offset = 0;
279         sequence_number = -1;
280         timestamp = -1.;
281         is_keyframe = 0;
282         pixel_rgb = 0x000000; // BLACK
283         pixel_yuv = 0x008080;
284         stipple = 0;
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->get_w() != w || vfrm->get_h() != h ) ) {
394                 delete vfrm;  vfrm = 0;
395         }
396         if( !vfrm ) vfrm = new VFrame(w, h, color_model, 0);
397 }
398
399
400
401 VFrameScene* VFrame::get_scene()
402 {
403         return scene;
404 }
405
406 int VFrame::calculate_bytes_per_pixel(int color_model)
407 {
408         return BC_CModels::calculate_pixelsize(color_model);
409 }
410
411 long VFrame::get_bytes_per_line()
412 {
413         return bytes_per_line;
414 }
415
416 long VFrame::get_data_size()
417 {
418         return calculate_data_size(w, h, bytes_per_line, color_model) - 4;
419 }
420
421 long VFrame::calculate_data_size(int w, int h, int bytes_per_line, int color_model)
422 {
423         return BC_CModels::calculate_datasize(w, h, bytes_per_line, color_model);
424 }
425
426 void VFrame::create_row_pointers()
427 {
428         int sz = w * h;
429         switch(color_model) {
430         case BC_YUV410P:
431                 if( this->v_offset ) break;
432                 this->y_offset = 0;
433                 this->u_offset = sz;
434                 this->v_offset = sz + w / 4 * h / 4;
435                 break;
436
437         case BC_YUV420P:
438         case BC_YUV420PI:
439         case BC_YUV411P:
440                 if( this->v_offset ) break;
441                 this->y_offset = 0;
442                 this->u_offset = sz;
443                 this->v_offset = sz + sz / 4;
444                 break;
445
446         case BC_YUV422P:
447                 if( this->v_offset ) break;
448                 this->y_offset = 0;
449                 this->u_offset = sz;
450                 this->v_offset = sz + sz / 2;
451                 break;
452         case BC_YUV444P:
453                 if( this->v_offset ) break;
454                 this->y_offset = 0;
455                 this->u_offset = sz;
456                 this->v_offset = sz + sz;
457                 break;
458         case BC_GBRP:
459                 if( this->v_offset ) break;
460                 this->y_offset = 0;
461                 this->u_offset = sz * sizeof(uint8_t);
462                 this->v_offset = 2 * sz * sizeof(uint8_t);
463                 break;
464         case BC_RGBA_FLOATP:
465                 if( this->v_offset || a ) break;
466                 a = this->data + 3 * sz * sizeof(float);
467         case BC_RGB_FLOATP:
468                 if( this->v_offset ) break;
469                 this->y_offset = 0;
470                 this->u_offset = sz * sizeof(float);
471                 this->v_offset = 2 * sz * sizeof(float);
472                 break;
473
474         default:
475                 rows = new unsigned char*[h];
476                 for(int i = 0; i < h; i++)
477                         rows[i] = &this->data[i * this->bytes_per_line];
478                 return;
479         }
480         y = this->data + this->y_offset;
481         u = this->data + this->u_offset;
482         v = this->data + this->v_offset;
483 }
484
485 int VFrame::allocate_data(unsigned char *data, int shmid,
486                 long y_offset, long u_offset, long v_offset, int w, int h,
487                 int color_model, long bytes_per_line)
488 {
489         this->w = w;
490         this->h = h;
491         this->color_model = color_model;
492         this->bytes_per_pixel = calculate_bytes_per_pixel(color_model);
493         this->y_offset = this->u_offset = this->v_offset = 0;
494 //      if(shmid == 0) {
495 //              printf("VFrame::allocate_data %d shmid == 0\n", __LINE__, shmid);
496 //      }
497
498         this->bytes_per_line = bytes_per_line >= 0 ?
499                 bytes_per_line : this->bytes_per_pixel * w;
500
501 // Allocate data + padding for MMX
502         if(data) {
503 //printf("VFrame::allocate_data %d %p\n", __LINE__, this->data);
504                 memory_type = VFrame::SHARED;
505                 this->data = data;
506                 this->shmid = -1;
507                 this->y_offset = y_offset;
508                 this->u_offset = u_offset;
509                 this->v_offset = v_offset;
510         }
511         else if(shmid >= 0) {
512                 memory_type = VFrame::SHMGET;
513                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
514 //printf("VFrame::allocate_data %d shmid=%d data=%p\n", __LINE__, shmid, this->data);
515                 this->shmid = shmid;
516                 this->y_offset = y_offset;
517                 this->u_offset = u_offset;
518                 this->v_offset = v_offset;
519         }
520         else {
521                 memory_type = VFrame::PRIVATE;
522                 this->data = 0;
523                 int size = calculate_data_size(this->w, this->h,
524                         this->bytes_per_line, this->color_model);
525                 if( use_shm && size >= SHM_MIN_SIZE &&
526                     BC_WindowBase::get_resources()->use_vframe_shm() ) {
527                         this->shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | 0777);
528                         if( this->shmid >= 0 ) {
529                                 this->data = (unsigned char*)shmat(this->shmid, NULL, 0);
530 //printf("VFrame::allocate_data %d %d %d %p\n", __LINE__, size, this->shmid, this->data);
531 // This causes it to automatically delete when the program exits.
532                                 shmctl(this->shmid, IPC_RMID, 0);
533                         }
534                         else {
535                                 printf("VFrame::allocate_data %d could not allocate"
536                                         " shared memory, %dx%d (model %d) size=0x%08x\n",
537                                         __LINE__, w, h, color_model, size);
538                                 BC_Trace::dump_shm_stats(stdout);
539                         }
540                 }
541 // Have to use malloc for libpng
542                 if( !this->data ) {
543                         this->data = (unsigned char *)malloc(size);
544                         this->shmid = -1;
545                 }
546 // Memory check
547 // if(this->w * this->h > 1500 * 1100)
548 // printf("VFrame::allocate_data 2 this=%p w=%d h=%d this->data=%p\n",
549 // this, this->w, this->h, this->data);
550
551                 if(!this->data)
552                         printf("VFrame::allocate_data %dx%d: memory exhausted.\n", this->w, this->h);
553 #ifdef LEAKER
554 printf("==new %p from %p sz %d\n", this->data, __builtin_return_address(0), size);
555 #endif
556
557 //printf("VFrame::allocate_data %d %p data=%p %d %d\n", __LINE__, this, this->data, this->w, this->h);
558 //if(size > 1000000) printf("VFrame::allocate_data %d\n", size);
559         }
560
561 // Create row pointers
562         create_row_pointers();
563         return 0;
564 }
565
566 void VFrame::set_memory(unsigned char *data,
567         int shmid,
568         long y_offset,
569         long u_offset,
570         long v_offset)
571 {
572         clear_objects(0);
573
574         if(data)
575         {
576                 memory_type = VFrame::SHARED;
577                 this->data = data;
578                 this->shmid = -1;
579                 this->y_offset = y_offset;
580                 this->u_offset = u_offset;
581                 this->v_offset = v_offset;
582         }
583         else
584         if(shmid >= 0)
585         {
586                 memory_type = VFrame::SHMGET;
587                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
588                 this->shmid = shmid;
589         }
590
591         y = this->data + this->y_offset;
592         u = this->data + this->u_offset;
593         v = this->data + this->v_offset;
594
595         create_row_pointers();
596 }
597
598 void VFrame::set_memory(BC_Bitmap *bitmap)
599 {
600         int shmid = 0;
601         unsigned char *data = 0;
602         if( bitmap->is_shared() && !bitmap->is_zombie() )
603                 shmid = bitmap->get_shmid();
604         else
605                 data = bitmap->get_data();
606         set_memory(data, shmid,
607                 bitmap->get_y_offset(),
608                 bitmap->get_u_offset(),
609                 bitmap->get_v_offset());
610 }
611
612 void VFrame::set_compressed_memory(unsigned char *data,
613         int shmid,
614         int data_size,
615         int data_allocated)
616 {
617         clear_objects(0);
618
619         if(data)
620         {
621                 memory_type = VFrame::SHARED;
622                 this->data = data;
623                 this->shmid = -1;
624         }
625         else
626         if(shmid >= 0)
627         {
628                 memory_type = VFrame::SHMGET;
629                 this->data = (unsigned char*)shmat(shmid, NULL, 0);
630                 this->shmid = shmid;
631         }
632
633         this->compressed_allocated = data_allocated;
634         this->compressed_size = data_size;
635 }
636
637
638 // Reallocate uncompressed buffer with or without alpha
639 int VFrame::reallocate(
640         unsigned char *data,
641         int shmid,
642         long y_offset,
643         long u_offset,
644         long v_offset,
645         int w,
646         int h,
647         int color_model,
648         long bytes_per_line)
649 {
650 //      if(shmid == 0) printf("VFrame::reallocate %d shmid=%d\n", __LINE__, shmid);
651         clear_objects(0);
652 //      reset_parameters(0);
653         allocate_data(data,
654                 shmid,
655                 y_offset,
656                 u_offset,
657                 v_offset,
658                 w,
659                 h,
660                 color_model,
661                 bytes_per_line);
662         return 0;
663 }
664
665 int VFrame::allocate_compressed_data(long bytes)
666 {
667         if(bytes < 1) return 1;
668
669 // Want to preserve original contents
670         if(data && compressed_allocated < bytes)
671         {
672                 int new_shmid = -1;
673                 unsigned char *new_data = 0;
674                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
675                 {
676                         new_shmid = shmget(IPC_PRIVATE,
677                                 bytes,
678                                 IPC_CREAT | 0777);
679                         new_data = (unsigned char*)shmat(new_shmid, NULL, 0);
680                         shmctl(new_shmid, IPC_RMID, 0);
681                 }
682                 else
683                 {
684 // Have to use malloc for libpng
685                         new_data = (unsigned char *)malloc(bytes);
686                 }
687
688                 bcopy(data, new_data, compressed_allocated);
689 UNBUFFER(data);
690
691                 if(memory_type == VFrame::PRIVATE)
692                 {
693                         if(shmid > 0) {
694                                 if(data)
695                                         shmdt(data);
696                         }
697                         else
698                                 free(data);
699                 }
700                 else
701                 if(memory_type == VFrame::SHMGET)
702                 {
703                         if(data)
704                                 shmdt(data);
705                 }
706
707                 data = new_data;
708                 shmid = new_shmid;
709                 compressed_allocated = bytes;
710         }
711         else
712         if(!data)
713         {
714                 if(BC_WindowBase::get_resources()->use_vframe_shm() && use_shm)
715                 {
716                         shmid = shmget(IPC_PRIVATE,
717                                 bytes,
718                                 IPC_CREAT | 0777);
719                         data = (unsigned char*)shmat(shmid, NULL, 0);
720                         shmctl(shmid, IPC_RMID, 0);
721                 }
722                 else
723                 {
724 // Have to use malloc for libpng
725                         data = (unsigned char *)malloc(bytes);
726                 }
727
728                 compressed_allocated = bytes;
729                 compressed_size = 0;
730         }
731
732         return 0;
733 }
734
735 int VFramePng::read_png(const unsigned char *data, long sz, double xscale, double yscale)
736 {
737 // Test for RAW format
738         if(data[0] == 'R' && data[1] == 'A' && data[2] == 'W' && data[3] == ' ') {
739                 int new_color_model = BC_RGBA8888;
740                 w = data[4] | (data[5] << 8) | (data[6]  << 16) | (data[7]  << 24);
741                 h = data[8] | (data[9] << 8) | (data[10] << 16) | (data[11] << 24);
742                 int components = data[12];
743                 new_color_model = components == 3 ? BC_RGB888 : BC_RGBA8888;
744 // This shares the data directly
745 //              reallocate(data + 20, 0, 0, 0, w, h, new_color_model, -1);
746
747 // Can't use shared data for theme since button constructions overlay the
748 // images directly.
749                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
750                 memcpy(get_data(), data + 16, w * h * components);
751
752         }
753         else if(data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') {
754                 int have_alpha = 0;
755                 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
756                 png_infop info_ptr = png_create_info_struct(png_ptr);
757                 int new_color_model;
758
759                 image_offset = 0;
760                 image = data;  image_size = sz;
761                 png_set_read_fn(png_ptr, this, PngReadFunction::png_read_function);
762                 png_read_info(png_ptr, info_ptr);
763
764                 w = png_get_image_width(png_ptr, info_ptr);
765                 h = png_get_image_height(png_ptr, info_ptr);
766
767                 int src_color_model = png_get_color_type(png_ptr, info_ptr);
768
769                 /* tell libpng to strip 16 bit/color files down to 8 bits/color */
770                 png_set_strip_16(png_ptr);
771
772                 /* extract multiple pixels with bit depths of 1, 2, and 4 from a single
773                  * byte into separate bytes (useful for paletted and grayscale images).
774                  */
775                 png_set_packing(png_ptr);
776
777                 /* expand paletted colors into true RGB triplets */
778                 if (src_color_model == PNG_COLOR_TYPE_PALETTE)
779                         png_set_expand(png_ptr);
780
781                 /* expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
782                 if (src_color_model == PNG_COLOR_TYPE_GRAY && png_get_bit_depth(png_ptr, info_ptr) < 8)
783                         png_set_expand(png_ptr);
784
785                 if (src_color_model == PNG_COLOR_TYPE_GRAY ||
786                     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                 {
798                         case PNG_COLOR_TYPE_GRAY:
799                         case PNG_COLOR_TYPE_RGB:
800                                 new_color_model = BC_RGB888;
801                                 break;
802
803                         case PNG_COLOR_TYPE_GRAY_ALPHA:
804                         case PNG_COLOR_TYPE_RGB_ALPHA:
805                         default:
806                                 new_color_model = BC_RGBA8888;
807                                 break;
808
809                         case PNG_COLOR_TYPE_PALETTE:
810                                 if(have_alpha)
811                                         new_color_model = BC_RGBA8888;
812                                 else
813                                         new_color_model = BC_RGB888;
814                 }
815
816                 reallocate(NULL, -1, 0, 0, 0, w, h, new_color_model, -1);
817
818 //printf("VFrame::read_png %d %d %d %p\n", __LINE__, w, h, get_rows());
819                 png_read_image(png_ptr, get_rows());
820                 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
821         }
822         else {
823                 printf("VFrame::read_png %d: unknown file format"
824                         " 0x%02x 0x%02x 0x%02x 0x%02x\n",
825                         __LINE__, data[4], data[5], data[6], data[7]);
826                 return 1;
827         }
828         int ww = w * xscale, hh = h * yscale;
829         if( ww != w || hh != h ) {
830                 VFrame vframe(*this);
831                 reallocate(NULL, -1, 0, 0, 0, ww, hh, color_model, -1);
832                 transfer_from(&vframe);
833         }
834         return 0;
835 }
836
837 int VFrame::write_png(const char *path)
838 {
839         VFrame *vframe = this;
840         png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
841         png_infop info_ptr = png_create_info_struct(png_ptr);
842         FILE *out_fd = fopen(path, "w");
843         if(!out_fd) {
844                 printf("VFrame::write_png %d %s %s\n", __LINE__, path, strerror(errno));
845                 return 1;
846         }
847
848         int png_cmodel = PNG_COLOR_TYPE_RGB;
849         int bc_cmodel = get_color_model();
850         switch( bc_cmodel ) {
851         case BC_RGB888:                                          break;
852         case BC_RGBA8888: png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA; break;
853         case BC_A8:       png_cmodel = PNG_COLOR_TYPE_GRAY;      break;
854         default:
855                 bc_cmodel = BC_RGB888;
856                 if( BC_CModels::has_alpha(bc_cmodel) ) {
857                         bc_cmodel = BC_RGBA8888;
858                         png_cmodel = PNG_COLOR_TYPE_RGB_ALPHA;
859                 }
860                 vframe = new VFrame(get_w(), get_h(), bc_cmodel, 0);
861                 vframe->transfer_from(this);
862                 break;
863         }
864         png_init_io(png_ptr, out_fd);
865         png_set_compression_level(png_ptr, 9);
866         png_set_IHDR(png_ptr, info_ptr, get_w(), get_h(), 8, png_cmodel,
867                 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
868         png_write_info(png_ptr, info_ptr);
869         png_write_image(png_ptr, vframe->get_rows());
870         png_write_end(png_ptr, info_ptr);
871         png_destroy_write_struct(&png_ptr, &info_ptr);
872         fclose(out_fd);
873         if( vframe != this ) delete vframe;
874         return 0;
875 }
876
877
878 #define ZERO_YUV(components, type, max) \
879 { \
880         for(int i = 0; i < h; i++) \
881         { \
882                 type *row = (type*)get_rows()[i]; \
883                 for(int j = 0; j < w; j++) \
884                 { \
885                         row[j * components] = 0; \
886                         row[j * components + 1] = (max + 1) / 2; \
887                         row[j * components + 2] = (max + 1) / 2; \
888                         if(components == 4) row[j * components + 3] = 0; \
889                 } \
890         } \
891 }
892
893 int VFrame::clear_frame()
894 {
895         int sz = w * h;
896 //printf("VFrame::clear_frame %d\n", __LINE__);
897         switch(color_model) {
898         case BC_COMPRESSED:
899                 break;
900
901         case BC_YUV410P:
902                 bzero(get_y(), sz);
903                 memset(get_u(), 0x80, w / 4 * h / 4);
904                 memset(get_v(), 0x80, w / 4 * h / 4);
905                 break;
906
907         case BC_YUV411P:
908         case BC_YUV420P:
909         case BC_YUV420PI:
910                 bzero(get_y(), sz);
911                 memset(get_u(), 0x80, sz / 4);
912                 memset(get_v(), 0x80, sz / 4);
913                 break;
914
915         case BC_YUV422P:
916                 bzero(get_y(), sz);
917                 memset(get_u(), 0x80, sz / 2);
918                 memset(get_v(), 0x80, sz / 2);
919                 break;
920
921         case BC_GBRP:
922                 bzero(get_y(), sz);
923                 bzero(get_u(), sz);
924                 bzero(get_b(), sz);
925                 break;
926
927         case BC_RGBA_FLOATP: if( a ) {
928                 float *ap = (float *)a;
929                 for( int i=sz; --i>=0; ++ap ) *ap = 0.f; }
930         case BC_RGB_FLOATP: {
931                 float *rp = (float *)y;
932                 for( int i=sz; --i>=0; ++rp ) *rp = 0.f;
933                 float *gp = (float *)u;
934                 for( int i=sz; --i>=0; ++gp ) *gp = 0.f;
935                 float *bp = (float *)v;
936                 for( int i=sz; --i>=0; ++bp ) *bp = 0.f;
937                 break; }
938         case BC_YUV444P:
939                 bzero(get_y(), sz);
940                 memset(get_u(), 0x80, sz);
941                 memset(get_v(), 0x80, sz);
942                 break;
943
944         case BC_YUV888:
945                 ZERO_YUV(3, unsigned char, 0xff);
946                 break;
947
948         case BC_YUVA8888:
949                 ZERO_YUV(4, unsigned char, 0xff);
950                 break;
951
952         case BC_YUV161616:
953                 ZERO_YUV(3, uint16_t, 0xffff);
954                 break;
955
956         case BC_YUVA16161616:
957                 ZERO_YUV(4, uint16_t, 0xffff);
958                 break;
959
960         default:
961                 bzero(data, calculate_data_size(w, h, bytes_per_line, color_model));
962                 break;
963         }
964         return 0;
965 }
966
967 void VFrame::rotate90()
968 {
969 // Allocate new frame
970         int new_w = h, new_h = w;
971         VFrame new_frame(new_w, new_h, color_model);
972         unsigned char **new_rows = new_frame.get_rows();
973 // Copy data
974         for(int in_y = 0, out_x = new_w - 1; in_y < h; in_y++, out_x--)
975         {
976                 for(int in_x = 0, out_y = 0; in_x < w; in_x++, out_y++)
977                 {
978                         for(int k = 0; k < bytes_per_pixel; k++)
979                         {
980                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
981                                         rows[in_y][in_x * bytes_per_pixel + k];
982                         }
983                 }
984         }
985
986 // Swap frames
987 // swap memory
988         unsigned char *new_data = new_frame.data;
989         new_frame.data = data;
990         data = new_data;
991 // swap rows
992         new_rows = new_frame.rows;
993         new_frame.rows = rows;
994         rows = new_rows;
995 // swap shmid
996         int new_shmid = new_frame.shmid;
997         new_frame.shmid = shmid;
998         shmid = new_shmid;
999 // swap bytes_per_line
1000         int new_bpl = new_frame.bytes_per_line;
1001         new_frame.bytes_per_line = bytes_per_line;
1002         bytes_per_line = new_bpl;
1003         new_frame.clear_objects(0);
1004
1005         w = new_frame.w;
1006         h = new_frame.h;
1007 }
1008
1009 void VFrame::rotate270()
1010 {
1011 // Allocate new frame
1012         int new_w = h, new_h = w;
1013         VFrame new_frame(new_w, new_h, color_model);
1014         unsigned char **new_rows = new_frame.get_rows();
1015 // Copy data
1016         for(int in_y = 0, out_x = 0; in_y < h; in_y++, out_x++)
1017         {
1018                 for(int in_x = 0, out_y = new_h - 1; in_x < w; in_x++, out_y--)
1019                 {
1020                         for(int k = 0; k < bytes_per_pixel; k++)
1021                         {
1022                                 new_rows[out_y][out_x * bytes_per_pixel + k] =
1023                                         rows[in_y][in_x * bytes_per_pixel + k];
1024                         }
1025                 }
1026         }
1027
1028 // Swap frames
1029 // swap memory
1030         unsigned char *new_data = new_frame.data;
1031         new_frame.data = data;
1032         data = new_data;
1033 // swap rows
1034         new_rows = new_frame.rows;
1035         new_frame.rows = rows;
1036         rows = new_rows;
1037 // swap shmid
1038         int new_shmid = new_frame.shmid;
1039         new_frame.shmid = shmid;
1040         shmid = new_shmid;
1041 // swap bytes_per_line
1042         int new_bpl = new_frame.bytes_per_line;
1043         new_frame.bytes_per_line = bytes_per_line;
1044         bytes_per_line = new_bpl;
1045         new_frame.clear_objects(0);
1046
1047         w = new_frame.w;
1048         h = new_frame.h;
1049 }
1050
1051 void VFrame::flip_vert()
1052 {
1053         unsigned char temp[bytes_per_line];
1054         for( int i=0, j=h; --j>i; ++i ) {
1055                 memcpy(temp, rows[j], bytes_per_line);
1056                 memcpy(rows[j], rows[i], bytes_per_line);
1057                 memcpy(rows[i], temp, bytes_per_line);
1058         }
1059 }
1060
1061 void VFrame::flip_horiz()
1062 {
1063         unsigned char temp[32];
1064         for(int i = 0; i < h; i++)
1065         {
1066                 unsigned char *row = rows[i];
1067                 for(int j = 0; j < bytes_per_line / 2; j += bytes_per_pixel)
1068                 {
1069                         memcpy(temp, row + j, bytes_per_pixel);
1070                         memcpy(row + j, row + bytes_per_line - j - bytes_per_pixel, bytes_per_pixel);
1071                         memcpy(row + bytes_per_line - j - bytes_per_pixel, temp, bytes_per_pixel);
1072                 }
1073         }
1074 }
1075
1076
1077
1078 int VFrame::copy_from(VFrame *frame)
1079 {
1080         if(this->w != frame->get_w() ||
1081                 this->h != frame->get_h())
1082         {
1083                 printf("VFrame::copy_from %d sizes differ src %dx%d != dst %dx%d\n",
1084                         __LINE__,
1085                         frame->get_w(),
1086                         frame->get_h(),
1087                         get_w(),
1088                         get_h());
1089                 return 1;
1090         }
1091
1092         int w = MIN(this->w, frame->get_w());
1093         int h = MIN(this->h, frame->get_h());
1094         timestamp = frame->timestamp;
1095
1096         switch(frame->color_model)
1097         {
1098                 case BC_COMPRESSED:
1099                         allocate_compressed_data(frame->compressed_size);
1100                         memcpy(data, frame->data, frame->compressed_size);
1101                         this->compressed_size = frame->compressed_size;
1102                         break;
1103
1104                 case BC_YUV410P:
1105                         memcpy(get_y(), frame->get_y(), w * h);
1106                         memcpy(get_u(), frame->get_u(), w / 4 * h / 4);
1107                         memcpy(get_v(), frame->get_v(), w / 4 * h / 4);
1108                         break;
1109
1110                 case BC_YUV420P:
1111                 case BC_YUV420PI:
1112                 case BC_YUV411P:
1113 //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());
1114                         memcpy(get_y(), frame->get_y(), w * h);
1115                         memcpy(get_u(), frame->get_u(), w * h / 4);
1116                         memcpy(get_v(), frame->get_v(), w * h / 4);
1117                         break;
1118
1119                 case BC_YUV422P:
1120 //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());
1121                         memcpy(get_y(), frame->get_y(), w * h);
1122                         memcpy(get_u(), frame->get_u(), w * h / 2);
1123                         memcpy(get_v(), frame->get_v(), w * h / 2);
1124                         break;
1125
1126                 case BC_YUV444P:
1127 //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());
1128                         memcpy(get_y(), frame->get_y(), w * h);
1129                         memcpy(get_u(), frame->get_u(), w * h);
1130                         memcpy(get_v(), frame->get_v(), w * h);
1131                         break;
1132                 default:
1133 // printf("VFrame::copy_from %d\n", calculate_data_size(w,
1134 //                              h,
1135 //                              -1,
1136 //                              frame->color_model));
1137 // Copy without extra 4 bytes in case the source is a hardware device
1138                         memmove(data, frame->data, get_data_size());
1139                         break;
1140         }
1141
1142         return 0;
1143 }
1144
1145 int VFrame::transfer_from(VFrame *that, int bg_color, int in_x, int in_y, int in_w, int in_h)
1146 {
1147         timestamp = that->timestamp;
1148         copy_params(that);
1149
1150         if( this->get_color_model() == that->get_color_model() &&
1151             this->get_w() == that->get_w() && this->get_h() == that->get_h() &&
1152             this->get_bytes_per_line() == that->get_bytes_per_line() )
1153                 return this->copy_from(that);
1154
1155 #if 0
1156         BC_CModels::transfer(
1157                 this->get_rows(), that->get_rows(),          // Packed data out/in
1158                 this->get_y(), this->get_u(), this->get_v(), // Planar data out/in
1159                 that->get_y(), that->get_u(), that->get_v(),
1160                 0, 0, that->get_w(), that->get_h(),          // Dimensions in/out
1161                 0, 0, this->get_w(), this->get_h(),
1162                 that->get_color_model(), this->get_color_model(), // Color models in/out
1163                 bg_color,                                    // alpha blend bg_color
1164                 that->get_bytes_per_line(),
1165                 this->get_bytes_per_line());                 // rowspans (of luma for YUV)
1166 #else
1167         unsigned char *in_ptrs[4], *out_ptrs[4];
1168         unsigned char **inp, **outp;
1169         if( BC_CModels::is_planar(that->get_color_model()) ) {
1170                 in_ptrs[0] = that->get_y();
1171                 in_ptrs[1] = that->get_u();
1172                 in_ptrs[2] = that->get_v();
1173                 in_ptrs[3] = that->get_a();
1174                 inp = in_ptrs;
1175         }
1176         else
1177                 inp = that->get_rows();
1178         if( BC_CModels::is_planar(this->get_color_model()) ) {
1179                 out_ptrs[0] = this->get_y();
1180                 out_ptrs[1] = this->get_u();
1181                 out_ptrs[2] = this->get_v();
1182                 out_ptrs[3] = this->get_a();
1183                 outp = out_ptrs;
1184         }
1185         else
1186                 outp = this->get_rows();
1187         BC_CModels::transfer(outp, this->get_color_model(),
1188                         0, 0, this->get_w(), this->get_h(),
1189                         this->get_bytes_per_line(),
1190                 inp, that->get_color_model(),
1191                         in_x, in_y, in_w, in_h,
1192                         that->get_bytes_per_line(),
1193                 bg_color);
1194 #endif
1195         return 0;
1196 }
1197
1198
1199 int VFrame::get_scale_tables(int *column_table, int *row_table,
1200                         int in_x1, int in_y1, int in_x2, int in_y2,
1201                         int out_x1, int out_y1, int out_x2, int out_y2)
1202 {
1203         int i;
1204         float w_in = in_x2 - in_x1;
1205         float h_in = in_y2 - in_y1;
1206         int w_out = out_x2 - out_x1;
1207         int h_out = out_y2 - out_y1;
1208
1209         float hscale = w_in / w_out;
1210         float vscale = h_in / h_out;
1211
1212         for(i = 0; i < w_out; i++)
1213         {
1214                 column_table[i] = (int)(hscale * i);
1215         }
1216
1217         for(i = 0; i < h_out; i++)
1218         {
1219                 row_table[i] = (int)(vscale * i) + in_y1;
1220         }
1221         return 0;
1222 }
1223
1224 void VFrame::push_prev_effect(const char *name)
1225 {
1226         char *ptr;
1227         prev_effects.append(ptr = new char[strlen(name) + 1]);
1228         strcpy(ptr, name);
1229         if(prev_effects.total > MAX_STACK_ELEMENTS) prev_effects.remove_object(0);
1230 }
1231
1232 void VFrame::pop_prev_effect()
1233 {
1234         if(prev_effects.total)
1235                 prev_effects.remove_object(prev_effects.last());
1236 }
1237
1238 void VFrame::push_next_effect(const char *name)
1239 {
1240         char *ptr;
1241         next_effects.append(ptr = new char[strlen(name) + 1]);
1242         strcpy(ptr, name);
1243         if(next_effects.total > MAX_STACK_ELEMENTS) next_effects.remove_object(0);
1244 }
1245
1246 void VFrame::pop_next_effect()
1247 {
1248         if(next_effects.total)
1249                 next_effects.remove_object(next_effects.last());
1250 }
1251
1252 const char* VFrame::get_next_effect(int number)
1253 {
1254         if(!next_effects.total) return "";
1255         else
1256         if(number > next_effects.total - 1) number = next_effects.total - 1;
1257
1258         return next_effects.values[next_effects.total - number - 1];
1259 }
1260
1261 const char* VFrame::get_prev_effect(int number)
1262 {
1263         if(!prev_effects.total) return "";
1264         else
1265         if(number > prev_effects.total - 1) number = prev_effects.total - 1;
1266
1267         return prev_effects.values[prev_effects.total - number - 1];
1268 }
1269
1270 BC_Hash* VFrame::get_params()
1271 {
1272         return params;
1273 }
1274
1275 void VFrame::clear_stacks()
1276 {
1277         next_effects.remove_all_objects();
1278         prev_effects.remove_all_objects();
1279         params->clear();
1280         status = 1;
1281 }
1282
1283 void VFrame::copy_params(VFrame *src)
1284 {
1285         status = src->status;
1286         params->copy_from(src->params);
1287 }
1288
1289 void VFrame::copy_stacks(VFrame *src)
1290 {
1291         clear_stacks();
1292
1293         for( int i=0; i < src->next_effects.total; ++i )
1294                 next_effects.append(cstrdup(src->next_effects[i]));
1295         for( int i=0; i < src->prev_effects.total; ++i )
1296                 prev_effects.append(cstrdup(src->prev_effects[i]));
1297
1298         copy_params(src);
1299 }
1300
1301 int VFrame::copy_vframe(VFrame *frame)
1302 {
1303         copy_stacks(frame);
1304         return copy_from(frame);
1305 }
1306
1307 int VFrame::equal_stacks(VFrame *src)
1308 {
1309         for(int i = 0; i < src->next_effects.total && i < next_effects.total; i++)
1310         {
1311                 if(strcmp(src->next_effects.values[i], next_effects.values[i])) return 0;
1312         }
1313
1314         for(int i = 0; i < src->prev_effects.total && i < prev_effects.total; i++)
1315         {
1316                 if(strcmp(src->prev_effects.values[i], prev_effects.values[i])) return 0;
1317         }
1318
1319         if(!params->equivalent(src->params)) return 0;
1320         return 1;
1321 }
1322
1323 void VFrame::dump_stacks()
1324 {
1325         printf("VFrame::dump_stacks\n");
1326         printf("        next_effects:\n");
1327         for(int i = next_effects.total - 1; i >= 0; i--)
1328                 printf("                %s\n", next_effects.values[i]);
1329         printf("        prev_effects:\n");
1330         for(int i = prev_effects.total - 1; i >= 0; i--)
1331                 printf("                %s\n", prev_effects.values[i]);
1332 }
1333
1334 void VFrame::dump_params()
1335 {
1336         params->dump();
1337 }
1338
1339 void VFrame::dump()
1340 {
1341         printf("VFrame::dump %d this=%p\n", __LINE__, this);
1342         printf("    w=%d h=%d colormodel=%d rows=%p use_shm=%d shmid=%d\n",
1343                 w, h, color_model, rows, use_shm, shmid);
1344 }
1345
1346
1347 int VFrame::get_memory_usage()
1348 {
1349         if(get_compressed_allocated()) return get_compressed_allocated();
1350         return get_h() * get_bytes_per_line();
1351 }
1352
1353 // rgb component colors (eg. from colors.h)
1354 // a (~alpha) transparency, 0x00==solid .. 0xff==transparent
1355 void VFrame::set_pixel_color(int argb)
1356 {
1357         pixel_rgb = argb;
1358         int ia = 0xff & (pixel_rgb >> 24);
1359         int ir = 0xff & (pixel_rgb >> 16);
1360         int ig = 0xff & (pixel_rgb >> 8);
1361         int ib = 0xff & (pixel_rgb >> 0);
1362         YUV::yuv.rgb_to_yuv_8(ir, ig, ib);
1363         pixel_yuv =  (ia<<24) | (ir<<16) | (ig<<8) | (ib<<0);
1364 }
1365
1366 void VFrame::set_stiple(int mask)
1367 {
1368         stipple = mask;
1369 }
1370
1371 int VFrame::draw_pixel(int x, int y)
1372 {
1373         if( x < 0 || y < 0 || x >= get_w() || y >= get_h() ) return 1;
1374
1375 #define DRAW_PIXEL(type, r, g, b, comps, a) { \
1376         type **rows = (type**)get_rows(); \
1377         type *rp = rows[y], *bp = rp + x*comps; \
1378         bp[0] = r; \
1379         if( comps > 1 ) { bp[1] = g; bp[2] = b; } \
1380         if( comps == 4 )  bp[3] = a; \
1381 }
1382         float fr = 0, fg = 0, fb = 0, fa = 0;
1383         int pixel_color = BC_CModels::is_yuv(color_model) ? pixel_yuv : pixel_rgb;
1384         int ir = (0xff & (pixel_color >> 16));
1385         int ig = (0xff & (pixel_color >> 8));
1386         int ib = (0xff & (pixel_color >> 0));
1387         int ia = (0xff & (pixel_color >> 24)) ^ 0xff;  // transparency, not opacity
1388         if( (x+y) & stipple ) {
1389                 ir = 255 - ir;  ig = 255 - ig;  ib = 255 - ib;
1390         }
1391         int rr = (ir<<8) | ir, gg = (ig<<8) | ig, bb = (ib<<8) | ib, aa = (ia<<8) | ia;
1392         if( BC_CModels::is_float(color_model) ) {
1393                 fr = rr/65535.f;  fg = gg/65535.f;  fb = bb/65535.f;  fa = aa/65535.f;
1394         }
1395
1396         switch(get_color_model()) {
1397         case BC_A8:
1398                 DRAW_PIXEL(uint8_t, ib, 0, 0, 1, 0);
1399                 break;
1400         case BC_YUV888:
1401                 DRAW_PIXEL(uint8_t, ir, ig, ib, 3, 0);
1402                 break;
1403         case BC_RGBA8888:
1404         case BC_YUVA8888:
1405                 DRAW_PIXEL(uint8_t, ir, ig, ib, 4, ia);
1406                 break;
1407         case BC_RGB161616:
1408         case BC_YUV161616:
1409                 DRAW_PIXEL(uint16_t, rr, gg, bb, 3, 0);
1410                 break;
1411         case BC_RGBA16161616:
1412         case BC_YUVA16161616:
1413                 DRAW_PIXEL(uint16_t, rr, gg, bb, 4, aa);
1414                 break;
1415         case BC_RGB_FLOAT:
1416                 DRAW_PIXEL(float, fr, fg, fb, 3, 0);
1417                 break;
1418         case BC_RGBA_FLOAT:
1419                 DRAW_PIXEL(float, fr, fg, fb, 4, fa);
1420                 break;
1421         }
1422         return 0;
1423 }
1424
1425
1426 // Bresenham's
1427 void VFrame::draw_line(int x1, int y1, int x2, int y2)
1428 {
1429         if( y1 > y2 ) {
1430                 int tx = x1;  x1 = x2;  x2 = tx;
1431                 int ty = y1;  y1 = y2;  y2 = ty;
1432         }
1433
1434         int x = x1, y = y1;
1435         int dx = x2-x1, dy = y2-y1;
1436         int dx2 = 2*dx, dy2 = 2*dy;
1437         if( dx < 0 ) dx = -dx;
1438         int r = dx > dy ? dx : dy, n = r;
1439         int dir = 0;
1440         if( dx2 < 0 ) dir += 1;
1441         if( dy >= dx ) {
1442                 if( dx2 >= 0 ) do {     /* +Y, +X */
1443                         draw_pixel(x, y++);
1444                         if( (r -= dx2) < 0 ) { r += dy2;  ++x; }
1445                 } while( --n >= 0 );
1446                 else do {               /* +Y, -X */
1447                         draw_pixel(x, y++);
1448                         if( (r += dx2) < 0 ) { r += dy2;  --x; }
1449                 } while( --n >= 0 );
1450         }
1451         else {
1452                 if( dx2 >= 0 ) do {     /* +X, +Y */
1453                         draw_pixel(x++, y);
1454                         if( (r -= dy2) < 0 ) { r += dx2;  ++y; }
1455                 } while( --n >= 0 );
1456                 else do {               /* -X, +Y */
1457                         draw_pixel(x--, y);
1458                         if( (r -= dy2) < 0 ) { r -= dx2;  ++y; }
1459                 } while( --n >= 0 );
1460         }
1461 }
1462
1463 // g++ -dD -E - < /dev/null | grep DBL_EPSILON
1464 #ifndef __DBL_EPSILON__
1465 #define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
1466 #endif
1467 // weakest fraction * graphics integer range
1468 #define RND_EPSILON (__DBL_EPSILON__*65536)
1469
1470 class smooth_line {
1471         int rnd(double v) { return round(v)+RND_EPSILON; }
1472         VFrame *vframe;
1473 public:
1474         int sx, sy, ex, ey;     /* current point, end point */
1475         int xs, ys;             /* x/y quadrant sign -1/1 */
1476         int64_t A, B, C;        /* quadratic coefficients */
1477         int64_t r, dx, dy;      /* residual, dr/dx and dr/dy */
1478         int xmxx, xmxy;         /* x,y at apex */
1479         int done;
1480
1481         void init0(int x1,int y1, int x2,int y2, int x3,int y3, int top);
1482         void init1(int x1,int y1, int x2,int y2, int x3,int y3);
1483         int64_t rx() { return r + xs*8*dx + 4*A; }
1484         void moveX(int64_t r) {
1485                 dx += xs*A;   dy -= xs*B;
1486                 this->r = r;  sx += xs;
1487         }
1488         int64_t ry() { return r + 8*dy + 4*C; }
1489         void moveY(int64_t r) {
1490                 dx -= B;      dy += C;
1491                 this->r = r;  ++sy;
1492         }
1493         void draw();
1494
1495         smooth_line(VFrame *vframe) { this->vframe = vframe; this->done = 0; }
1496 };
1497
1498
1499 void smooth_line::draw()
1500 {
1501         if( done ) return;
1502         if( abs(dy) >= abs(dx) ) {
1503                 if( xs*(sx-xmxx) >= 0 ) {
1504                         if( ys > 0 ) { done = 1;  return; }
1505                         if( dy < 0 || ry() < 0 ) { moveY(ry()); goto xit; }
1506                         xmxx = ex;  xmxy = ey;
1507                         ys = 1;  xs = -xs;
1508                 }
1509                 moveX(rx());
1510                 int64_t rr = ry();
1511                 if( abs(rr) < abs(r) )
1512                         moveY(rr);
1513         }
1514         else {
1515                 if( sy >= xmxy ) {
1516                         if( ys > 0 ) { done = 1;  return; }
1517                         xmxx = ex;  xmxy = ey;
1518                         ys = 1;  xs = -xs;
1519                 }
1520                 moveY(ry());
1521                 int64_t rr = rx();
1522                 if( abs(rr) < abs(r) )
1523                         moveX(rr);
1524         }
1525 xit:    vframe->draw_pixel(sx, sy);
1526 }
1527
1528 void VFrame::draw_smooth(int x1, int y1, int x2, int y2, int x3, int y3)
1529 {
1530         if( (x1 == x2 && y1 == y2) || (x2 == x3 && y2 == y3) )
1531                 draw_line(x1,y1, x3,y3);
1532         else if( x1 == x3 && y1 == y3 )
1533                 draw_line(x1,y1, x2,y2);
1534         else if( (x2-x1) * (y2-y3) == (x2-x3) * (y2-y1) ) {
1535                 // co-linear, draw line from min to max
1536                 if( x1 < x3 ) {
1537                         if( x2 < x1 ) { x1 = x2;  y1 = y2; }
1538                         if( x2 > x3 ) { x3 = x2;  y3 = y2; }
1539                 }
1540                 else {
1541                         if( x2 > x1 ) { x1 = x2;  y1 = y2; }
1542                         if( x2 < x3 ) { x3 = x2;  y3 = y2; }
1543                 }
1544                 draw_line(x1,y1, x3,y3);
1545         }
1546         else
1547                 smooth_draw(x1, y1, x2, y2, x3, y3);
1548 }
1549
1550 /*
1551   Non-Parametric Smooth Curve Generation. Don Kelly 1984
1552
1553      P+-----+Q'= virtual
1554      /     /       origin
1555     /     /
1556   Q+-----+R
1557
1558    Let the starting point be P. the ending point R. and the tangent vertex Q.
1559    A general point Z on the curve is then
1560         Z = (P + R - Q) + (Q - P) sin t + (Q - R) cos t
1561
1562    Expanding the Cartesian coordinates around (P + R - Q) gives
1563         [x y] = Z - (P + R - Q)
1564         [a c] = Q - P
1565         [b d] = Q - R
1566         x = a*sin(t) + b*cos(t)
1567         y = c*sin(t) + d*cos(t)
1568
1569    from which t can now be eliminated via
1570         c*x - a*y = (c*b - a*d)*cos(t)
1571         d*x - b*y = (a*d - c*b)*sin(t)
1572
1573    giving the Cartesian equation for the ellipse as
1574         f(x, y) = (c*x - a*y)**2 + (d*x - b*y)**2 - (a*d - c*b)**2 = 0
1575
1576    or:  f(x, y) = A*x**2 - 2*B*x*y + C*y**2 + B**2 - A*C = 0
1577    where: A = c**2 + d**2,  B = a*c + b*d,  C = a**2 + b**2
1578
1579    The maximum y extent of the ellipse may now be derived as follows:
1580         let df/dx = 0,  2*A*x = 2*B*y,  x = y*B/A
1581         f(x, y) == B**2 * y**2 / A - 2*B**2 * y**2 / A + C*y**2 + B**2 - A*C = 0
1582            (A*C - B**2)*y = (A*C - B**2)*A
1583            max x = sqrt(C), at y = B/sqrt(C)
1584            max y = sqrt(A), at x = B/sqrt(A)
1585
1586  */
1587
1588
1589 /* x1,y1 = P, x2,y2 = Q, x3,y3=R,
1590  *  draw from P to Q to R   if top=0
1591  *    or from P to (x,ymax) if top>0
1592  *    or from Q to (x,ymax) if top<0
1593  */
1594 void smooth_line::init0(int x1,int y1, int x2,int y2, int x3,int y3, int top)
1595 {
1596         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1597
1598         int a = x2-x1,  c = y2-y1;
1599         int b = x2-x3,  d = y2-y3;
1600         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1601
1602         sx = top >= 0 ? x1 : x3;
1603         sy = top >= 0 ? y1 : y3;
1604         xs = x2 > sx || (x2==sx && (x1+x3-sx)>=x2) ? 1 : -1;
1605         int64_t px = sx-x0, py = sy-y0;
1606         dx = A*px - B*py;  dy = C*py - B*px;
1607         r = 0;
1608
1609         if( top ) {
1610                 double ymy = sqrt(A), ymx = B/ymy;
1611                 ex = x0 + rnd(ymx);
1612                 ey = y0 + rnd(ymy);
1613         }
1614         else {
1615                 ex = x3;  ey = y3;
1616         }
1617
1618         ys = a*b > 0 && (!top || top*xs*(b*c - a*d) > 0) ? -1 : 1;
1619         if( ys < 0 ) {
1620                 double xmx = xs*sqrt(C), xmy = B/xmx;
1621                 xmxx = x0 + rnd(xmx);
1622                 xmxy = y0 + rnd(xmy);
1623         }
1624         else {
1625                 xmxx = ex; xmxy = ey;
1626         }
1627 }
1628
1629 /*  x1,y1 = P, x2,y2 = Q, x3,y3=R,
1630  *  draw from (x,ymax) to P
1631  */
1632 void smooth_line::init1(int x1,int y1, int x2,int y2, int x3,int y3)
1633 {
1634         int x0 = x1+x3-x2, y0 = y1+y3-y2; // Q'
1635
1636         int a = x2-x1,  c = y2-y1;
1637         int b = x2-x3,  d = y2-y3;
1638         A = c*c + d*d;  C = a*a + b*b;  B = a*c + b*d;
1639
1640         double ymy = -sqrt(A), ymx = B/ymy;
1641         int64_t px = rnd(ymx), py = rnd(ymy);
1642         sx = x0 + px;  ex = x1;
1643         sy = y0 + py;  ey = y1;
1644         xs = x2 > x1 || (x2==x1 && x3>=x2) ? 1 : -1;
1645         dx = A*px - B*py;  dy = C*py - B*px;
1646         r = 4 * (A*px*px - 2*B*px*py + C*py*py + B*B - A*C);
1647
1648         ys = a*b > 0 && xs*(b*c - a*d) < 0 ? -1 : 1;
1649         if( ys < 0 ) {
1650                 double xmx = xs*sqrt(C), xmy = B/xmx;
1651                 xmxx = x0 + rnd(xmx);
1652                 xmxy = y0 + rnd(xmy);
1653         }
1654         else {
1655                 xs = -xs;
1656                 xmxx = ex; xmxy = ey;
1657         }
1658         if( xs > 0 )
1659                 vframe->draw_pixel(sx, sy);
1660         while( xs*(sx-xmxx) < 0 && (xs*dx < 0 || rx() < 0) ) {
1661                 moveX(rx());
1662                 vframe->draw_pixel(sx, sy);
1663         }
1664 }
1665
1666
1667 void VFrame::smooth_draw(int x1, int y1, int x2, int y2, int x3, int y3)
1668 {
1669 //printf("p smooth_draw( %d,%d, %d,%d, %d,%d )\n", x1,y1,x2,y2,x3,y3);
1670         if( y1 > y3 ) {         // make y3 >= y1
1671                 int xt = x1;  x1 = x3;  x3 = xt;
1672                 int yt = y1;  y1 = y3;  y3 = yt;
1673         }
1674         if( y1 > y2 && y3 > y2 ) {
1675                 smooth_line lt(this), rt(this); // Q on bottom
1676                 lt.init1(x1, y1, x2, y2, x3, y3);
1677                 rt.init1(x3, y3, x2, y2, x1, y1);
1678                 while( !lt.done || !rt.done ) {
1679                         lt.draw();
1680                         rt.draw();
1681                 }
1682         }
1683         else if( y1 < y2 && y3 < y2 ) {
1684                 smooth_line lt(this), rt(this); // Q on top
1685                 lt.init0(x1, y1, x2, y2, x3, y3, 1);
1686                 draw_pixel(lt.sx, lt.sy);
1687                 rt.init0(x1, y1, x2, y2, x3, y3, -1);
1688                 draw_pixel(rt.sx, rt.sy);
1689                 while( !lt.done || !rt.done ) {
1690                         lt.draw();
1691                         rt.draw();
1692                 }
1693         }
1694         else {
1695                 smooth_line pt(this);           // Q in between
1696                 pt.init0(x1, y1, x2, y2, x3, y3, 0);
1697                 draw_pixel(pt.sx, pt.sy);
1698                 while( !pt.done ) {
1699                         pt.draw();
1700                 }
1701         }
1702 }
1703
1704
1705 void VFrame::draw_rect(int x1, int y1, int x2, int y2)
1706 {
1707         draw_line(x1, y1, x2, y1);
1708         draw_line(x2, y1 + 1, x2, y2);
1709         draw_line(x2 - 1, y2, x1, y2);
1710         draw_line(x1, y2 - 1, x1, y1 + 1);
1711 }
1712
1713
1714 void VFrame::draw_oval(int x1, int y1, int x2, int y2)
1715 {
1716         int w = x2 - x1;
1717         int h = y2 - y1;
1718         int center_x = (x2 + x1) / 2;
1719         int center_y = (y2 + y1) / 2;
1720         int x_table[h / 2];
1721
1722 //printf("VFrame::draw_oval %d %d %d %d %d\n", __LINE__, x1, y1, x2, y2);
1723
1724         for(int i = 0; i < h / 2; i++) {
1725 // A^2 = -(B^2) + C^2
1726                 x_table[i] = (int)(sqrt(-SQR(h / 2 - i) + SQR(h / 2)) * w / h);
1727 //printf("VFrame::draw_oval %d i=%d x=%d\n", __LINE__, i, x_table[i]);
1728         }
1729
1730         for(int i = 0; i < h / 2 - 1; i++) {
1731                 int x3 = x_table[i];
1732                 int x4 = x_table[i + 1];
1733
1734                 if(x4 > x3 + 1) {
1735                         for(int j = x3; j < x4; j++) {
1736                                 draw_pixel(center_x + j, y1 + i);
1737                                 draw_pixel(center_x - j, y1 + i);
1738                                 draw_pixel(center_x + j, y2 - i - 1);
1739                                 draw_pixel(center_x - j, y2 - i - 1);
1740                         }
1741                 }
1742                 else {
1743                         draw_pixel(center_x + x3, y1 + i);
1744                         draw_pixel(center_x - x3, y1 + i);
1745                         draw_pixel(center_x + x3, y2 - i - 1);
1746                         draw_pixel(center_x - x3, y2 - i - 1);
1747                 }
1748         }
1749         
1750         draw_pixel(center_x, y1);
1751         draw_pixel(center_x, y2 - 1);
1752         draw_pixel(x1, center_y);
1753         draw_pixel(x2 - 1, center_y);
1754         draw_pixel(x1, center_y - 1);
1755         draw_pixel(x2 - 1, center_y - 1);
1756 }
1757
1758
1759 void VFrame::draw_arrow(int x1, int y1, int x2, int y2, int sz)
1760 {
1761         double angle = atan((float)(y2 - y1) / (float)(x2 - x1));
1762         double angle1 = angle + (float)145 / 360 * 2 * M_PI;
1763         double angle2 = angle - (float)145 / 360 * 2 * M_PI;
1764         int s = x2 < x1 ? -1 : 1;
1765         int x3 = x2 + s * (int)(sz * cos(angle1));
1766         int y3 = y2 + s * (int)(sz * sin(angle1));
1767         int x4 = x2 + s * (int)(sz * cos(angle2));
1768         int y4 = y2 + s * (int)(sz * sin(angle2));
1769
1770 // Main vector
1771         draw_line(x1, y1, x2, y2);
1772 //      draw_line(x1, y1 + 1, x2, y2 + 1);
1773
1774 // Arrow line
1775         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x3, y3);
1776 // Arrow line
1777         if(abs(y2 - y1) || abs(x2 - x1)) draw_line(x2, y2, x4, y4);
1778 }
1779
1780 void VFrame::draw_x(int x, int y, int sz)
1781 {
1782         draw_line(x-sz,y-sz, x+sz,y+sz);
1783         draw_line(x+sz,y-sz, x-sz,y+sz);
1784 }
1785 void VFrame::draw_t(int x, int y, int sz)
1786 {
1787         draw_line(x,y-sz, x,y+sz);
1788         draw_line(x+sz,y, x-sz,y);
1789 }
1790
1791