aboutsummaryrefslogtreecommitdiff
path: root/webrtc/modules/video_render/mac/video_render_agl.cc
blob: 3243563b2bf901e1e268637273247fa0e72ba3f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/engine_configurations.h"

#if defined(CARBON_RENDERING)

#include "webrtc/modules/video_render/mac/video_render_agl.h"

//  includes
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
#include "webrtc/system_wrappers/include/event_wrapper.h"
#include "webrtc/system_wrappers/include/trace.h"

namespace webrtc {

/*
 *
 *    VideoChannelAGL
 *
 */

#pragma mark VideoChannelAGL constructor

VideoChannelAGL::VideoChannelAGL(AGLContext& aglContext, int iId, VideoRenderAGL* owner) :
    _aglContext( aglContext),
    _id( iId),
    _owner( owner),
    _width( 0),
    _height( 0),
    _stretchedWidth( 0),
    _stretchedHeight( 0),
    _startWidth( 0.0f),
    _startHeight( 0.0f),
    _stopWidth( 0.0f),
    _stopHeight( 0.0f),
    _xOldWidth( 0),
    _yOldHeight( 0),
    _oldStretchedHeight(0),
    _oldStretchedWidth( 0),
    _buffer( 0),
    _bufferSize( 0),
    _incomingBufferSize(0),
    _bufferIsUpdated( false),
    _sizeInitialized( false),
    _numberOfStreams( 0),
    _bVideoSizeStartedChanging(false),
    _pixelFormat( GL_RGBA),
    _pixelDataType( GL_UNSIGNED_INT_8_8_8_8),
    _texture( 0)

{
    //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s:%d Constructor", __FUNCTION__, __LINE__);
}

VideoChannelAGL::~VideoChannelAGL()
{
    //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s:%d Destructor", __FUNCTION__, __LINE__);
    if (_buffer)
    {
        delete [] _buffer;
        _buffer = NULL;
    }

    aglSetCurrentContext(_aglContext);

    if (_texture != 0)
    {
        glDeleteTextures(1, (const GLuint*) &_texture);
        _texture = 0;
    }
}

int32_t VideoChannelAGL::RenderFrame(const uint32_t streamId,
                                     VideoFrame& videoFrame) {
  _owner->LockAGLCntx();
  if (_width != videoFrame.width() ||
      _height != videoFrame.height()) {
    if (FrameSizeChange(videoFrame.width(), videoFrame.height(), 1) == -1) {
      WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, _id, "%s:%d FrameSize
                   Change returned an error", __FUNCTION__, __LINE__);
      _owner->UnlockAGLCntx();
      return -1;
    }
  }

  _owner->UnlockAGLCntx();
  return DeliverFrame(videoFrame);
}

int VideoChannelAGL::UpdateSize(int /*width*/, int /*height*/)
{
    _owner->LockAGLCntx();
    _owner->UnlockAGLCntx();
    return 0;
}

int VideoChannelAGL::UpdateStretchSize(int stretchHeight, int stretchWidth)
{

    _owner->LockAGLCntx();
    _stretchedHeight = stretchHeight;
    _stretchedWidth = stretchWidth;
    _owner->UnlockAGLCntx();
    return 0;
}

int VideoChannelAGL::FrameSizeChange(int width, int height, int numberOfStreams)
{
    //  We'll get a new frame size from VideoAPI, prepare the buffer

    _owner->LockAGLCntx();

    if (width == _width && _height == height)
    {
        // We already have a correct buffer size
        _numberOfStreams = numberOfStreams;
        _owner->UnlockAGLCntx();
        return 0;
    }

    _width = width;
    _height = height;

    // Delete the old buffer, create a new one with correct size.
    if (_buffer)
    {
        delete [] _buffer;
        _bufferSize = 0;
    }

    _incomingBufferSize = CalcBufferSize(kI420, _width, _height);
    _bufferSize = CalcBufferSize(kARGB, _width, _height);//_width * _height * bytesPerPixel;
    _buffer = new unsigned char [_bufferSize];
    memset(_buffer, 0, _bufferSize * sizeof(unsigned char));

    if (aglSetCurrentContext(_aglContext) == false)
    {
        _owner->UnlockAGLCntx();
        return -1;
    }

    // Delete a possible old texture
    if (_texture != 0)
    {
        glDeleteTextures(1, (const GLuint*) &_texture);
        _texture = 0;
    }

    // Create a new texture
    glGenTextures(1, (GLuint *) &_texture);

    GLenum glErr = glGetError();

    if (glErr != GL_NO_ERROR)
    {
    }

    // Do the setup for both textures
    // Note: we setup two textures even if we're not running full screen
    glBindTexture(GL_TEXTURE_RECTANGLE_EXT, _texture);

    // Set texture parameters
    glTexParameterf(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_PRIORITY, 1.0);

    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    //glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    //glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_STORAGE_HINT_APPLE, GL_STORAGE_SHARED_APPLE);

    // Maximum width/height for a texture
    GLint texSize;
    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize);

    if (texSize < _width || texSize < _height)
    {
        // Image too big for memory
        _owner->UnlockAGLCntx();
        return -1;
    }

    // Set up th texture type and size
    glTexImage2D(GL_TEXTURE_RECTANGLE_EXT, // target
            0, // level
            GL_RGBA, // internal format
            _width, // width
            _height, // height
            0, // border 0/1 = off/on
            _pixelFormat, // format, GL_BGRA
            _pixelDataType, // data type, GL_UNSIGNED_INT_8_8_8_8
            _buffer); // pixel data

    glErr = glGetError();
    if (glErr != GL_NO_ERROR)
    {
        _owner->UnlockAGLCntx();
        return -1;
    }

    _owner->UnlockAGLCntx();
    return 0;
}

// Called from video engine when a new frame should be rendered.
int VideoChannelAGL::DeliverFrame(const VideoFrame& videoFrame) {
  _owner->LockAGLCntx();

  if (_texture == 0) {
    _owner->UnlockAGLCntx();
    return 0;
  }

  if (CalcBufferSize(kI420, videoFrame.width(), videoFrame.height()) !=
      _incomingBufferSize) {
    _owner->UnlockAGLCntx();
    return -1;
  }

  // Setting stride = width.
  int rgbret = ConvertFromYV12(videoFrame, kBGRA, 0, _buffer);
  if (rgbret < 0) {
    _owner->UnlockAGLCntx();
    return -1;
  }

  aglSetCurrentContext(_aglContext);

  // Put the new frame into the graphic card texture.
  // Make sure this texture is the active one
  glBindTexture(GL_TEXTURE_RECTANGLE_EXT, _texture);
  GLenum glErr = glGetError();
  if (glErr != GL_NO_ERROR) {
    _owner->UnlockAGLCntx();
    return -1;
  }

  // Copy buffer to texture
  glTexSubImage2D(GL_TEXTURE_RECTANGLE_EXT,
                  0, // Level, not use
                  0, // start point x, (low left of pic)
                  0, // start point y,
                  _width, // width
                  _height, // height
                  _pixelFormat, // pictue format for _buffer
                  _pixelDataType, // data type of _buffer
                  (const GLvoid*) _buffer); // the pixel data

  if (glGetError() != GL_NO_ERROR) {
    _owner->UnlockAGLCntx();
    return -1;
  }

  _bufferIsUpdated = true;
  _owner->UnlockAGLCntx();

  return 0;
}

int VideoChannelAGL::RenderOffScreenBuffer()
{

    _owner->LockAGLCntx();

    if (_texture == 0)
    {
        _owner->UnlockAGLCntx();
        return 0;
    }

    GLfloat xStart = 2.0f * _startWidth - 1.0f;
    GLfloat xStop = 2.0f * _stopWidth - 1.0f;
    GLfloat yStart = 1.0f - 2.0f * _stopHeight;
    GLfloat yStop = 1.0f - 2.0f * _startHeight;

    aglSetCurrentContext(_aglContext);
    glBindTexture(GL_TEXTURE_RECTANGLE_EXT, _texture);

    if(_stretchedWidth != _oldStretchedWidth || _stretchedHeight != _oldStretchedHeight)
    {
        glViewport(0, 0, _stretchedWidth, _stretchedHeight);
    }
    _oldStretchedHeight = _stretchedHeight;
    _oldStretchedWidth = _stretchedWidth;

    // Now really put the texture into the framebuffer
    glLoadIdentity();

    glEnable(GL_TEXTURE_RECTANGLE_EXT);

    glBegin(GL_POLYGON);
    {
        glTexCoord2f(0.0, 0.0); glVertex2f(xStart, yStop);
        glTexCoord2f(_width, 0.0); glVertex2f(xStop, yStop);
        glTexCoord2f(_width, _height); glVertex2f(xStop, yStart);
        glTexCoord2f(0.0, _height); glVertex2f(xStart, yStart);
    }
    glEnd();

    glDisable(GL_TEXTURE_RECTANGLE_EXT);

    _bufferIsUpdated = false;

    _owner->UnlockAGLCntx();
    return 0;
}

int VideoChannelAGL::IsUpdated(bool& isUpdated)
{
    _owner->LockAGLCntx();
    isUpdated = _bufferIsUpdated;
    _owner->UnlockAGLCntx();

    return 0;
}

int VideoChannelAGL::SetStreamSettings(int /*streamId*/, float startWidth, float startHeight, float stopWidth, float stopHeight)
{

    _owner->LockAGLCntx();

    _startWidth = startWidth;
    _stopWidth = stopWidth;
    _startHeight = startHeight;
    _stopHeight = stopHeight;

    int oldWidth = _width;
    int oldHeight = _height;
    int oldNumberOfStreams = _numberOfStreams;

    _width = 0;
    _height = 0;

    int retVal = FrameSizeChange(oldWidth, oldHeight, oldNumberOfStreams);

    _owner->UnlockAGLCntx();

    return retVal;
}

int VideoChannelAGL::SetStreamCropSettings(int /*streamId*/, float /*startWidth*/, float /*startHeight*/, float /*stopWidth*/, float /*stopHeight*/)
{
    return -1;
}

#pragma mark VideoRenderAGL WindowRef constructor

VideoRenderAGL::VideoRenderAGL(WindowRef windowRef, bool fullscreen, int iId) :
_hiviewRef( 0),
_windowRef( windowRef),
_fullScreen( fullscreen),
_id( iId),
_renderCritSec(*CriticalSectionWrapper::CreateCriticalSection()),
_screenUpdateEvent( 0),
_isHIViewRef( false),
_aglContext( 0),
_windowWidth( 0),
_windowHeight( 0),
_lastWindowWidth( -1),
_lastWindowHeight( -1),
_lastHiViewWidth( -1),
_lastHiViewHeight( -1),
_currentParentWindowHeight( 0),
_currentParentWindowWidth( 0),
_currentParentWindowBounds( ),
_windowHasResized( false),
_lastParentWindowBounds( ),
_currentHIViewBounds( ),
_lastHIViewBounds( ),
_windowRect( ),
_aglChannels( ),
_zOrderToChannel( ),
_hiviewEventHandlerRef( NULL),
_windowEventHandlerRef( NULL),
_currentViewBounds( ),
_lastViewBounds( ),
_renderingIsPaused( false),

{
    //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s");

    _screenUpdateThread.reset(
        new rtc::PlatformThread(ScreenUpdateThreadProc, this, "ScreenUpdate"));
    _screenUpdateEvent = EventWrapper::Create();

    if(!IsValidWindowPtr(_windowRef))
    {
        //WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, _id, "%s:%d Invalid WindowRef:0x%x", __FUNCTION__, __LINE__, _windowRef);
    }
    else
    {
        //WEBRTC_TRACE(kTraceDebug, kTraceVideoRenderer, _id, "%s:%d WindowRef 0x%x is valid", __FUNCTION__, __LINE__, _windowRef);
    }

    GetWindowRect(_windowRect);

    _lastViewBounds.origin.x = 0;
    _lastViewBounds.origin.y = 0;
    _lastViewBounds.size.width = 0;
    _lastViewBounds.size.height = 0;

}

// this is a static function. It has been registered (in class constructor) to be called on various window redrawing or resizing.
// Since it is a static method, I have passed in "this" as the userData (one and only allowed) parameter, then calling member methods on it.
#pragma mark WindowRef Event Handler
pascal OSStatus VideoRenderAGL::sHandleWindowResized (EventHandlerCallRef /*nextHandler*/,
        EventRef theEvent,
        void* userData)
{
    WindowRef windowRef = NULL;

    int eventType = GetEventKind(theEvent);

    // see https://dcs.sourcerepo.com/dcs/tox_view/trunk/tox/libraries/i686-win32/include/quicktime/CarbonEvents.h for a list of codes
    GetEventParameter (theEvent,
            kEventParamDirectObject,
            typeWindowRef,
            NULL,
            sizeof (WindowRef),
            NULL,
            &windowRef);

    VideoRenderAGL* obj = (VideoRenderAGL*)(userData);

    bool updateUI = true;
    if(kEventWindowBoundsChanged == eventType)
    {
    }
    else if(kEventWindowBoundsChanging == eventType)
    {
    }
    else if(kEventWindowZoomed == eventType)
    {
    }
    else if(kEventWindowExpanding == eventType)
    {
    }
    else if(kEventWindowExpanded == eventType)
    {
    }
    else if(kEventWindowClickResizeRgn == eventType)
    {
    }
    else if(kEventWindowClickDragRgn == eventType)
    {
    }
    else
    {
        updateUI = false;
    }

    if(true == updateUI)
    {
        obj->ParentWindowResized(windowRef);
        obj->UpdateClipping();
        obj->RenderOffScreenBuffers();
    }

    return noErr;
}

#pragma mark VideoRenderAGL HIViewRef constructor

VideoRenderAGL::VideoRenderAGL(HIViewRef windowRef, bool fullscreen, int iId) :
_hiviewRef( windowRef),
_windowRef( 0),
_fullScreen( fullscreen),
_id( iId),
_renderCritSec(*CriticalSectionWrapper::CreateCriticalSection()),
_screenUpdateEvent( 0),
_isHIViewRef( false),
_aglContext( 0),
_windowWidth( 0),
_windowHeight( 0),
_lastWindowWidth( -1),
_lastWindowHeight( -1),
_lastHiViewWidth( -1),
_lastHiViewHeight( -1),
_currentParentWindowHeight( 0),
_currentParentWindowWidth( 0),
_currentParentWindowBounds( ),
_windowHasResized( false),
_lastParentWindowBounds( ),
_currentHIViewBounds( ),
_lastHIViewBounds( ),
_windowRect( ),
_aglChannels( ),
_zOrderToChannel( ),
_hiviewEventHandlerRef( NULL),
_windowEventHandlerRef( NULL),
_currentViewBounds( ),
_lastViewBounds( ),
_renderingIsPaused( false),
{
    //WEBRTC_TRACE(kTraceDebug, "%s:%d Constructor", __FUNCTION__, __LINE__);
    //    _renderCritSec = CriticalSectionWrapper::CreateCriticalSection();

    _screenUpdateThread.reset(new rtc::PlatformThread(
        ScreenUpdateThreadProc, this, "ScreenUpdateThread"));
    _screenUpdateEvent = EventWrapper::Create();

    GetWindowRect(_windowRect);

    _lastViewBounds.origin.x = 0;
    _lastViewBounds.origin.y = 0;
    _lastViewBounds.size.width = 0;
    _lastViewBounds.size.height = 0;

#ifdef NEW_HIVIEW_PARENT_EVENT_HANDLER
    // This gets the parent window of the HIViewRef that's passed in and installs a WindowRef event handler on it
    // The event handler looks for window resize events and adjusts the offset of the controls.

    //WEBRTC_TRACE(kTraceDebug, "%s:%d Installing Eventhandler for hiviewRef's parent window", __FUNCTION__, __LINE__);


    static const EventTypeSpec windowEventTypes[] =
    {
        kEventClassWindow, kEventWindowBoundsChanged,
        kEventClassWindow, kEventWindowBoundsChanging,
        kEventClassWindow, kEventWindowZoomed,
        kEventClassWindow, kEventWindowExpanded,
        kEventClassWindow, kEventWindowClickResizeRgn,
        kEventClassWindow, kEventWindowClickDragRgn
    };

    WindowRef parentWindow = HIViewGetWindow(windowRef);

    InstallWindowEventHandler (parentWindow,
            NewEventHandlerUPP (sHandleWindowResized),
            GetEventTypeCount(windowEventTypes),
            windowEventTypes,
            (void *) this, // this is an arbitrary parameter that will be passed on to your event handler when it is called later
            &_windowEventHandlerRef);

#endif

#ifdef NEW_HIVIEW_EVENT_HANDLER
    //WEBRTC_TRACE(kTraceDebug, "%s:%d Installing Eventhandler for hiviewRef", __FUNCTION__, __LINE__);

    static const EventTypeSpec hiviewEventTypes[] =
    {
        kEventClassControl, kEventControlBoundsChanged,
        kEventClassControl, kEventControlDraw
        //			kEventControlDragLeave
        //			kEventControlDragReceive
        //			kEventControlGetFocusPart
        //			kEventControlApplyBackground
        //			kEventControlDraw
        //			kEventControlHit

    };

    HIViewInstallEventHandler(_hiviewRef,
            NewEventHandlerUPP(sHandleHiViewResized),
            GetEventTypeCount(hiviewEventTypes),
            hiviewEventTypes,
            (void *) this,
            &_hiviewEventHandlerRef);

#endif
}

// this is a static function. It has been registered (in constructor) to be called on various window redrawing or resizing.
// Since it is a static method, I have passed in "this" as the userData (one and only allowed) parameter, then calling member methods on it.
#pragma mark HIViewRef Event Handler
pascal OSStatus VideoRenderAGL::sHandleHiViewResized (EventHandlerCallRef nextHandler, EventRef theEvent, void* userData)
{
    //static int      callbackCounter = 1;
    HIViewRef hiviewRef = NULL;

    // see https://dcs.sourcerepo.com/dcs/tox_view/trunk/tox/libraries/i686-win32/include/quicktime/CarbonEvents.h for a list of codes
    int eventType = GetEventKind(theEvent);
    OSStatus status = noErr;
    status = GetEventParameter (theEvent,
            kEventParamDirectObject,
            typeControlRef,
            NULL,
            sizeof (ControlRef),
            NULL,
            &hiviewRef);

    VideoRenderAGL* obj = (VideoRenderAGL*)(userData);
    WindowRef parentWindow = HIViewGetWindow(hiviewRef);
    bool updateUI = true;

    if(kEventControlBoundsChanged == eventType)
    {
    }
    else if(kEventControlDraw == eventType)
    {
    }
    else
    {
        updateUI = false;
    }

    if(true == updateUI)
    {
        obj->ParentWindowResized(parentWindow);
        obj->UpdateClipping();
        obj->RenderOffScreenBuffers();
    }

    return status;
}

VideoRenderAGL::~VideoRenderAGL()
{

    //WEBRTC_TRACE(kTraceDebug, "%s:%d Destructor", __FUNCTION__, __LINE__);


#ifdef USE_EVENT_HANDLERS
    // remove event handlers
    OSStatus status;
    if(_isHIViewRef)
    {
        status = RemoveEventHandler(_hiviewEventHandlerRef);
    }
    else
    {
        status = RemoveEventHandler(_windowEventHandlerRef);
    }
    if(noErr != status)
    {
        if(_isHIViewRef)
        {

            //WEBRTC_TRACE(kTraceDebug, "%s:%d Failed to remove hiview event handler: %d", __FUNCTION__, __LINE__, (int)_hiviewEventHandlerRef);
        }
        else
        {
            //WEBRTC_TRACE(kTraceDebug, "%s:%d Failed to remove window event handler %d", __FUNCTION__, __LINE__, (int)_windowEventHandlerRef);
        }
    }

#endif

    OSStatus status;
#ifdef NEW_HIVIEW_PARENT_EVENT_HANDLER
    if(_windowEventHandlerRef)
    {
        status = RemoveEventHandler(_windowEventHandlerRef);
        if(status != noErr)
        {
            //WEBRTC_TRACE(kTraceDebug, "%s:%d failed to remove window event handler %d", __FUNCTION__, __LINE__, (int)_windowEventHandlerRef);
        }
    }
#endif

#ifdef NEW_HIVIEW_EVENT_HANDLER
    if(_hiviewEventHandlerRef)
    {
        status = RemoveEventHandler(_hiviewEventHandlerRef);
        if(status != noErr)
        {
            //WEBRTC_TRACE(kTraceDebug, "%s:%d Failed to remove hiview event handler: %d", __FUNCTION__, __LINE__, (int)_hiviewEventHandlerRef);
        }
    }
#endif

    // Signal event to exit thread, then delete it
    rtc::PlatformThread* tmpPtr = _screenUpdateThread.release();

    if (tmpPtr)
    {
        _screenUpdateEvent->Set();
        _screenUpdateEvent->StopTimer();

        tmpPtr->Stop();
        delete tmpPtr;
        delete _screenUpdateEvent;
        _screenUpdateEvent = NULL;
    }

    if (_aglContext != 0)
    {
        aglSetCurrentContext(_aglContext);
        aglDestroyContext(_aglContext);
        _aglContext = 0;
    }

    // Delete all channels
    std::map<int, VideoChannelAGL*>::iterator it = _aglChannels.begin();
    while (it!= _aglChannels.end())
    {
        delete it->second;
        _aglChannels.erase(it);
        it = _aglChannels.begin();
    }
    _aglChannels.clear();

    // Clean the zOrder map
    std::multimap<int, int>::iterator zIt = _zOrderToChannel.begin();
    while(zIt != _zOrderToChannel.end())
    {
        _zOrderToChannel.erase(zIt);
        zIt = _zOrderToChannel.begin();
    }
    _zOrderToChannel.clear();

    //delete _renderCritSec;


}

int VideoRenderAGL::GetOpenGLVersion(int& aglMajor, int& aglMinor)
{
    aglGetVersion((GLint *) &aglMajor, (GLint *) &aglMinor);
    return 0;
}

int VideoRenderAGL::Init()
{
    LockAGLCntx();

    // Start rendering thread...
    if (!_screenUpdateThread)
    {
        UnlockAGLCntx();
        //WEBRTC_TRACE(kTraceError, "%s:%d Thread not created", __FUNCTION__, __LINE__);
        return -1;
    }
    _screenUpdateThread->Start();
    _screenUpdateThread->SetPriority(rtc::kRealtimePriority);

    // Start the event triggering the render process
    unsigned int monitorFreq = 60;
    _screenUpdateEvent->StartTimer(true, 1000/monitorFreq);

    // Create mixing textures
    if (CreateMixingContext() == -1)
    {
        //WEBRTC_TRACE(kTraceError, "%s:%d Could not create a mixing context", __FUNCTION__, __LINE__);
        UnlockAGLCntx();
        return -1;
    }

    UnlockAGLCntx();
    return 0;
}

VideoChannelAGL* VideoRenderAGL::CreateAGLChannel(int channel, int zOrder, float startWidth, float startHeight, float stopWidth, float stopHeight)
{

    LockAGLCntx();

    //WEBRTC_TRACE(kTraceInfo, "%s:%d Creating AGL channel: %d", __FUNCTION__, __LINE__, channel);

    if (HasChannel(channel))
    {
        //WEBRTC_TRACE(kTraceError, "%s:%d Channel already exists", __FUNCTION__, __LINE__);
        UnlockAGLCntx();k
        return NULL;
    }

    if (_zOrderToChannel.find(zOrder) != _zOrderToChannel.end())
    {
        // There are already one channel using this zOrder
        // TODO: Allow multiple channels with same zOrder
    }

    VideoChannelAGL* newAGLChannel = new VideoChannelAGL(_aglContext, _id, this);

    if (newAGLChannel->SetStreamSettings(0, startWidth, startHeight, stopWidth, stopHeight) == -1)
    {
        if (newAGLChannel)
        {
            delete newAGLChannel;
            newAGLChannel = NULL;
        }
        //WEBRTC_LOG(kTraceError, "Could not create AGL channel");
        //WEBRTC_TRACE(kTraceError, "%s:%d Could not create AGL channel", __FUNCTION__, __LINE__);
        UnlockAGLCntx();
        return NULL;
    }
k
    _aglChannels[channel] = newAGLChannel;
    _zOrderToChannel.insert(std::pair<int, int>(zOrder, channel));

    UnlockAGLCntx();
    return newAGLChannel;
}

int VideoRenderAGL::DeleteAllAGLChannels()
{
    CriticalSectionScoped cs(&_renderCritSec);

    //WEBRTC_TRACE(kTraceInfo, "%s:%d Deleting all AGL channels", __FUNCTION__, __LINE__);
    //int i = 0 ;
    std::map<int, VideoChannelAGL*>::iterator it;
    it = _aglChannels.begin();

    while (it != _aglChannels.end())
    {
        VideoChannelAGL* channel = it->second;
        if (channel)
        delete channel;

        _aglChannels.erase(it);
        it = _aglChannels.begin();
    }
    _aglChannels.clear();
    return 0;
}

int VideoRenderAGL::DeleteAGLChannel(int channel)
{
    CriticalSectionScoped cs(&_renderCritSec);
    //WEBRTC_TRACE(kTraceDebug, "%s:%d Deleting AGL channel %d", __FUNCTION__, __LINE__, channel);

    std::map<int, VideoChannelAGL*>::iterator it;
    it = _aglChannels.find(channel);
    if (it != _aglChannels.end())
    {
        delete it->second;
        _aglChannels.erase(it);
    }
    else
    {
        //WEBRTC_TRACE(kTraceWarning, "%s:%d Channel not found", __FUNCTION__, __LINE__);
        return -1;
    }

    std::multimap<int, int>::iterator zIt = _zOrderToChannel.begin();
    while( zIt != _zOrderToChannel.end())
    {
        if (zIt->second == channel)
        {
            _zOrderToChannel.erase(zIt);
            break;
        }
        zIt++;// = _zOrderToChannel.begin();
    }

    return 0;
}

int VideoRenderAGL::StopThread()
{
    CriticalSectionScoped cs(&_renderCritSec);
    rtc::PlatformThread* tmpPtr = _screenUpdateThread.release();

    if (tmpPtr)
    {
        _screenUpdateEvent->Set();
        _renderCritSec.Leave();
        tmpPtr->Stop();
        delete tmpPtr;
        _renderCritSec.Enter();
    }

    delete _screenUpdateEvent;
    _screenUpdateEvent = NULL;

    return 0;
}

bool VideoRenderAGL::IsFullScreen()
{
    CriticalSectionScoped cs(&_renderCritSec);
    return _fullScreen;
}

bool VideoRenderAGL::HasChannels()
{

    CriticalSectionScoped cs(&_renderCritSec);

    if (_aglChannels.begin() != _aglChannels.end())
    {
        return true;
    }

    return false;
}

bool VideoRenderAGL::HasChannel(int channel)
{
    CriticalSectionScoped cs(&_renderCritSec);

    std::map<int, VideoChannelAGL*>::iterator it = _aglChannels.find(channel);
    if (it != _aglChannels.end())
    {
        return true;
    }

    return false;
}

int VideoRenderAGL::GetChannels(std::list<int>& channelList)
{

    CriticalSectionScoped cs(&_renderCritSec);
    std::map<int, VideoChannelAGL*>::iterator it = _aglChannels.begin();

    while (it != _aglChannels.end())
    {
        channelList.push_back(it->first);
        it++;
    }

    return 0;
}

VideoChannelAGL* VideoRenderAGL::ConfigureAGLChannel(int channel, int zOrder, float startWidth, float startHeight, float stopWidth, float stopHeight)
{

    CriticalSectionScoped cs(&_renderCritSec);

    std::map<int, VideoChannelAGL*>::iterator it = _aglChannels.find(channel);

    if (it != _aglChannels.end())
    {
        VideoChannelAGL* aglChannel = it->second;
        if (aglChannel->SetStreamSettings(0, startWidth, startHeight, stopWidth, stopHeight) == -1)
        {
            return NULL;
        }

        std::multimap<int, int>::iterator it = _zOrderToChannel.begin();
        while(it != _zOrderToChannel.end())
        {
            if (it->second == channel)
            {
                if (it->first != zOrder)
                {
                    _zOrderToChannel.erase(it);
                    _zOrderToChannel.insert(std::pair<int, int>(zOrder, channel));
                }
                break;
            }
            it++;
        }
        return aglChannel;
    }

    return NULL;
}

bool VideoRenderAGL::ScreenUpdateThreadProc(void* obj)
{
    return static_cast<VideoRenderAGL*>(obj)->ScreenUpdateProcess();
}

bool VideoRenderAGL::ScreenUpdateProcess()
{
    _screenUpdateEvent->Wait(100);

    LockAGLCntx();

    if (!_screenUpdateThread)
    {
        UnlockAGLCntx();
        return false;
    }

    if (aglSetCurrentContext(_aglContext) == GL_FALSE)
    {
        UnlockAGLCntx();
        return true;
    }

    if (GetWindowRect(_windowRect) == -1)
    {
        UnlockAGLCntx();
        return true;
    }

    if (_windowWidth != (_windowRect.right - _windowRect.left)
            || _windowHeight != (_windowRect.bottom - _windowRect.top))
    {
        // We have a new window size, update the context.
        if (aglUpdateContext(_aglContext) == GL_FALSE)
        {
            UnlockAGLCntx();
            return true;
        }
        _windowWidth = _windowRect.right - _windowRect.left;
        _windowHeight = _windowRect.bottom - _windowRect.top;
    }

    // this section will poll to see if the window size has changed
    // this is causing problem w/invalid windowRef
    // this code has been modified and exists now in the window event handler
#ifndef NEW_HIVIEW_PARENT_EVENT_HANDLER
    if (_isHIViewRef)
    {

        if(FALSE == HIViewIsValid(_hiviewRef))
        {

            //WEBRTC_TRACE(kTraceDebug, "%s:%d Invalid windowRef", __FUNCTION__, __LINE__);
            UnlockAGLCntx();
            return true;
        }
        WindowRef window = HIViewGetWindow(_hiviewRef);

        if(FALSE == IsValidWindowPtr(window))
        {
            //WEBRTC_TRACE(kTraceDebug, "%s:%d Invalide hiviewRef", __FUNCTION__, __LINE__);
            UnlockAGLCntx();
            return true;
        }
        if (window == NULL)
        {
            //WEBRTC_TRACE(kTraceDebug, "%s:%d WindowRef = NULL", __FUNCTION__, __LINE__);
            UnlockAGLCntx();
            return true;
        }

        if(FALSE == MacIsWindowVisible(window))
        {
            //WEBRTC_TRACE(kTraceDebug, "%s:%d MacIsWindowVisible == FALSE. Returning early", __FUNCTION__, __LINE__);
            UnlockAGLCntx();
            return true;
        }

        HIRect viewBounds; // Placement and size for HIView
        int windowWidth = 0; // Parent window width
        int windowHeight = 0; // Parent window height

        // NOTE: Calling GetWindowBounds with kWindowStructureRgn will crash intermittentaly if the OS decides it needs to push it into the back for a moment.
        // To counter this, we get the titlebar height on class construction and then add it to the content region here. Content regions seems not to crash
        Rect contentBounds =
        {   0, 0, 0, 0}; // The bounds for the parent window

#if		defined(USE_CONTENT_RGN)
        GetWindowBounds(window, kWindowContentRgn, &contentBounds);
#elif	defined(USE_STRUCT_RGN)
        GetWindowBounds(window, kWindowStructureRgn, &contentBounds);
#endif

        Rect globalBounds =
        {   0, 0, 0, 0}; // The bounds for the parent window
        globalBounds.top = contentBounds.top;
        globalBounds.right = contentBounds.right;
        globalBounds.bottom = contentBounds.bottom;
        globalBounds.left = contentBounds.left;

        windowHeight = globalBounds.bottom - globalBounds.top;
        windowWidth = globalBounds.right - globalBounds.left;

        // Get the size of the HIViewRef
        HIViewGetBounds(_hiviewRef, &viewBounds);
        HIViewConvertRect(&viewBounds, _hiviewRef, NULL);

        // Check if this is the first call..
        if (_lastWindowHeight == -1 &&
                _lastWindowWidth == -1)
        {
            _lastWindowWidth = windowWidth;
            _lastWindowHeight = windowHeight;

            _lastViewBounds.origin.x = viewBounds.origin.x;
            _lastViewBounds.origin.y = viewBounds.origin.y;
            _lastViewBounds.size.width = viewBounds.size.width;
            _lastViewBounds.size.height = viewBounds.size.height;
        }
        sfasdfasdf

        bool resized = false;

        // Check if parent window size has changed
        if (windowHeight != _lastWindowHeight ||
                windowWidth != _lastWindowWidth)
        {
            resized = true;
        }

        // Check if the HIView has new size or is moved in the parent window
        if (_lastViewBounds.origin.x != viewBounds.origin.x ||
                _lastViewBounds.origin.y != viewBounds.origin.y ||
                _lastViewBounds.size.width != viewBounds.size.width ||
                _lastViewBounds.size.height != viewBounds.size.height)
        {
            // The HiView is resized or has moved.
            resized = true;
        }

        if (resized)
        {

            //WEBRTC_TRACE(kTraceDebug, "%s:%d Window has resized", __FUNCTION__, __LINE__);

            // Calculate offset between the windows
            // {x, y, widht, height}, x,y = lower left corner
            const GLint offs[4] =
            {   (int)(0.5f + viewBounds.origin.x),
                (int)(0.5f + windowHeight - (viewBounds.origin.y + viewBounds.size.height)),
                viewBounds.size.width, viewBounds.size.height};

            //WEBRTC_TRACE(kTraceDebug, "%s:%d contentBounds	t:%d r:%d b:%d l:%d", __FUNCTION__, __LINE__,
            contentBounds.top, contentBounds.right, contentBounds.bottom, contentBounds.left);
            //WEBRTC_TRACE(kTraceDebug, "%s:%d windowHeight=%d", __FUNCTION__, __LINE__, windowHeight);
            //WEBRTC_TRACE(kTraceDebug, "%s:%d offs[4] = %d, %d, %d, %d", __FUNCTION__, __LINE__, offs[0], offs[1], offs[2], offs[3]);

            aglSetDrawable (_aglContext, GetWindowPort(window));
            aglSetInteger(_aglContext, AGL_BUFFER_RECT, offs);
            aglEnable(_aglContext, AGL_BUFFER_RECT);

            // We need to change the viewport too if the HIView size has changed
            glViewport(0.0f, 0.0f, (GLsizei) viewBounds.size.width, (GLsizei) viewBounds.size.height);

        }
        _lastWindowWidth = windowWidth;
        _lastWindowHeight = windowHeight;

        _lastViewBounds.origin.x = viewBounds.origin.x;
        _lastViewBounds.origin.y = viewBounds.origin.y;
        _lastViewBounds.size.width = viewBounds.size.width;
        _lastViewBounds.size.height = viewBounds.size.height;

    }
#endif
    if (_fullScreen)
    {
        // TODO
        // We use double buffers, must always update
        //RenderOffScreenBuffersToBackBuffer();
    }
    else
    {
        // Check if there are any updated buffers
        bool updated = false;

        // TODO: check if window size is updated!
        // TODO Improvement: Walk through the zOrder Map to only render the ones in need of update
        std::map<int, VideoChannelAGL*>::iterator it = _aglChannels.begin();
        while (it != _aglChannels.end())
        {

            VideoChannelAGL* aglChannel = it->second;
            aglChannel->UpdateStretchSize(_windowHeight, _windowWidth);
            aglChannel->IsUpdated(updated);
            if (updated)
            {
                break;
            }
            it++;
        }

        if (updated)
        {
            // At least on buffers is updated, we need to repaint the texture
            if (RenderOffScreenBuffers() != -1)
            {
                // MF
                //SwapAndDisplayBuffers();
            }
            else
            {
                // Error updating the mixing texture, don't swap.
            }
        }
    }

    UnlockAGLCntx();

    //WEBRTC_LOG(kTraceDebug, "Leaving ScreenUpdateProcess()");
    return true;
}

void VideoRenderAGL::ParentWindowResized(WindowRef window)
{
    //WEBRTC_LOG(kTraceDebug, "%s HIViewRef:%d owner window has resized", __FUNCTION__, (int)_hiviewRef);

    LockAGLCntx();
k
    // set flag
    _windowHasResized = false;

    if(FALSE == HIViewIsValid(_hiviewRef))
    {
        //WEBRTC_LOG(kTraceDebug, "invalid windowRef");
        UnlockAGLCntx();
        return;
    }

    if(FALSE == IsValidWindowPtr(window))
    {
        //WEBRTC_LOG(kTraceError, "invalid windowRef");
        UnlockAGLCntx();
        return;
    }

    if (window == NULL)
    {
        //WEBRTC_LOG(kTraceError, "windowRef = NULL");
        UnlockAGLCntx();
        return;
    }

    if(FALSE == MacIsWindowVisible(window))
    {
        //WEBRTC_LOG(kTraceDebug, "MacIsWindowVisible = FALSE. Returning early.");
        UnlockAGLCntx();
        return;
    }

    Rect contentBounds =
    {   0, 0, 0, 0};

#if		defined(USE_CONTENT_RGN)
    GetWindowBounds(window, kWindowContentRgn, &contentBounds);
#elif	defined(USE_STRUCT_RGN)
    GetWindowBounds(window, kWindowStructureRgn, &contentBounds);
#endif

    //WEBRTC_LOG(kTraceDebug, "%s contentBounds	t:%d r:%d b:%d l:%d", __FUNCTION__, contentBounds.top, contentBounds.right, contentBounds.bottom, contentBounds.left);

    // update global vars
    _currentParentWindowBounds.top = contentBounds.top;
    _currentParentWindowBounds.left = contentBounds.left;
    _currentParentWindowBounds.bottom = contentBounds.bottom;
    _currentParentWindowBounds.right = contentBounds.right;

    _currentParentWindowWidth = _currentParentWindowBounds.right - _currentParentWindowBounds.left;
    _currentParentWindowHeight = _currentParentWindowBounds.bottom - _currentParentWindowBounds.top;

    _windowHasResized = true;

    // ********* update AGL offsets
    HIRect viewBounds;
    HIViewGetBounds(_hiviewRef, &viewBounds);
    HIViewConvertRect(&viewBounds, _hiviewRef, NULL);

    const GLint offs[4] =
    {   (int)(0.5f + viewBounds.origin.x),
        (int)(0.5f + _currentParentWindowHeight - (viewBounds.origin.y + viewBounds.size.height)),
        viewBounds.size.width, viewBounds.size.height};
    //WEBRTC_LOG(kTraceDebug, "%s _currentParentWindowHeight=%d", __FUNCTION__, _currentParentWindowHeight);
    //WEBRTC_LOG(kTraceDebug, "%s offs[4] = %d, %d, %d, %d", __FUNCTION__, offs[0], offs[1], offs[2], offs[3]);

    aglSetCurrentContext(_aglContext);
    aglSetDrawable (_aglContext, GetWindowPort(window));
    aglSetInteger(_aglContext, AGL_BUFFER_RECT, offs);
    aglEnable(_aglContext, AGL_BUFFER_RECT);

    // We need to change the viewport too if the HIView size has changed
    glViewport(0.0f, 0.0f, (GLsizei) viewBounds.size.width, (GLsizei) viewBounds.size.height);

    UnlockAGLCntx();

    return;
}

int VideoRenderAGL::CreateMixingContext()
{

    LockAGLCntx();

    //WEBRTC_LOG(kTraceDebug, "Entering CreateMixingContext()");

    // Use both AGL_ACCELERATED and AGL_NO_RECOVERY to make sure
    // a hardware renderer is used and not a software renderer.

    GLint attributes[] =
    {
        AGL_DOUBLEBUFFER,
        AGL_WINDOW,
        AGL_RGBA,
        AGL_NO_RECOVERY,
        AGL_ACCELERATED,
        AGL_RED_SIZE, 8,
        AGL_GREEN_SIZE, 8,
        AGL_BLUE_SIZE, 8,
        AGL_ALPHA_SIZE, 8,
        AGL_DEPTH_SIZE, 24,
        AGL_NONE,
    };

    AGLPixelFormat aglPixelFormat;

    // ***** Set up the OpenGL Context *****

    // Get a pixel format for the attributes above
    aglPixelFormat = aglChoosePixelFormat(NULL, 0, attributes);
    if (NULL == aglPixelFormat)
    {
        //WEBRTC_LOG(kTraceError, "Could not create pixel format");
        UnlockAGLCntx();
        return -1;
    }

    // Create an AGL context
    _aglContext = aglCreateContext(aglPixelFormat, NULL);
    if (_aglContext == NULL)
    {
        //WEBRTC_LOG(kTraceError, "Could no create AGL context");
        UnlockAGLCntx();
        return -1;
    }

    // Release the pixel format memory
    aglDestroyPixelFormat(aglPixelFormat);

    // Set the current AGL context for the rest of the settings
    if (aglSetCurrentContext(_aglContext) == false)
    {
        //WEBRTC_LOG(kTraceError, "Could not set current context: %d", aglGetError());
        UnlockAGLCntx();
        return -1;
    }

    if (_isHIViewRef)
    {
        //---------------------------
        // BEGIN: new test code
#if 0
        // Don't use this one!
        // There seems to be an OS X bug that can't handle
        // movements and resizing of the parent window
        // and or the HIView
        if (aglSetHIViewRef(_aglContext,_hiviewRef) == false)
        {
            //WEBRTC_LOG(kTraceError, "Could not set WindowRef: %d", aglGetError());
            UnlockAGLCntx();
            return -1;
        }
#else

        // Get the parent window for this control
        WindowRef window = GetControlOwner(_hiviewRef);

        Rect globalBounds =
        {   0,0,0,0}; // The bounds for the parent window
        HIRect viewBounds; // Placemnt in the parent window and size.
        int windowHeight = 0;

        //		Rect titleBounds = {0,0,0,0};
        //		GetWindowBounds(window, kWindowTitleBarRgn, &titleBounds);
        //		_titleBarHeight = titleBounds.top - titleBounds.bottom;
        //		if(0 == _titleBarHeight)
        //		{
        //            //WEBRTC_LOG(kTraceError, "Titlebar height = 0");
        //            //return -1;
        //		}


        // Get the bounds for the parent window
#if		defined(USE_CONTENT_RGN)
        GetWindowBounds(window, kWindowContentRgn, &globalBounds);
#elif	defined(USE_STRUCT_RGN)
        GetWindowBounds(window, kWindowStructureRgn, &globalBounds);
#endif
        windowHeight = globalBounds.bottom - globalBounds.top;

        // Get the bounds for the HIView
        HIViewGetBounds(_hiviewRef, &viewBounds);

        HIViewConvertRect(&viewBounds, _hiviewRef, NULL);

        const GLint offs[4] =
        {   (int)(0.5f + viewBounds.origin.x),
            (int)(0.5f + windowHeight - (viewBounds.origin.y + viewBounds.size.height)),
            viewBounds.size.width, viewBounds.size.height};

        //WEBRTC_LOG(kTraceDebug, "%s offs[4] = %d, %d, %d, %d", __FUNCTION__, offs[0], offs[1], offs[2], offs[3]);


        aglSetDrawable (_aglContext, GetWindowPort(window));
        aglSetInteger(_aglContext, AGL_BUFFER_RECT, offs);
        aglEnable(_aglContext, AGL_BUFFER_RECT);

        GLint surfaceOrder = 1; // 1: above window, -1 below.
        //OSStatus status = aglSetInteger(_aglContext, AGL_SURFACE_ORDER, &surfaceOrder);
        aglSetInteger(_aglContext, AGL_SURFACE_ORDER, &surfaceOrder);

        glViewport(0.0f, 0.0f, (GLsizei) viewBounds.size.width, (GLsizei) viewBounds.size.height);
#endif

    }
    else
    {
        if(GL_FALSE == aglSetDrawable (_aglContext, GetWindowPort(_windowRef)))
        {
            //WEBRTC_LOG(kTraceError, "Could not set WindowRef: %d", aglGetError());
            UnlockAGLCntx();
            return -1;
        }
    }

    _windowWidth = _windowRect.right - _windowRect.left;
    _windowHeight = _windowRect.bottom - _windowRect.top;

    // opaque surface
    int surfaceOpacity = 1;
    if (aglSetInteger(_aglContext, AGL_SURFACE_OPACITY, (const GLint *) &surfaceOpacity) == false)
    {
        //WEBRTC_LOG(kTraceError, "Could not set surface opacity: %d", aglGetError());
        UnlockAGLCntx();
        return -1;
    }

    // 1 -> sync to screen rat, slow...
    //int swapInterval = 0;  // 0 don't sync with vertical trace
    int swapInterval = 0; // 1 sync with vertical trace
    if (aglSetInteger(_aglContext, AGL_SWAP_INTERVAL, (const GLint *) &swapInterval) == false)
    {
        //WEBRTC_LOG(kTraceError, "Could not set swap interval: %d", aglGetError());
        UnlockAGLCntx();
        return -1;
    }

    // Update the rect with the current size
    if (GetWindowRect(_windowRect) == -1)
    {
        //WEBRTC_LOG(kTraceError, "Could not get window size");
        UnlockAGLCntx();
        return -1;
    }

    // Disable not needed functionality to increase performance
    glDisable(GL_DITHER);
    glDisable(GL_ALPHA_TEST);
    glDisable(GL_STENCIL_TEST);
    glDisable(GL_FOG);
    glDisable(GL_TEXTURE_2D);
    glPixelZoom(1.0, 1.0);

    glDisable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glDepthMask(GL_FALSE);
    glDisable(GL_CULL_FACE);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    GLenum glErr = glGetError();

    if (glErr)
    {
    }

    UpdateClipping();

    //WEBRTC_LOG(kTraceDebug, "Leaving CreateMixingContext()");

    UnlockAGLCntx();
    return 0;
}

int VideoRenderAGL::RenderOffScreenBuffers()
{
    LockAGLCntx();

    // Get the current window size, it might have changed since last render.
    if (GetWindowRect(_windowRect) == -1)
    {
        //WEBRTC_LOG(kTraceError, "Could not get window rect");
        UnlockAGLCntx();
        return -1;
    }

    if (aglSetCurrentContext(_aglContext) == false)
    {
        //WEBRTC_LOG(kTraceError, "Could not set current context for rendering");
        UnlockAGLCntx();
        return -1;
    }

    // HERE - onl if updated!
    glClear(GL_COLOR_BUFFER_BIT);

    // Loop through all channels starting highest zOrder ending with lowest.
    for (std::multimap<int, int>::reverse_iterator rIt = _zOrderToChannel.rbegin();
    rIt != _zOrderToChannel.rend();
    rIt++)
    {
        int channelId = rIt->second;
        std::map<int, VideoChannelAGL*>::iterator it = _aglChannels.find(channelId);

        VideoChannelAGL* aglChannel = it->second;

        aglChannel->RenderOffScreenBuffer();
    }

    SwapAndDisplayBuffers();

    UnlockAGLCntx();
    return 0;
}

int VideoRenderAGL::SwapAndDisplayBuffers()
{

    LockAGLCntx();
    if (_fullScreen)
    {
        // TODO:
        // Swap front and back buffers, rendering taking care of in the same call
        //aglSwapBuffers(_aglContext);
        // Update buffer index to the idx for the next rendering!
        //_textureIdx = (_textureIdx + 1) & 1;
    }
    else
    {
        // Single buffer rendering, only update context.
        glFlush();
        aglSwapBuffers(_aglContext);
        HIViewSetNeedsDisplay(_hiviewRef, true);
    }

    UnlockAGLCntx();
    return 0;
}

int VideoRenderAGL::GetWindowRect(Rect& rect)
{

    LockAGLCntx();

    if (_isHIViewRef)
    {
        if (_hiviewRef)
        {
            HIRect HIViewRect1;
            if(FALSE == HIViewIsValid(_hiviewRef))
            {
                rect.top = 0;
                rect.left = 0;
                rect.right = 0;
                rect.bottom = 0;
                //WEBRTC_LOG(kTraceError,"GetWindowRect() HIViewIsValid() returned false");
                UnlockAGLCntx();
            }
            HIViewGetBounds(_hiviewRef,&HIViewRect1);
            HIRectConvert(&HIViewRect1, 1, NULL, 2, NULL);
            if(HIViewRect1.origin.x < 0)
            {
                rect.top = 0;
                //WEBRTC_LOG(kTraceDebug, "GetWindowRect() rect.top = 0");
            }
            else
            {
                rect.top = HIViewRect1.origin.x;
            }

            if(HIViewRect1.origin.y < 0)
            {
                rect.left = 0;
                //WEBRTC_LOG(kTraceDebug, "GetWindowRect() rect.left = 0");
            }
            else
            {
                rect.left = HIViewRect1.origin.y;
            }

            if(HIViewRect1.size.width < 0)
            {
                rect.right = 0;
                //WEBRTC_LOG(kTraceDebug, "GetWindowRect() rect.right = 0");
            }
            else
            {
                rect.right = HIViewRect1.size.width;
            }

            if(HIViewRect1.size.height < 0)
            {
                rect.bottom = 0;
                //WEBRTC_LOG(kTraceDebug, "GetWindowRect() rect.bottom = 0");
            }
            else
            {
                rect.bottom = HIViewRect1.size.height;
            }

            ////WEBRTC_LOG(kTraceDebug,"GetWindowRect() HIViewRef: rect.top = %d, rect.left = %d, rect.right = %d, rect.bottom =%d in GetWindowRect", rect.top,rect.left,rect.right,rect.bottom);
            UnlockAGLCntx();
        }
        else
        {
            //WEBRTC_LOG(kTraceError, "invalid HIViewRef");
            UnlockAGLCntx();
        }
    }
    else
    {
        if (_windowRef)
        {
            GetWindowBounds(_windowRef, kWindowContentRgn, &rect);
            UnlockAGLCntx();
        }
        else
        {
            //WEBRTC_LOG(kTraceError, "No WindowRef");
            UnlockAGLCntx();
        }
    }
}

int VideoRenderAGL::UpdateClipping()
{
    //WEBRTC_LOG(kTraceDebug, "Entering UpdateClipping()");
    LockAGLCntx();

    if(_isHIViewRef)
    {
        if(FALSE == HIViewIsValid(_hiviewRef))
        {
            //WEBRTC_LOG(kTraceError, "UpdateClipping() _isHIViewRef is invalid. Returning -1");
            UnlockAGLCntx();
            return -1;
        }

        RgnHandle visibleRgn = NewRgn();
        SetEmptyRgn (visibleRgn);

        if(-1 == CalculateVisibleRegion((ControlRef)_hiviewRef, visibleRgn, true))
        {
        }

        if(GL_FALSE == aglSetCurrentContext(_aglContext))
        {
            GLenum glErr = aglGetError();
            //WEBRTC_LOG(kTraceError, "aglSetCurrentContext returned FALSE with error code %d at line %d", glErr, __LINE__);
        }

        if(GL_FALSE == aglEnable(_aglContext, AGL_CLIP_REGION))
        {
            GLenum glErr = aglGetError();
            //WEBRTC_LOG(kTraceError, "aglEnable returned FALSE with error code %d at line %d\n", glErr, __LINE__);
        }

        if(GL_FALSE == aglSetInteger(_aglContext, AGL_CLIP_REGION, (const GLint*)visibleRgn))
        {
            GLenum glErr = aglGetError();
            //WEBRTC_LOG(kTraceError, "aglSetInteger returned FALSE with error code %d at line %d\n", glErr, __LINE__);
        }

        DisposeRgn(visibleRgn);
    }
    else
    {
        //WEBRTC_LOG(kTraceDebug, "Not using a hiviewref!\n");
    }

    //WEBRTC_LOG(kTraceDebug, "Leaving UpdateClipping()");
    UnlockAGLCntx();
    return true;
}

int VideoRenderAGL::CalculateVisibleRegion(ControlRef control, RgnHandle &visibleRgn, bool clipChildren)
{

    //	LockAGLCntx();

    //WEBRTC_LOG(kTraceDebug, "Entering CalculateVisibleRegion()");
    OSStatus osStatus = 0;
    OSErr osErr = 0;

    RgnHandle tempRgn = NewRgn();
    if (IsControlVisible(control))
    {
        RgnHandle childRgn = NewRgn();
        WindowRef window = GetControlOwner(control);
        ControlRef rootControl;
        GetRootControl(window, &rootControl); // 'wvnc'
        ControlRef masterControl;
        osStatus = GetSuperControl(rootControl, &masterControl);
        // //WEBRTC_LOG(kTraceDebug, "IBM GetSuperControl=%d", osStatus);

        if (masterControl != NULL)
        {
            CheckValidRegion(visibleRgn);
            // init visibleRgn with region of 'wvnc'
            osStatus = GetControlRegion(rootControl, kControlStructureMetaPart, visibleRgn);
            // //WEBRTC_LOG(kTraceDebug, "IBM GetControlRegion=%d : %d", osStatus, __LINE__);
            //GetSuperControl(rootControl, &rootControl);
            ControlRef tempControl = control, lastControl = 0;
            while (tempControl != masterControl) // current control != master

            {
                CheckValidRegion(tempRgn);

                // //WEBRTC_LOG(kTraceDebug, "IBM tempControl=%d masterControl=%d", tempControl, masterControl);
                ControlRef subControl;

                osStatus = GetControlRegion(tempControl, kControlStructureMetaPart, tempRgn); // intersect the region of the current control with visibleRgn
                // //WEBRTC_LOG(kTraceDebug, "IBM GetControlRegion=%d : %d", osStatus, __LINE__);
                CheckValidRegion(tempRgn);

                osErr = HIViewConvertRegion(tempRgn, tempControl, rootControl);
                // //WEBRTC_LOG(kTraceDebug, "IBM HIViewConvertRegion=%d : %d", osErr, __LINE__);
                CheckValidRegion(tempRgn);

                SectRgn(tempRgn, visibleRgn, visibleRgn);
                CheckValidRegion(tempRgn);
                CheckValidRegion(visibleRgn);
                if (EmptyRgn(visibleRgn)) // if the region is empty, bail
                break;

                if (clipChildren || tempControl != control) // clip children if true, cut out the tempControl if it's not one passed to this function

                {
                    UInt16 numChildren;
                    osStatus = CountSubControls(tempControl, &numChildren); // count the subcontrols
                    // //WEBRTC_LOG(kTraceDebug, "IBM CountSubControls=%d : %d", osStatus, __LINE__);

                    // //WEBRTC_LOG(kTraceDebug, "IBM numChildren=%d", numChildren);
                    for (int i = 0; i < numChildren; i++)
                    {
                        osErr = GetIndexedSubControl(tempControl, numChildren - i, &subControl); // retrieve the subcontrol in order by zorder
                        // //WEBRTC_LOG(kTraceDebug, "IBM GetIndexedSubControls=%d : %d", osErr, __LINE__);
                        if ( subControl == lastControl ) // break because of zorder

                        {
                            // //WEBRTC_LOG(kTraceDebug, "IBM breaking because of zorder %d", __LINE__);
                            break;
                        }

                        if (!IsControlVisible(subControl)) // dont' clip invisible controls

                        {
                            // //WEBRTC_LOG(kTraceDebug, "IBM continue. Control is not visible %d", __LINE__);
                            continue;
                        }

                        if(!subControl) continue;

                        osStatus = GetControlRegion(subControl, kControlStructureMetaPart, tempRgn); //get the region of the current control and union to childrg
                        // //WEBRTC_LOG(kTraceDebug, "IBM GetControlRegion=%d %d", osStatus, __LINE__);
                        CheckValidRegion(tempRgn);
                        if(osStatus != 0)
                        {
                            // //WEBRTC_LOG(kTraceDebug, "IBM ERROR! osStatus=%d. Continuing. %d", osStatus, __LINE__);
                            continue;
                        }
                        if(!tempRgn)
                        {
                            // //WEBRTC_LOG(kTraceDebug, "IBM ERROR! !tempRgn %d", osStatus, __LINE__);
                            continue;
                        }

                        osStatus = HIViewConvertRegion(tempRgn, subControl, rootControl);
                        CheckValidRegion(tempRgn);
                        // //WEBRTC_LOG(kTraceDebug, "IBM HIViewConvertRegion=%d %d", osStatus, __LINE__);
                        if(osStatus != 0)
                        {
                            // //WEBRTC_LOG(kTraceDebug, "IBM ERROR! osStatus=%d. Continuing. %d", osStatus, __LINE__);
                            continue;
                        }
                        if(!rootControl)
                        {
                            // //WEBRTC_LOG(kTraceDebug, "IBM ERROR! !rootControl %d", osStatus, __LINE__);
                            continue;
                        }

                        UnionRgn(tempRgn, childRgn, childRgn);
                        CheckValidRegion(tempRgn);
                        CheckValidRegion(childRgn);
                        CheckValidRegion(visibleRgn);
                        if(!childRgn)
                        {
                            // //WEBRTC_LOG(kTraceDebug, "IBM ERROR! !childRgn %d", osStatus, __LINE__);
                            continue;
                        }

                    }  // next child control
                }
                lastControl = tempControl;
                GetSuperControl(tempControl, &subControl);
                tempControl = subControl;
            }

            DiffRgn(visibleRgn, childRgn, visibleRgn);
            CheckValidRegion(visibleRgn);
            CheckValidRegion(childRgn);
            DisposeRgn(childRgn);
        }
        else
        {
            CopyRgn(tempRgn, visibleRgn);
            CheckValidRegion(tempRgn);
            CheckValidRegion(visibleRgn);
        }
        DisposeRgn(tempRgn);
    }

    //WEBRTC_LOG(kTraceDebug, "Leaving CalculateVisibleRegion()");
    //_aglCritPtr->Leave();
    return 0;
}

bool VideoRenderAGL::CheckValidRegion(RgnHandle rHandle)
{

    Handle hndSize = (Handle)rHandle;
    long size = GetHandleSize(hndSize);
    if(0 == size)
    {

        OSErr memErr = MemError();
        if(noErr != memErr)
        {
            // //WEBRTC_LOG(kTraceError, "IBM ERROR Could not get size of handle. MemError() returned %d", memErr);
        }
        else
        {
            // //WEBRTC_LOG(kTraceError, "IBM ERROR Could not get size of handle yet MemError() returned noErr");
        }

    }
    else
    {
        // //WEBRTC_LOG(kTraceDebug, "IBM handleSize = %d", size);
    }

    if(false == IsValidRgnHandle(rHandle))
    {
        // //WEBRTC_LOG(kTraceError, "IBM ERROR Invalid Region found : $%d", rHandle);
        assert(false);
    }

    int err = QDError();
    switch(err)
    {
        case 0:
        break;
        case -147:
        //WEBRTC_LOG(kTraceError, "ERROR region too big");
        assert(false);
        break;

        case -149:
        //WEBRTC_LOG(kTraceError, "ERROR not enough stack");
        assert(false);
        break;

        default:
        //WEBRTC_LOG(kTraceError, "ERROR Unknown QDError %d", err);
        assert(false);
        break;
    }

    return true;
}

int VideoRenderAGL::ChangeWindow(void* newWindowRef)
{

    LockAGLCntx();

    UnlockAGLCntx();
    return -1;
}

int32_t VideoRenderAGL::StartRender()
{

    LockAGLCntx();
    const unsigned int MONITOR_FREQ = 60;
    if(TRUE == _renderingIsPaused)
    {
        //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s:%d Rendering is paused. Restarting now", __FUNCTION__, __LINE__);

        // we already have the thread. Most likely StopRender() was called and they were paused
        if(FALSE == _screenUpdateThread->Start())
        {
            //WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, _id, "%s:%d Failed to start screenUpdateThread", __FUNCTION__, __LINE__);
            UnlockAGLCntx();
            return -1;
        }
        _screenUpdateThread->SetPriority(rtc::kRealtimePriority);
        if(FALSE == _screenUpdateEvent->StartTimer(true, 1000/MONITOR_FREQ))
        {
            //WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, _id, "%s:%d Failed to start screenUpdateEvent", __FUNCTION__, __LINE__);
            UnlockAGLCntx();
            return -1;
        }

        return 0;
    }

    _screenUpdateThread.reset(
        new rtc::PlatformThread(ScreenUpdateThreadProc, this, "ScreenUpdate"));
    _screenUpdateEvent = EventWrapper::Create();

    if (!_screenUpdateThread)
    {
        //WEBRTC_TRACE(kTraceError, kTraceVideoRenderer, _id, "%s:%d Failed to start screenUpdateThread", __FUNCTION__, __LINE__);
        UnlockAGLCntx();
        return -1;
    }

    _screenUpdateThread->Start();
    _screenUpdateThread->SetPriority(rtc::kRealtimePriority);
    _screenUpdateEvent->StartTimer(true, 1000/MONITOR_FREQ);

    //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s:%d Started screenUpdateThread", __FUNCTION__, __LINE__);

    UnlockAGLCntx();
    return 0;
}

int32_t VideoRenderAGL::StopRender()
{
    LockAGLCntx();

    if(!_screenUpdateThread || !_screenUpdateEvent)
    {
        _renderingIsPaused = TRUE;
        UnlockAGLCntx();
        return 0;
    }

    if(FALSE == _screenUpdateThread->Stop() || FALSE == _screenUpdateEvent->StopTimer())
    {
        _renderingIsPaused = FALSE;
        //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s:%d Could not stop either: screenUpdateThread or screenUpdateEvent", __FUNCTION__, __LINE__);
        UnlockAGLCntx();
        return -1;
    }

    _renderingIsPaused = TRUE;

    //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s:%d Stopped screenUpdateThread", __FUNCTION__, __LINE__);
    UnlockAGLCntx();
    return 0;
}

int32_t VideoRenderAGL::DeleteAGLChannel(const uint32_t streamID)
{

    LockAGLCntx();

    std::map<int, VideoChannelAGL*>::iterator it;
    it = _aglChannels.begin();

    while (it != _aglChannels.end())
    {
        VideoChannelAGL* channel = it->second;
        //WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _id, "%s:%d Deleting channel %d", __FUNCTION__, __LINE__, streamID);
        delete channel;
        it++;
    }
    _aglChannels.clear();

    UnlockAGLCntx();
    return 0;
}

int32_t VideoRenderAGL::GetChannelProperties(const uint16_t streamId,
                                             uint32_t& zOrder,
                                             float& left,
                                             float& top,
                                             float& right,
                                             float& bottom)
{

    LockAGLCntx();
    UnlockAGLCntx();
    return -1;

}

void VideoRenderAGL::LockAGLCntx()
{
    _renderCritSec.Enter();
}
void VideoRenderAGL::UnlockAGLCntx()
{
    _renderCritSec.Leave();
}

}  // namespace webrtc

#endif   // CARBON_RENDERING