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