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