summaryrefslogtreecommitdiff
path: root/dom/plugins/base/nsNPAPIPluginInstance.cpp
blob: 4b211ed7ef9c6418be0f12197a02cfe9acbe662b (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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/DebugOnly.h"

#ifdef MOZ_WIDGET_ANDROID
// For ScreenOrientation.h and Hal.h
#include "base/basictypes.h"
#endif

#include "mozilla/Logging.h"
#include "prmem.h"
#include "nscore.h"
#include "prenv.h"

#include "nsNPAPIPluginInstance.h"
#include "nsNPAPIPlugin.h"
#include "nsNPAPIPluginStreamListener.h"
#include "nsPluginHost.h"
#include "nsPluginLogging.h"
#include "nsContentUtils.h"
#include "nsPluginInstanceOwner.h"

#include "nsThreadUtils.h"
#include "nsIDOMElement.h"
#include "nsIDocument.h"
#include "nsIDocShell.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptContext.h"
#include "nsDirectoryServiceDefs.h"
#include "nsJSNPRuntime.h"
#include "nsPluginStreamListenerPeer.h"
#include "nsSize.h"
#include "nsNetCID.h"
#include "nsIContent.h"
#include "nsVersionComparator.h"
#include "mozilla/Preferences.h"
#include "mozilla/Unused.h"
#include "nsILoadContext.h"
#include "mozilla/dom/HTMLObjectElementBinding.h"
#include "AudioChannelService.h"

using namespace mozilla;
using namespace mozilla::dom;

#ifdef MOZ_WIDGET_ANDROID
#include "ANPBase.h"
#include <android/log.h>
#include "android_npapi.h"
#include "mozilla/Mutex.h"
#include "mozilla/CondVar.h"
#include "mozilla/dom/ScreenOrientation.h"
#include "mozilla/Hal.h"
#include "GLContextProvider.h"
#include "GLContext.h"
#include "TexturePoolOGL.h"
#include "SurfaceTypes.h"
#include "EGLUtils.h"

using namespace mozilla;
using namespace mozilla::gl;

typedef nsNPAPIPluginInstance::VideoInfo VideoInfo;

class PluginEventRunnable : public Runnable
{
public:
  PluginEventRunnable(nsNPAPIPluginInstance* instance, ANPEvent* event)
    : mInstance(instance), mEvent(*event), mCanceled(false) {}

  virtual nsresult Run() {
    if (mCanceled)
      return NS_OK;

    mInstance->HandleEvent(&mEvent, nullptr);
    mInstance->PopPostedEvent(this);
    return NS_OK;
  }

  void Cancel() { mCanceled = true; }
private:
  nsNPAPIPluginInstance* mInstance;
  ANPEvent mEvent;
  bool mCanceled;
};

static RefPtr<GLContext> sPluginContext = nullptr;

static bool EnsureGLContext()
{
  if (!sPluginContext) {
    const auto flags = CreateContextFlags::REQUIRE_COMPAT_PROFILE;
    nsCString discardedFailureId;
    sPluginContext = GLContextProvider::CreateHeadless(flags, &discardedFailureId);
  }

  return sPluginContext != nullptr;
}

static std::map<NPP, nsNPAPIPluginInstance*> sPluginNPPMap;

#endif

using namespace mozilla;
using namespace mozilla::plugins::parent;
using namespace mozilla::layers;

static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID);

NS_IMPL_ISUPPORTS(nsNPAPIPluginInstance, nsIAudioChannelAgentCallback)

nsNPAPIPluginInstance::nsNPAPIPluginInstance()
  : mDrawingModel(kDefaultDrawingModel)
#ifdef MOZ_WIDGET_ANDROID
  , mANPDrawingModel(0)
  , mFullScreenOrientation(dom::eScreenOrientation_LandscapePrimary)
  , mWakeLocked(false)
  , mFullScreen(false)
  , mOriginPos(gl::OriginPos::TopLeft)
#endif
  , mRunning(NOT_STARTED)
  , mWindowless(false)
  , mTransparent(false)
  , mCached(false)
  , mUsesDOMForCursor(false)
  , mInPluginInitCall(false)
  , mPlugin(nullptr)
  , mMIMEType(nullptr)
  , mOwner(nullptr)
#ifdef XP_MACOSX
  , mCurrentPluginEvent(nullptr)
#endif
#ifdef MOZ_WIDGET_ANDROID
  , mOnScreen(true)
#endif
  , mHaveJavaC2PJSObjectQuirk(false)
  , mCachedParamLength(0)
  , mCachedParamNames(nullptr)
  , mCachedParamValues(nullptr)
  , mMuted(false)
{
  mNPP.pdata = nullptr;
  mNPP.ndata = this;

  PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance ctor: this=%p\n",this));

#ifdef MOZ_WIDGET_ANDROID
  sPluginNPPMap[&mNPP] = this;
#endif
}

nsNPAPIPluginInstance::~nsNPAPIPluginInstance()
{
  PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance dtor: this=%p\n",this));

#ifdef MOZ_WIDGET_ANDROID
  sPluginNPPMap.erase(&mNPP);
#endif

  if (mMIMEType) {
    PR_Free((void *)mMIMEType);
    mMIMEType = nullptr;
  }

  if (!mCachedParamValues || !mCachedParamNames) {
    return;
  }
  MOZ_ASSERT(mCachedParamValues && mCachedParamNames);

  for (uint32_t i = 0; i < mCachedParamLength; i++) {
    if (mCachedParamNames[i]) {
      free(mCachedParamNames[i]);
      mCachedParamNames[i] = nullptr;
    }
    if (mCachedParamValues[i]) {
      free(mCachedParamValues[i]);
      mCachedParamValues[i] = nullptr;
    }
  }

  free(mCachedParamNames);
  mCachedParamNames = nullptr;

  free(mCachedParamValues);
  mCachedParamValues = nullptr;
}

uint32_t nsNPAPIPluginInstance::gInUnsafePluginCalls = 0;

void
nsNPAPIPluginInstance::Destroy()
{
  Stop();
  mPlugin = nullptr;
  mAudioChannelAgent = nullptr;

#if MOZ_WIDGET_ANDROID
  if (mContentSurface)
    mContentSurface->SetFrameAvailableCallback(nullptr);

  mContentSurface = nullptr;

  std::map<void*, VideoInfo*>::iterator it;
  for (it = mVideos.begin(); it != mVideos.end(); it++) {
    it->second->mSurfaceTexture->SetFrameAvailableCallback(nullptr);
    delete it->second;
  }
  mVideos.clear();
  SetWakeLock(false);
#endif
}

TimeStamp
nsNPAPIPluginInstance::StopTime()
{
  return mStopTime;
}

nsresult nsNPAPIPluginInstance::Initialize(nsNPAPIPlugin *aPlugin, nsPluginInstanceOwner* aOwner, const nsACString& aMIMEType)
{
  PROFILER_LABEL_FUNC(js::ProfileEntry::Category::OTHER);
  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::Initialize this=%p\n",this));

  NS_ENSURE_ARG_POINTER(aPlugin);
  NS_ENSURE_ARG_POINTER(aOwner);

  mPlugin = aPlugin;
  mOwner = aOwner;

  if (!aMIMEType.IsEmpty()) {
    mMIMEType = ToNewCString(aMIMEType);
  }

  return Start();
}

nsresult nsNPAPIPluginInstance::Stop()
{
  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::Stop this=%p\n",this));

  // Make sure the plugin didn't leave popups enabled.
  if (mPopupStates.Length() > 0) {
    nsCOMPtr<nsPIDOMWindowOuter> window = GetDOMWindow();

    if (window) {
      window->PopPopupControlState(openAbused);
    }
  }

  if (RUNNING != mRunning) {
    return NS_OK;
  }

  // clean up all outstanding timers
  for (uint32_t i = mTimers.Length(); i > 0; i--)
    UnscheduleTimer(mTimers[i - 1]->id);

  // If there's code from this plugin instance on the stack, delay the
  // destroy.
  if (PluginDestructionGuard::DelayDestroy(this)) {
    return NS_OK;
  }

  // Make sure we lock while we're writing to mRunning after we've
  // started as other threads might be checking that inside a lock.
  {
    AsyncCallbackAutoLock lock;
    mRunning = DESTROYING;
    mStopTime = TimeStamp::Now();
  }

  OnPluginDestroy(&mNPP);

  // clean up open streams
  while (mStreamListeners.Length() > 0) {
    RefPtr<nsNPAPIPluginStreamListener> currentListener(mStreamListeners[0]);
    currentListener->CleanUpStream(NPRES_USER_BREAK);
    mStreamListeners.RemoveElement(currentListener);
  }

  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  NPError error = NPERR_GENERIC_ERROR;
  if (pluginFunctions->destroy) {
    NPSavedData *sdata = 0;

    NS_TRY_SAFE_CALL_RETURN(error, (*pluginFunctions->destroy)(&mNPP, &sdata), this,
                            NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);

    NPP_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
                   ("NPP Destroy called: this=%p, npp=%p, return=%d\n", this, &mNPP, error));
  }
  mRunning = DESTROYED;

#if MOZ_WIDGET_ANDROID
  for (uint32_t i = 0; i < mPostedEvents.Length(); i++) {
    mPostedEvents[i]->Cancel();
  }

  mPostedEvents.Clear();
#endif

  nsJSNPRuntime::OnPluginDestroy(&mNPP);

  if (error != NPERR_NO_ERROR)
    return NS_ERROR_FAILURE;
  else
    return NS_OK;
}

already_AddRefed<nsPIDOMWindowOuter>
nsNPAPIPluginInstance::GetDOMWindow()
{
  if (!mOwner)
    return nullptr;

  RefPtr<nsPluginInstanceOwner> kungFuDeathGrip(mOwner);

  nsCOMPtr<nsIDocument> doc;
  kungFuDeathGrip->GetDocument(getter_AddRefs(doc));
  if (!doc)
    return nullptr;

  RefPtr<nsPIDOMWindowOuter> window = doc->GetWindow();

  return window.forget();
}

nsresult
nsNPAPIPluginInstance::GetTagType(nsPluginTagType *result)
{
  if (!mOwner) {
    return NS_ERROR_FAILURE;
  }

  return mOwner->GetTagType(result);
}

nsresult
nsNPAPIPluginInstance::GetMode(int32_t *result)
{
  if (mOwner)
    return mOwner->GetMode(result);
  else
    return NS_ERROR_FAILURE;
}

nsTArray<nsNPAPIPluginStreamListener*>*
nsNPAPIPluginInstance::StreamListeners()
{
  return &mStreamListeners;
}

nsTArray<nsPluginStreamListenerPeer*>*
nsNPAPIPluginInstance::FileCachedStreamListeners()
{
  return &mFileCachedStreamListeners;
}

nsresult
nsNPAPIPluginInstance::Start()
{
  if (mRunning == RUNNING) {
    return NS_OK;
  }

  if (!mOwner) {
    MOZ_ASSERT(false, "Should not be calling Start() on unowned plugin.");
    return NS_ERROR_FAILURE;
  }

  PluginDestructionGuard guard(this);

  nsTArray<MozPluginParameter> attributes;
  nsTArray<MozPluginParameter> params;

  nsPluginTagType tagtype;
  nsresult rv = GetTagType(&tagtype);
  if (NS_SUCCEEDED(rv)) {
    mOwner->GetAttributes(attributes);
    mOwner->GetParameters(params);
  } else {
    MOZ_ASSERT(false, "Failed to get tag type.");
  }

  mCachedParamLength = attributes.Length() + 1 + params.Length();

  // We add an extra entry "PARAM" as a separator between the attribute
  // and param values, but we don't count it if there are no <param> entries.
  // Legacy behavior quirk.
  uint32_t quirkParamLength = params.Length() ?
                                mCachedParamLength : attributes.Length();

  mCachedParamNames = (char**)moz_xmalloc(sizeof(char*) * mCachedParamLength);
  mCachedParamValues = (char**)moz_xmalloc(sizeof(char*) * mCachedParamLength);

  for (uint32_t i = 0; i < attributes.Length(); i++) {
    mCachedParamNames[i] = ToNewUTF8String(attributes[i].mName);
    mCachedParamValues[i] = ToNewUTF8String(attributes[i].mValue);
  }

  // Android expects and empty string instead of null.
  mCachedParamNames[attributes.Length()] = ToNewUTF8String(NS_LITERAL_STRING("PARAM"));
  #ifdef MOZ_WIDGET_ANDROID
    mCachedParamValues[attributes.Length()] = ToNewUTF8String(NS_LITERAL_STRING(""));
  #else
    mCachedParamValues[attributes.Length()] = nullptr;
  #endif

  for (uint32_t i = 0, pos = attributes.Length() + 1; i < params.Length(); i ++) {
    mCachedParamNames[pos] = ToNewUTF8String(params[i].mName);
    mCachedParamValues[pos] = ToNewUTF8String(params[i].mValue);
    pos++;
  }

  int32_t       mode;
  const char*   mimetype;
  NPError       error = NPERR_GENERIC_ERROR;

  GetMode(&mode);
  GetMIMEType(&mimetype);

  CheckJavaC2PJSObjectQuirk(quirkParamLength, mCachedParamNames, mCachedParamValues);

  bool oldVal = mInPluginInitCall;
  mInPluginInitCall = true;

  // Need this on the stack before calling NPP_New otherwise some callbacks that
  // the plugin may make could fail (NPN_HasProperty, for example).
  NPPAutoPusher autopush(&mNPP);

  if (!mPlugin)
    return NS_ERROR_FAILURE;

  PluginLibrary* library = mPlugin->GetLibrary();
  if (!library)
    return NS_ERROR_FAILURE;

  // Mark this instance as running before calling NPP_New because the plugin may
  // call other NPAPI functions, like NPN_GetURLNotify, that assume this is set
  // before returning. If the plugin returns failure, we'll clear it out below.
  mRunning = RUNNING;

  nsresult newResult = library->NPP_New((char*)mimetype, &mNPP, (uint16_t)mode,
                                        quirkParamLength, mCachedParamNames,
                                        mCachedParamValues, nullptr, &error);
  mInPluginInitCall = oldVal;

  NPP_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
  ("NPP New called: this=%p, npp=%p, mime=%s, mode=%d, argc=%d, return=%d\n",
  this, &mNPP, mimetype, mode, quirkParamLength, error));

  if (NS_FAILED(newResult) || error != NPERR_NO_ERROR) {
    mRunning = DESTROYED;
    nsJSNPRuntime::OnPluginDestroy(&mNPP);
    return NS_ERROR_FAILURE;
  }

  return newResult;
}

nsresult nsNPAPIPluginInstance::SetWindow(NPWindow* window)
{
  // NPAPI plugins don't want a SetWindow(nullptr).
  if (!window || RUNNING != mRunning)
    return NS_OK;

#if MOZ_WIDGET_GTK
  // bug 108347, flash plugin on linux doesn't like window->width <=
  // 0, but Java needs wants this call.
  if (window && window->type == NPWindowTypeWindow &&
      (window->width <= 0 || window->height <= 0) &&
      (nsPluginHost::GetSpecialType(nsDependentCString(mMIMEType)) !=
       nsPluginHost::eSpecialType_Java)) {
    return NS_OK;
  }
#endif

  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  if (pluginFunctions->setwindow) {
    PluginDestructionGuard guard(this);

    // XXX Turns out that NPPluginWindow and NPWindow are structurally
    // identical (on purpose!), so there's no need to make a copy.

    PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::SetWindow (about to call it) this=%p\n",this));

    bool oldVal = mInPluginInitCall;
    mInPluginInitCall = true;

    NPPAutoPusher nppPusher(&mNPP);

    NPError error;
    NS_TRY_SAFE_CALL_RETURN(error, (*pluginFunctions->setwindow)(&mNPP, (NPWindow*)window), this,
                            NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);
    // 'error' is only used if this is a logging-enabled build.
    // That is somewhat complex to check, so we just use "unused"
    // to suppress any compiler warnings in build configurations
    // where the logging is a no-op.
    mozilla::Unused << error;

    mInPluginInitCall = oldVal;

    NPP_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
    ("NPP SetWindow called: this=%p, [x=%d,y=%d,w=%d,h=%d], clip[t=%d,b=%d,l=%d,r=%d], return=%d\n",
    this, window->x, window->y, window->width, window->height,
    window->clipRect.top, window->clipRect.bottom, window->clipRect.left, window->clipRect.right, error));
  }
  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::NewStreamFromPlugin(const char* type, const char* target,
                                           nsIOutputStream* *result)
{
  nsPluginStreamToFile* stream = new nsPluginStreamToFile(target, mOwner);
  return stream->QueryInterface(kIOutputStreamIID, (void**)result);
}

nsresult
nsNPAPIPluginInstance::NewStreamListener(const char* aURL, void* notifyData,
                                         nsNPAPIPluginStreamListener** listener)
{
  RefPtr<nsNPAPIPluginStreamListener> sl = new nsNPAPIPluginStreamListener(this, notifyData, aURL);

  mStreamListeners.AppendElement(sl);

  sl.forget(listener);

  return NS_OK;
}

nsresult nsNPAPIPluginInstance::Print(NPPrint* platformPrint)
{
  NS_ENSURE_TRUE(platformPrint, NS_ERROR_NULL_POINTER);

  PluginDestructionGuard guard(this);

  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  NPPrint* thePrint = (NPPrint *)platformPrint;

  // to be compatible with the older SDK versions and to match what
  // NPAPI and other browsers do, overwrite |window.type| field with one
  // more copy of |platformPrint|. See bug 113264
  uint16_t sdkmajorversion = (pluginFunctions->version & 0xff00)>>8;
  uint16_t sdkminorversion = pluginFunctions->version & 0x00ff;
  if ((sdkmajorversion == 0) && (sdkminorversion < 11)) {
    // Let's copy platformPrint bytes over to where it was supposed to be
    // in older versions -- four bytes towards the beginning of the struct
    // but we should be careful about possible misalignments
    if (sizeof(NPWindowType) >= sizeof(void *)) {
      void* source = thePrint->print.embedPrint.platformPrint;
      void** destination = (void **)&(thePrint->print.embedPrint.window.type);
      *destination = source;
    } else {
      NS_ERROR("Incompatible OS for assignment");
    }
  }

  if (pluginFunctions->print)
      NS_TRY_SAFE_CALL_VOID((*pluginFunctions->print)(&mNPP, thePrint), this,
                            NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);

  NPP_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
  ("NPP PrintProc called: this=%p, pDC=%p, [x=%d,y=%d,w=%d,h=%d], clip[t=%d,b=%d,l=%d,r=%d]\n",
  this,
  platformPrint->print.embedPrint.platformPrint,
  platformPrint->print.embedPrint.window.x,
  platformPrint->print.embedPrint.window.y,
  platformPrint->print.embedPrint.window.width,
  platformPrint->print.embedPrint.window.height,
  platformPrint->print.embedPrint.window.clipRect.top,
  platformPrint->print.embedPrint.window.clipRect.bottom,
  platformPrint->print.embedPrint.window.clipRect.left,
  platformPrint->print.embedPrint.window.clipRect.right));

  return NS_OK;
}

nsresult nsNPAPIPluginInstance::HandleEvent(void* event, int16_t* result,
                                            NSPluginCallReentry aSafeToReenterGecko)
{
  if (RUNNING != mRunning)
    return NS_OK;

  PROFILER_LABEL_FUNC(js::ProfileEntry::Category::OTHER);

  if (!event)
    return NS_ERROR_FAILURE;

  PluginDestructionGuard guard(this);

  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  int16_t tmpResult = kNPEventNotHandled;

  if (pluginFunctions->event) {
#ifdef XP_MACOSX
    mCurrentPluginEvent = event;
#endif
#if defined(XP_WIN)
    NS_TRY_SAFE_CALL_RETURN(tmpResult, (*pluginFunctions->event)(&mNPP, event), this,
                            aSafeToReenterGecko);
#else
    MAIN_THREAD_JNI_REF_GUARD;
    tmpResult = (*pluginFunctions->event)(&mNPP, event);
#endif
    NPP_PLUGIN_LOG(PLUGIN_LOG_NOISY,
      ("NPP HandleEvent called: this=%p, npp=%p, event=%p, return=%d\n",
      this, &mNPP, event, tmpResult));

    if (result)
      *result = tmpResult;
#ifdef XP_MACOSX
    mCurrentPluginEvent = nullptr;
#endif
  }

  return NS_OK;
}

nsresult nsNPAPIPluginInstance::GetValueFromPlugin(NPPVariable variable, void* value)
{
  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  nsresult rv = NS_ERROR_FAILURE;

  if (pluginFunctions->getvalue && RUNNING == mRunning) {
    PluginDestructionGuard guard(this);

    NPError pluginError = NPERR_GENERIC_ERROR;
    NS_TRY_SAFE_CALL_RETURN(pluginError, (*pluginFunctions->getvalue)(&mNPP, variable, value), this,
                            NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);
    NPP_PLUGIN_LOG(PLUGIN_LOG_NORMAL,
    ("NPP GetValue called: this=%p, npp=%p, var=%d, value=%d, return=%d\n",
    this, &mNPP, variable, value, pluginError));

    if (pluginError == NPERR_NO_ERROR) {
      rv = NS_OK;
    }
  }

  return rv;
}

nsNPAPIPlugin* nsNPAPIPluginInstance::GetPlugin()
{
  return mPlugin;
}

nsresult nsNPAPIPluginInstance::GetNPP(NPP* aNPP)
{
  if (aNPP)
    *aNPP = &mNPP;
  else
    return NS_ERROR_NULL_POINTER;

  return NS_OK;
}

NPError nsNPAPIPluginInstance::SetWindowless(bool aWindowless)
{
  mWindowless = aWindowless;

  if (mMIMEType) {
    // bug 558434 - Prior to 3.6.4, we assumed windowless was transparent.
    // Silverlight apparently relied on this quirk, so we default to
    // transparent unless they specify otherwise after setting the windowless
    // property. (Last tested version: sl 4.0).
    // Changes to this code should be matched with changes in
    // PluginInstanceChild::InitQuirksMode.
    if (nsPluginHost::GetSpecialType(nsDependentCString(mMIMEType)) ==
        nsPluginHost::eSpecialType_Silverlight) {
      mTransparent = true;
    }
  }

  return NPERR_NO_ERROR;
}

NPError nsNPAPIPluginInstance::SetTransparent(bool aTransparent)
{
  mTransparent = aTransparent;
  return NPERR_NO_ERROR;
}

NPError nsNPAPIPluginInstance::SetUsesDOMForCursor(bool aUsesDOMForCursor)
{
  mUsesDOMForCursor = aUsesDOMForCursor;
  return NPERR_NO_ERROR;
}

bool
nsNPAPIPluginInstance::UsesDOMForCursor()
{
  return mUsesDOMForCursor;
}

void nsNPAPIPluginInstance::SetDrawingModel(NPDrawingModel aModel)
{
  mDrawingModel = aModel;
}

void nsNPAPIPluginInstance::RedrawPlugin()
{
  mOwner->RedrawPlugin();
}

#if defined(XP_MACOSX)
void nsNPAPIPluginInstance::SetEventModel(NPEventModel aModel)
{
  // the event model needs to be set for the object frame immediately
  if (!mOwner) {
    NS_WARNING("Trying to set event model without a plugin instance owner!");
    return;
  }

  mOwner->SetEventModel(aModel);
}
#endif

#if defined(MOZ_WIDGET_ANDROID)

static void SendLifecycleEvent(nsNPAPIPluginInstance* aInstance, uint32_t aAction)
{
  ANPEvent event;
  event.inSize = sizeof(ANPEvent);
  event.eventType = kLifecycle_ANPEventType;
  event.data.lifecycle.action = aAction;
  aInstance->HandleEvent(&event, nullptr);
}

void nsNPAPIPluginInstance::NotifyForeground(bool aForeground)
{
  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::SetForeground this=%p\n foreground=%d",this, aForeground));
  if (RUNNING != mRunning)
    return;

  SendLifecycleEvent(this, aForeground ? kResume_ANPLifecycleAction : kPause_ANPLifecycleAction);
}

void nsNPAPIPluginInstance::NotifyOnScreen(bool aOnScreen)
{
  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::SetOnScreen this=%p\n onScreen=%d",this, aOnScreen));
  if (RUNNING != mRunning || mOnScreen == aOnScreen)
    return;

  mOnScreen = aOnScreen;
  SendLifecycleEvent(this, aOnScreen ? kOnScreen_ANPLifecycleAction : kOffScreen_ANPLifecycleAction);
}

void nsNPAPIPluginInstance::MemoryPressure()
{
  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::MemoryPressure this=%p\n",this));
  if (RUNNING != mRunning)
    return;

  SendLifecycleEvent(this, kFreeMemory_ANPLifecycleAction);
}

void nsNPAPIPluginInstance::NotifyFullScreen(bool aFullScreen)
{
  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance::NotifyFullScreen this=%p\n",this));

  if (RUNNING != mRunning || mFullScreen == aFullScreen)
    return;

  mFullScreen = aFullScreen;
  SendLifecycleEvent(this, mFullScreen ? kEnterFullScreen_ANPLifecycleAction : kExitFullScreen_ANPLifecycleAction);

  if (mFullScreen && mFullScreenOrientation != dom::eScreenOrientation_None) {
    java::GeckoAppShell::LockScreenOrientation(mFullScreenOrientation);
  }
}

void nsNPAPIPluginInstance::NotifySize(nsIntSize size)
{
  if (kOpenGL_ANPDrawingModel != GetANPDrawingModel() ||
      size == mCurrentSize)
    return;

  mCurrentSize = size;

  ANPEvent event;
  event.inSize = sizeof(ANPEvent);
  event.eventType = kDraw_ANPEventType;
  event.data.draw.model = kOpenGL_ANPDrawingModel;
  event.data.draw.data.surfaceSize.width = size.width;
  event.data.draw.data.surfaceSize.height = size.height;

  HandleEvent(&event, nullptr);
}

void nsNPAPIPluginInstance::SetANPDrawingModel(uint32_t aModel)
{
  mANPDrawingModel = aModel;
}

void* nsNPAPIPluginInstance::GetJavaSurface()
{
  void* surface = nullptr;
  nsresult rv = GetValueFromPlugin(kJavaSurface_ANPGetValue, &surface);
  if (NS_FAILED(rv))
    return nullptr;

  return surface;
}

void nsNPAPIPluginInstance::PostEvent(void* event)
{
  PluginEventRunnable *r = new PluginEventRunnable(this, (ANPEvent*)event);
  mPostedEvents.AppendElement(RefPtr<PluginEventRunnable>(r));

  NS_DispatchToMainThread(r);
}

void nsNPAPIPluginInstance::SetFullScreenOrientation(uint32_t orientation)
{
  if (mFullScreenOrientation == orientation)
    return;

  uint32_t oldOrientation = mFullScreenOrientation;
  mFullScreenOrientation = orientation;

  if (mFullScreen) {
    // We're already fullscreen so immediately apply the orientation change

    if (mFullScreenOrientation != dom::eScreenOrientation_None) {
      java::GeckoAppShell::LockScreenOrientation(mFullScreenOrientation);
    } else if (oldOrientation != dom::eScreenOrientation_None) {
      // We applied an orientation when we entered fullscreen, but
      // we don't want it anymore
      java::GeckoAppShell::UnlockScreenOrientation();
    }
  }
}

void nsNPAPIPluginInstance::PopPostedEvent(PluginEventRunnable* r)
{
  mPostedEvents.RemoveElement(r);
}

void nsNPAPIPluginInstance::SetWakeLock(bool aLocked)
{
  if (aLocked == mWakeLocked)
    return;

  mWakeLocked = aLocked;
  hal::ModifyWakeLock(NS_LITERAL_STRING("screen"),
                      mWakeLocked ? hal::WAKE_LOCK_ADD_ONE : hal::WAKE_LOCK_REMOVE_ONE,
                      hal::WAKE_LOCK_NO_CHANGE);
}

GLContext* nsNPAPIPluginInstance::GLContext()
{
  if (!EnsureGLContext())
    return nullptr;

  return sPluginContext;
}

already_AddRefed<AndroidSurfaceTexture> nsNPAPIPluginInstance::CreateSurfaceTexture()
{
  if (!EnsureGLContext())
    return nullptr;

  GLuint texture = TexturePoolOGL::AcquireTexture();
  if (!texture)
    return nullptr;

  RefPtr<AndroidSurfaceTexture> surface = AndroidSurfaceTexture::Create(TexturePoolOGL::GetGLContext(),
                                                                        texture);
  if (!surface) {
    return nullptr;
  }

  nsCOMPtr<nsIRunnable> frameCallback = NewRunnableMethod(this, &nsNPAPIPluginInstance::OnSurfaceTextureFrameAvailable);
  surface->SetFrameAvailableCallback(frameCallback);
  return surface.forget();
}

void nsNPAPIPluginInstance::OnSurfaceTextureFrameAvailable()
{
  if (mRunning == RUNNING && mOwner)
    mOwner->Recomposite();
}

void* nsNPAPIPluginInstance::AcquireContentWindow()
{
  if (!mContentSurface) {
    mContentSurface = CreateSurfaceTexture();

    if (!mContentSurface)
      return nullptr;
  }

  return mContentSurface->NativeWindow();
}

AndroidSurfaceTexture*
nsNPAPIPluginInstance::AsSurfaceTexture()
{
  if (!mContentSurface)
    return nullptr;

  return mContentSurface;
}

void* nsNPAPIPluginInstance::AcquireVideoWindow()
{
  RefPtr<AndroidSurfaceTexture> surface = CreateSurfaceTexture();
  if (!surface) {
    return nullptr;
  }

  VideoInfo* info = new VideoInfo(surface);

  void* window = info->mSurfaceTexture->NativeWindow();
  mVideos.insert(std::pair<void*, VideoInfo*>(window, info));

  return window;
}

void nsNPAPIPluginInstance::ReleaseVideoWindow(void* window)
{
  std::map<void*, VideoInfo*>::iterator it = mVideos.find(window);
  if (it == mVideos.end())
    return;

  delete it->second;
  mVideos.erase(window);
}

void nsNPAPIPluginInstance::SetVideoDimensions(void* window, gfxRect aDimensions)
{
  std::map<void*, VideoInfo*>::iterator it;

  it = mVideos.find(window);
  if (it == mVideos.end())
    return;

  it->second->mDimensions = aDimensions;
}

void nsNPAPIPluginInstance::GetVideos(nsTArray<VideoInfo*>& aVideos)
{
  std::map<void*, VideoInfo*>::iterator it;
  for (it = mVideos.begin(); it != mVideos.end(); it++)
    aVideos.AppendElement(it->second);
}

nsNPAPIPluginInstance* nsNPAPIPluginInstance::GetFromNPP(NPP npp)
{
  std::map<NPP, nsNPAPIPluginInstance*>::iterator it;

  it = sPluginNPPMap.find(npp);
  if (it == sPluginNPPMap.end())
    return nullptr;

  return it->second;
}

#endif

nsresult nsNPAPIPluginInstance::GetDrawingModel(int32_t* aModel)
{
  *aModel = (int32_t)mDrawingModel;
  return NS_OK;
}

nsresult nsNPAPIPluginInstance::IsRemoteDrawingCoreAnimation(bool* aDrawing)
{
#ifdef XP_MACOSX
  if (!mPlugin)
      return NS_ERROR_FAILURE;

  PluginLibrary* library = mPlugin->GetLibrary();
  if (!library)
      return NS_ERROR_FAILURE;

  return library->IsRemoteDrawingCoreAnimation(&mNPP, aDrawing);
#else
  return NS_ERROR_FAILURE;
#endif
}

nsresult
nsNPAPIPluginInstance::ContentsScaleFactorChanged(double aContentsScaleFactor)
{
#if defined(XP_MACOSX) || defined(XP_WIN)
  if (!mPlugin)
      return NS_ERROR_FAILURE;

  PluginLibrary* library = mPlugin->GetLibrary();
  if (!library)
      return NS_ERROR_FAILURE;

  // We only need to call this if the plugin is running OOP.
  if (!library->IsOOP())
      return NS_OK;

  return library->ContentsScaleFactorChanged(&mNPP, aContentsScaleFactor);
#else
  return NS_ERROR_FAILURE;
#endif
}

nsresult
nsNPAPIPluginInstance::CSSZoomFactorChanged(float aCSSZoomFactor)
{
  if (RUNNING != mRunning)
    return NS_OK;

  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance informing plugin of CSS Zoom Factor change this=%p\n",this));

  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  if (!pluginFunctions->setvalue)
    return NS_ERROR_FAILURE;

  PluginDestructionGuard guard(this);

  NPError error;
  double value = static_cast<double>(aCSSZoomFactor);
  NS_TRY_SAFE_CALL_RETURN(error, (*pluginFunctions->setvalue)(&mNPP, NPNVCSSZoomFactor, &value), this,
                          NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);
  return (error == NPERR_NO_ERROR) ? NS_OK : NS_ERROR_FAILURE;
}

nsresult
nsNPAPIPluginInstance::GetJSObject(JSContext *cx, JSObject** outObject)
{
  if (mHaveJavaC2PJSObjectQuirk) {
    return NS_ERROR_FAILURE;
  }

  NPObject *npobj = nullptr;
  nsresult rv = GetValueFromPlugin(NPPVpluginScriptableNPObject, &npobj);
  if (NS_FAILED(rv) || !npobj)
    return NS_ERROR_FAILURE;

  *outObject = nsNPObjWrapper::GetNewOrUsed(&mNPP, cx, npobj);

  _releaseobject(npobj);

  return NS_OK;
}

void
nsNPAPIPluginInstance::SetCached(bool aCache)
{
  mCached = aCache;
}

bool
nsNPAPIPluginInstance::ShouldCache()
{
  return mCached;
}

nsresult
nsNPAPIPluginInstance::IsWindowless(bool* isWindowless)
{
#if defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
  // All OS X plugins are windowless.
  // On android, pre-honeycomb, all plugins are treated as windowless.
  *isWindowless = true;
#else
  *isWindowless = mWindowless;
#endif
  return NS_OK;
}

class MOZ_STACK_CLASS AutoPluginLibraryCall
{
public:
  explicit AutoPluginLibraryCall(nsNPAPIPluginInstance* aThis)
    : mThis(aThis), mGuard(aThis), mLibrary(nullptr)
  {
    nsNPAPIPlugin* plugin = mThis->GetPlugin();
    if (plugin)
      mLibrary = plugin->GetLibrary();
  }
  explicit operator bool() { return !!mLibrary; }
  PluginLibrary* operator->() { return mLibrary; }

private:
  nsNPAPIPluginInstance* mThis;
  PluginDestructionGuard mGuard;
  PluginLibrary* mLibrary;
};

nsresult
nsNPAPIPluginInstance::AsyncSetWindow(NPWindow* window)
{
  if (RUNNING != mRunning)
    return NS_OK;

  AutoPluginLibraryCall library(this);
  if (!library)
    return NS_ERROR_FAILURE;

  return library->AsyncSetWindow(&mNPP, window);
}

nsresult
nsNPAPIPluginInstance::GetImageContainer(ImageContainer**aContainer)
{
  *aContainer = nullptr;

  if (RUNNING != mRunning)
    return NS_OK;

  AutoPluginLibraryCall library(this);
  return !library ? NS_ERROR_FAILURE : library->GetImageContainer(&mNPP, aContainer);
}

nsresult
nsNPAPIPluginInstance::GetImageSize(nsIntSize* aSize)
{
  *aSize = nsIntSize(0, 0);

  if (RUNNING != mRunning)
    return NS_OK;

  AutoPluginLibraryCall library(this);
  return !library ? NS_ERROR_FAILURE : library->GetImageSize(&mNPP, aSize);
}

#if defined(XP_WIN)
nsresult
nsNPAPIPluginInstance::GetScrollCaptureContainer(ImageContainer**aContainer)
{
  *aContainer = nullptr;

  if (RUNNING != mRunning)
    return NS_OK;

  AutoPluginLibraryCall library(this);
  return !library ? NS_ERROR_FAILURE : library->GetScrollCaptureContainer(&mNPP, aContainer);
}
#endif

nsresult
nsNPAPIPluginInstance::HandledWindowedPluginKeyEvent(
                         const NativeEventData& aKeyEventData,
                         bool aIsConsumed)
{
  if (NS_WARN_IF(!mPlugin)) {
    return NS_ERROR_FAILURE;
  }

  PluginLibrary* library = mPlugin->GetLibrary();
  if (NS_WARN_IF(!library)) {
    return NS_ERROR_FAILURE;
  }
  return library->HandledWindowedPluginKeyEvent(&mNPP, aKeyEventData,
                                                aIsConsumed);
}

void
nsNPAPIPluginInstance::DidComposite()
{
  if (RUNNING != mRunning)
    return;

  AutoPluginLibraryCall library(this);
  library->DidComposite(&mNPP);
}

nsresult
nsNPAPIPluginInstance::NotifyPainted(void)
{
  NS_NOTREACHED("Dead code, shouldn't be called.");
  return NS_ERROR_NOT_IMPLEMENTED;
}

nsresult
nsNPAPIPluginInstance::GetIsOOP(bool* aIsAsync)
{
  AutoPluginLibraryCall library(this);
  if (!library)
    return NS_ERROR_FAILURE;

  *aIsAsync = library->IsOOP();
  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::SetBackgroundUnknown()
{
  if (RUNNING != mRunning)
    return NS_OK;

  AutoPluginLibraryCall library(this);
  if (!library)
    return NS_ERROR_FAILURE;

  return library->SetBackgroundUnknown(&mNPP);
}

nsresult
nsNPAPIPluginInstance::BeginUpdateBackground(nsIntRect* aRect,
                                             DrawTarget** aDrawTarget)
{
  if (RUNNING != mRunning)
    return NS_OK;

  AutoPluginLibraryCall library(this);
  if (!library)
    return NS_ERROR_FAILURE;

  return library->BeginUpdateBackground(&mNPP, *aRect, aDrawTarget);
}

nsresult
nsNPAPIPluginInstance::EndUpdateBackground(nsIntRect* aRect)
{
  if (RUNNING != mRunning)
    return NS_OK;

  AutoPluginLibraryCall library(this);
  if (!library)
    return NS_ERROR_FAILURE;

  return library->EndUpdateBackground(&mNPP, *aRect);
}

nsresult
nsNPAPIPluginInstance::IsTransparent(bool* isTransparent)
{
  *isTransparent = mTransparent;
  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::GetFormValue(nsAString& aValue)
{
  aValue.Truncate();

  char *value = nullptr;
  nsresult rv = GetValueFromPlugin(NPPVformValue, &value);
  if (NS_FAILED(rv) || !value)
    return NS_ERROR_FAILURE;

  CopyUTF8toUTF16(value, aValue);

  // NPPVformValue allocates with NPN_MemAlloc(), which uses
  // nsMemory.
  free(value);

  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::PushPopupsEnabledState(bool aEnabled)
{
  nsCOMPtr<nsPIDOMWindowOuter> window = GetDOMWindow();
  if (!window)
    return NS_ERROR_FAILURE;

  PopupControlState oldState =
    window->PushPopupControlState(aEnabled ? openAllowed : openAbused,
                                  true);

  if (!mPopupStates.AppendElement(oldState)) {
    // Appending to our state stack failed, pop what we just pushed.
    window->PopPopupControlState(oldState);
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::PopPopupsEnabledState()
{
  int32_t last = mPopupStates.Length() - 1;

  if (last < 0) {
    // Nothing to pop.
    return NS_OK;
  }

  nsCOMPtr<nsPIDOMWindowOuter> window = GetDOMWindow();
  if (!window)
    return NS_ERROR_FAILURE;

  PopupControlState &oldState = mPopupStates[last];

  window->PopPopupControlState(oldState);

  mPopupStates.RemoveElementAt(last);

  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::GetPluginAPIVersion(uint16_t* version)
{
  NS_ENSURE_ARG_POINTER(version);

  if (!mPlugin)
    return NS_ERROR_FAILURE;

  if (!mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  *version = pluginFunctions->version;

  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::PrivateModeStateChanged(bool enabled)
{
  if (RUNNING != mRunning)
    return NS_OK;

  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance informing plugin of private mode state change this=%p\n",this));

  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  if (!pluginFunctions->setvalue)
    return NS_ERROR_FAILURE;

  PluginDestructionGuard guard(this);

  NPError error;
  NPBool value = static_cast<NPBool>(enabled);
  NS_TRY_SAFE_CALL_RETURN(error, (*pluginFunctions->setvalue)(&mNPP, NPNVprivateModeBool, &value), this,
                          NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);
  return (error == NPERR_NO_ERROR) ? NS_OK : NS_ERROR_FAILURE;
}

nsresult
nsNPAPIPluginInstance::IsPrivateBrowsing(bool* aEnabled)
{
  if (!mOwner)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDocument> doc;
  mOwner->GetDocument(getter_AddRefs(doc));
  NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);

  nsCOMPtr<nsPIDOMWindowOuter> domwindow = doc->GetWindow();
  NS_ENSURE_TRUE(domwindow, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDocShell> docShell = domwindow->GetDocShell();
  nsCOMPtr<nsILoadContext> loadContext = do_QueryInterface(docShell);
  *aEnabled = (loadContext && loadContext->UsePrivateBrowsing());
  return NS_OK;
}

static void
PluginTimerCallback(nsITimer *aTimer, void *aClosure)
{
  nsNPAPITimer* t = (nsNPAPITimer*)aClosure;
  NPP npp = t->npp;
  uint32_t id = t->id;

  PLUGIN_LOG(PLUGIN_LOG_NOISY, ("nsNPAPIPluginInstance running plugin timer callback this=%p\n", npp->ndata));

  MAIN_THREAD_JNI_REF_GUARD;
  // Some plugins (Flash on Android) calls unscheduletimer
  // from this callback.
  t->inCallback = true;
  (*(t->callback))(npp, id);
  t->inCallback = false;

  // Make sure we still have an instance and the timer is still alive
  // after the callback.
  nsNPAPIPluginInstance *inst = (nsNPAPIPluginInstance*)npp->ndata;
  if (!inst || !inst->TimerWithID(id, nullptr))
    return;

  // use UnscheduleTimer to clean up if this is a one-shot timer
  uint32_t timerType;
  t->timer->GetType(&timerType);
  if (t->needUnschedule || timerType == nsITimer::TYPE_ONE_SHOT)
    inst->UnscheduleTimer(id);
}

nsNPAPITimer*
nsNPAPIPluginInstance::TimerWithID(uint32_t id, uint32_t* index)
{
  uint32_t len = mTimers.Length();
  for (uint32_t i = 0; i < len; i++) {
    if (mTimers[i]->id == id) {
      if (index)
        *index = i;
      return mTimers[i];
    }
  }
  return nullptr;
}

uint32_t
nsNPAPIPluginInstance::ScheduleTimer(uint32_t interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32_t timerID))
{
  if (RUNNING != mRunning)
    return 0;

  nsNPAPITimer *newTimer = new nsNPAPITimer();

  newTimer->inCallback = newTimer->needUnschedule = false;
  newTimer->npp = &mNPP;

  // generate ID that is unique to this instance
  uint32_t uniqueID = mTimers.Length();
  while ((uniqueID == 0) || TimerWithID(uniqueID, nullptr))
    uniqueID++;
  newTimer->id = uniqueID;

  // create new xpcom timer, scheduled correctly
  nsresult rv;
  nsCOMPtr<nsITimer> xpcomTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
  if (NS_FAILED(rv)) {
    delete newTimer;
    return 0;
  }
  const short timerType = (repeat ? (short)nsITimer::TYPE_REPEATING_SLACK : (short)nsITimer::TYPE_ONE_SHOT);
  xpcomTimer->InitWithFuncCallback(PluginTimerCallback, newTimer, interval, timerType);
  newTimer->timer = xpcomTimer;

  // save callback function
  newTimer->callback = timerFunc;

  // add timer to timers array
  mTimers.AppendElement(newTimer);

  return newTimer->id;
}

void
nsNPAPIPluginInstance::UnscheduleTimer(uint32_t timerID)
{
  // find the timer struct by ID
  uint32_t index;
  nsNPAPITimer* t = TimerWithID(timerID, &index);
  if (!t)
    return;

  if (t->inCallback) {
    t->needUnschedule = true;
    return;
  }

  // cancel the timer
  t->timer->Cancel();

  // remove timer struct from array
  mTimers.RemoveElementAt(index);

  // delete timer
  delete t;
}

NPBool
nsNPAPIPluginInstance::ConvertPoint(double sourceX, double sourceY, NPCoordinateSpace sourceSpace,
                                    double *destX, double *destY, NPCoordinateSpace destSpace)
{
  if (mOwner) {
    return mOwner->ConvertPoint(sourceX, sourceY, sourceSpace, destX, destY, destSpace);
  }

  return false;
}

nsresult
nsNPAPIPluginInstance::GetDOMElement(nsIDOMElement* *result)
{
  if (!mOwner) {
    *result = nullptr;
    return NS_ERROR_FAILURE;
  }

  return mOwner->GetDOMElement(result);
}

nsresult
nsNPAPIPluginInstance::InvalidateRect(NPRect *invalidRect)
{
  if (RUNNING != mRunning)
    return NS_OK;

  if (!mOwner)
    return NS_ERROR_FAILURE;

  return mOwner->InvalidateRect(invalidRect);
}

nsresult
nsNPAPIPluginInstance::InvalidateRegion(NPRegion invalidRegion)
{
  if (RUNNING != mRunning)
    return NS_OK;

  if (!mOwner)
    return NS_ERROR_FAILURE;

  return mOwner->InvalidateRegion(invalidRegion);
}

nsresult
nsNPAPIPluginInstance::GetMIMEType(const char* *result)
{
  if (!mMIMEType)
    *result = "";
  else
    *result = mMIMEType;

  return NS_OK;
}

nsPluginInstanceOwner*
nsNPAPIPluginInstance::GetOwner()
{
  return mOwner;
}

void
nsNPAPIPluginInstance::SetOwner(nsPluginInstanceOwner *aOwner)
{
  mOwner = aOwner;
}

nsresult
nsNPAPIPluginInstance::AsyncSetWindow(NPWindow& window)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

void
nsNPAPIPluginInstance::URLRedirectResponse(void* notifyData, NPBool allow)
{
  if (!notifyData) {
    return;
  }

  uint32_t listenerCount = mStreamListeners.Length();
  for (uint32_t i = 0; i < listenerCount; i++) {
    nsNPAPIPluginStreamListener* currentListener = mStreamListeners[i];
    if (currentListener->GetNotifyData() == notifyData) {
      currentListener->URLRedirectResponse(allow);
    }
  }
}

NPError
nsNPAPIPluginInstance::InitAsyncSurface(NPSize *size, NPImageFormat format,
                                        void *initData, NPAsyncSurface *surface)
{
  if (mOwner) {
    return mOwner->InitAsyncSurface(size, format, initData, surface);
  }

  return NPERR_GENERIC_ERROR;
}

NPError
nsNPAPIPluginInstance::FinalizeAsyncSurface(NPAsyncSurface *surface)
{
  if (mOwner) {
    return mOwner->FinalizeAsyncSurface(surface);
  }

  return NPERR_GENERIC_ERROR;
}

void
nsNPAPIPluginInstance::SetCurrentAsyncSurface(NPAsyncSurface *surface, NPRect *changed)
{
  if (mOwner) {
    mOwner->SetCurrentAsyncSurface(surface, changed);
  }
}

class CarbonEventModelFailureEvent : public Runnable {
public:
  nsCOMPtr<nsIContent> mContent;

  explicit CarbonEventModelFailureEvent(nsIContent* aContent)
    : mContent(aContent)
  {}

  ~CarbonEventModelFailureEvent() {}

  NS_IMETHOD Run();
};

NS_IMETHODIMP
CarbonEventModelFailureEvent::Run()
{
  nsString type = NS_LITERAL_STRING("npapi-carbon-event-model-failure");
  nsContentUtils::DispatchTrustedEvent(mContent->GetComposedDoc(), mContent,
                                       type, true, true);
  return NS_OK;
}

void
nsNPAPIPluginInstance::CarbonNPAPIFailure()
{
  nsCOMPtr<nsIDOMElement> element;
  GetDOMElement(getter_AddRefs(element));
  if (!element) {
    return;
  }

  nsCOMPtr<nsIContent> content(do_QueryInterface(element));
  if (!content) {
    return;
  }

  nsCOMPtr<nsIRunnable> e = new CarbonEventModelFailureEvent(content);
  nsresult rv = NS_DispatchToCurrentThread(e);
  if (NS_FAILED(rv)) {
    NS_WARNING("Failed to dispatch CarbonEventModelFailureEvent.");
  }
}

static bool
GetJavaVersionFromMimetype(nsPluginTag* pluginTag, nsCString& version)
{
  for (uint32_t i = 0; i < pluginTag->MimeTypes().Length(); ++i) {
    nsCString type = pluginTag->MimeTypes()[i];
    nsAutoCString jpi("application/x-java-applet;jpi-version=");

    int32_t idx = type.Find(jpi, false, 0, -1);
    if (idx != 0) {
      continue;
    }

    type.Cut(0, jpi.Length());
    if (type.IsEmpty()) {
      continue;
    }

    type.ReplaceChar('_', '.');
    version = type;
    return true;
  }

  return false;
}

void
nsNPAPIPluginInstance::CheckJavaC2PJSObjectQuirk(uint16_t paramCount,
                                                 const char* const* paramNames,
                                                 const char* const* paramValues)
{
  if (!mMIMEType || !mPlugin) {
    return;
  }

  nsPluginTagType tagtype;
  nsresult rv = GetTagType(&tagtype);
  if (NS_FAILED(rv) ||
      (tagtype != nsPluginTagType_Applet)) {
    return;
  }

  RefPtr<nsPluginHost> pluginHost = nsPluginHost::GetInst();
  if (!pluginHost) {
    return;
  }

  nsPluginTag* pluginTag = pluginHost->TagForPlugin(mPlugin);
  if (!pluginTag ||
      !pluginTag->mIsJavaPlugin) {
    return;
  }

  // check the params for "code" being present and non-empty
  bool haveCodeParam = false;
  bool isCodeParamEmpty = true;

  for (uint16_t i = paramCount; i > 0; --i) {
    if (PL_strcasecmp(paramNames[i - 1], "code") == 0) {
      haveCodeParam = true;
      if (strlen(paramValues[i - 1]) > 0) {
        isCodeParamEmpty = false;
      }
      break;
    }
  }

  // Due to the Java version being specified inconsistently across platforms
  // check the version via the mimetype for choosing specific Java versions
  nsCString javaVersion;
  if (!GetJavaVersionFromMimetype(pluginTag, javaVersion)) {
    return;
  }

  mozilla::Version version(javaVersion.get());

  if (version >= "1.7.0.4") {
    return;
  }

  if (!haveCodeParam && version >= "1.6.0.34" && version < "1.7") {
    return;
  }

  if (haveCodeParam && !isCodeParamEmpty) {
    return;
  }

  mHaveJavaC2PJSObjectQuirk = true;
}

double
nsNPAPIPluginInstance::GetContentsScaleFactor()
{
  double scaleFactor = 1.0;
  if (mOwner) {
    mOwner->GetContentsScaleFactor(&scaleFactor);
  }
  return scaleFactor;
}

float
nsNPAPIPluginInstance::GetCSSZoomFactor()
{
  float zoomFactor = 1.0;
  if (mOwner) {
    mOwner->GetCSSZoomFactor(&zoomFactor);
  }
  return zoomFactor;
}

nsresult
nsNPAPIPluginInstance::GetRunID(uint32_t* aRunID)
{
  if (NS_WARN_IF(!aRunID)) {
    return NS_ERROR_INVALID_POINTER;
  }

  if (NS_WARN_IF(!mPlugin)) {
    return NS_ERROR_FAILURE;
  }

  PluginLibrary* library = mPlugin->GetLibrary();
  if (!library) {
    return NS_ERROR_FAILURE;
  }

  return library->GetRunID(aRunID);
}

nsresult
nsNPAPIPluginInstance::GetOrCreateAudioChannelAgent(nsIAudioChannelAgent** aAgent)
{
  if (!mAudioChannelAgent) {
    nsresult rv;
    mAudioChannelAgent = do_CreateInstance("@mozilla.org/audiochannelagent;1", &rv);
    if (NS_WARN_IF(!mAudioChannelAgent)) {
      return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsPIDOMWindowOuter> window = GetDOMWindow();
    if (NS_WARN_IF(!window)) {
      return NS_ERROR_FAILURE;
    }

    rv = mAudioChannelAgent->Init(window->GetCurrentInnerWindow(),
                                 (int32_t)AudioChannelService::GetDefaultAudioChannel(),
                                 this);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
  }

  nsCOMPtr<nsIAudioChannelAgent> agent = mAudioChannelAgent;
  agent.forget(aAgent);
  return NS_OK;
}

NS_IMETHODIMP
nsNPAPIPluginInstance::WindowVolumeChanged(float aVolume, bool aMuted)
{
  // We just support mute/unmute
  nsresult rv = SetMuted(aMuted);
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "SetMuted failed");
  if (mMuted != aMuted) {
    mMuted = aMuted;
    AudioChannelService::AudibleState audible = aMuted ?
      AudioChannelService::AudibleState::eNotAudible :
      AudioChannelService::AudibleState::eAudible;
    mAudioChannelAgent->NotifyStartedAudible(audible,
                                             AudioChannelService::AudibleChangedReasons::eVolumeChanged);
  }
  return rv;
}

NS_IMETHODIMP
nsNPAPIPluginInstance::WindowSuspendChanged(nsSuspendedTypes aSuspend)
{
  // It doesn't support suspended, so we just do something like mute/unmute.
  WindowVolumeChanged(1.0, /* useless */
                      aSuspend != nsISuspendedTypes::NONE_SUSPENDED);
  return NS_OK;
}

NS_IMETHODIMP
nsNPAPIPluginInstance::WindowAudioCaptureChanged(bool aCapture)
{
  return NS_OK;
}

nsresult
nsNPAPIPluginInstance::SetMuted(bool aIsMuted)
{
  if (RUNNING != mRunning)
    return NS_OK;

  PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("nsNPAPIPluginInstance informing plugin of mute state change this=%p\n",this));

  if (!mPlugin || !mPlugin->GetLibrary())
    return NS_ERROR_FAILURE;

  NPPluginFuncs* pluginFunctions = mPlugin->PluginFuncs();

  if (!pluginFunctions->setvalue)
    return NS_ERROR_FAILURE;

  PluginDestructionGuard guard(this);

  NPError error;
  NPBool value = static_cast<NPBool>(aIsMuted);
  NS_TRY_SAFE_CALL_RETURN(error, (*pluginFunctions->setvalue)(&mNPP, NPNVmuteAudioBool, &value), this,
                          NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO);
  return (error == NPERR_NO_ERROR) ? NS_OK : NS_ERROR_FAILURE;
}