stormcloud-video-player 0.8.64 → 0.8.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -807,7 +807,7 @@ function toVastMediaErrorCode(error) {
807
807
  }
808
808
  }
809
809
  function createHlsAdPlayer(contentVideo, options) {
810
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
810
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
811
811
  var adPlaying = false;
812
812
  var originalMutedState = false;
813
813
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -839,6 +839,16 @@ function createHlsAdPlayer(contentVideo, options) {
839
839
  var sawDecodedVideoFrame = false;
840
840
  var videoFrameCallbackHandle;
841
841
  var pendingPlayPromise;
842
+ var currentVastTagUrl;
843
+ var funnelContext = {};
844
+ var mediaCandidates = [];
845
+ var mediaCandidateIndex = 0;
846
+ var mediaStartTimerId;
847
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
848
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
849
+ var pendingVastRequests = /* @__PURE__ */ new Set();
850
+ var pendingRequestAbortReason;
851
+ var forcedMuteByAutoplay = false;
842
852
  function createTrackingState() {
843
853
  return {
844
854
  impression: false,
@@ -889,6 +899,77 @@ function createHlsAdPlayer(contentVideo, options) {
889
899
  }
890
900
  }
891
901
  }
902
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
903
+ "ppid",
904
+ "rdid",
905
+ "idtype",
906
+ "is_lat",
907
+ "ifa",
908
+ "idfa",
909
+ "aaid",
910
+ "uid",
911
+ "user_id",
912
+ "userid",
913
+ "device_id",
914
+ "deviceid",
915
+ "ip",
916
+ "ua",
917
+ "gdpr_consent",
918
+ "us_privacy",
919
+ "gpp",
920
+ "addtl_consent",
921
+ "cust_params",
922
+ "email"
923
+ ]);
924
+ function redactUrl(url) {
925
+ if (!url) return url;
926
+ try {
927
+ var parsed = new URL(url);
928
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
929
+ try {
930
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
931
+ var key = _step.value;
932
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
933
+ parsed.searchParams.set(key, "REDACTED");
934
+ }
935
+ }
936
+ } catch (err) {
937
+ _didIteratorError = true;
938
+ _iteratorError = err;
939
+ } finally{
940
+ try {
941
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
942
+ _iterator.return();
943
+ }
944
+ } finally{
945
+ if (_didIteratorError) {
946
+ throw _iteratorError;
947
+ }
948
+ }
949
+ }
950
+ return parsed.toString();
951
+ } catch (unused) {
952
+ return url.split("?")[0];
953
+ }
954
+ }
955
+ function logFunnel(stage) {
956
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
957
+ var payload = _object_spread({
958
+ stage: stage,
959
+ breakId: funnelContext.breakId,
960
+ requestId: funnelContext.requestId,
961
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
962
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
963
+ podIndex: podIndex,
964
+ podSize: podAds.length,
965
+ vastUrl: redactUrl(currentVastTagUrl),
966
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
967
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
968
+ muted: adVideoElement ? adVideoElement.muted : void 0
969
+ }, extra);
970
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
971
+ emit("ad_funnel", payload);
972
+ }
892
973
  function buildTrackingMacroContext() {
893
974
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
894
975
  var _options2_ad;
@@ -928,20 +1009,53 @@ function createHlsAdPlayer(contentVideo, options) {
928
1009
  urls.forEach(function(url) {
929
1010
  try {
930
1011
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
1012
+ var trackingHost;
1013
+ try {
1014
+ trackingHost = new URL(trackingUrl).host;
1015
+ } catch (unused) {
1016
+ logFunnel("tracking_url_invalid", {
1017
+ trackingUrl: redactUrl(trackingUrl)
1018
+ });
1019
+ return;
1020
+ }
1021
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
1022
+ if (unexpanded) {
1023
+ logFunnel("tracking_url_unexpanded_macro", {
1024
+ trackingHost: trackingHost,
1025
+ macros: Array.from(new Set(unexpanded))
1026
+ });
1027
+ }
931
1028
  var img = new Image(1, 1);
932
1029
  inFlightBeacons.add(img);
933
1030
  var timeoutId;
934
- var release = function release() {
1031
+ var release = function release(outcome) {
935
1032
  if (timeoutId !== void 0) clearTimeout(timeoutId);
936
1033
  img.onload = null;
937
1034
  img.onerror = null;
938
1035
  inFlightBeacons.delete(img);
1036
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
1037
+ if (outcome !== "load") {
1038
+ logFunnel("tracking_request_settled", {
1039
+ reason: outcome,
1040
+ trackingHost: trackingHost
1041
+ });
1042
+ }
1043
+ };
1044
+ img.onload = function() {
1045
+ return release("load");
1046
+ };
1047
+ img.onerror = function() {
1048
+ return release("error");
939
1049
  };
940
- img.onload = release;
941
- img.onerror = release;
942
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
1050
+ timeoutId = setTimeout(function() {
1051
+ return release("timeout");
1052
+ }, BEACON_TIMEOUT_MS);
943
1053
  img.src = trackingUrl;
944
1054
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
1055
+ logFunnel("tracking_request_created", {
1056
+ trackingHost: trackingHost,
1057
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
1058
+ });
945
1059
  } catch (error) {
946
1060
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
947
1061
  }
@@ -971,54 +1085,80 @@ function createHlsAdPlayer(contentVideo, options) {
971
1085
  bitrate: level.bitrate || 5e6
972
1086
  };
973
1087
  }
974
- function selectBestMediaFile(mediaFiles) {
975
- if (mediaFiles.length === 0) {
976
- throw new Error("No media files available");
977
- }
978
- var firstFile = mediaFiles[0];
979
- if (!firstFile) {
980
- throw new Error("No media files available");
981
- }
982
- if (mediaFiles.length === 1) {
983
- return firstFile;
984
- }
1088
+ function getMediaTargetQuality() {
985
1089
  var mainQuality = getMainStreamQuality();
986
- if (!mainQuality) {
987
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
988
- return firstFile;
989
- }
990
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
991
- var scoredFiles = mediaFiles.map(function(file) {
992
- var widthDiff = Math.abs(file.width - mainQuality.width);
993
- var heightDiff = Math.abs(file.height - mainQuality.height);
994
- var resolutionDiff = widthDiff + heightDiff;
995
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
996
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
997
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
998
- return {
1090
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
1091
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
1092
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
1093
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
1094
+ return null;
1095
+ }
1096
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
1097
+ width: containerWidth,
1098
+ height: containerHeight,
1099
+ bitrate: 5e6
1100
+ };
1101
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
1102
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
1103
+ return {
1104
+ width: width,
1105
+ height: height,
1106
+ bitrate: base.bitrate
1107
+ };
1108
+ }
1109
+ function rankMediaCandidates(mediaFiles) {
1110
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
1111
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
1112
+ var target = getMediaTargetQuality();
1113
+ var accepted = [];
1114
+ mediaFiles.forEach(function(file, index) {
1115
+ var isHls = isHlsMediaFile(file);
1116
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
1117
+ var canPlay2 = probe.canPlayType(mimeForProbe);
1118
+ var playable = isHls ? import_hls.default.isSupported() || canPlay2 !== "" : canPlay2 !== "";
1119
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
1120
+ var details = {
1121
+ index: index,
1122
+ candidateUrl: file.url,
1123
+ candidateType: file.type,
1124
+ width: file.width,
1125
+ height: file.height,
1126
+ bitrate: file.bitrate,
1127
+ canPlayType: canPlay2,
1128
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
1129
+ };
1130
+ if (!playable) {
1131
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1132
+ reason: "rejected",
1133
+ why: "cannot_play_type"
1134
+ }));
1135
+ return;
1136
+ }
1137
+ var score = 0;
1138
+ if (target) {
1139
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
1140
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
1141
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
1142
+ }
1143
+ accepted.push({
999
1144
  file: file,
1000
1145
  score: score,
1001
- resolutionDiff: resolutionDiff,
1002
- bitrateDiff: bitrateDiff
1003
- };
1146
+ insecure: insecure
1147
+ });
1148
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1149
+ reason: "accepted",
1150
+ // Mixed-content media is often auto-upgraded, so it is kept as a last resort.
1151
+ why: insecure ? "insecure_http_deprioritized" : "playable",
1152
+ score: score
1153
+ }));
1004
1154
  });
1005
- scoredFiles.sort(function(a, b) {
1155
+ accepted.sort(function(a, b) {
1156
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
1006
1157
  return a.score - b.score;
1007
1158
  });
1008
- var bestMatch = scoredFiles[0];
1009
- if (!bestMatch) {
1010
- console.log("[HlsAdPlayer] No best match found, using first media file");
1011
- return firstFile;
1012
- }
1013
- console.log("[HlsAdPlayer] Selected media file:", {
1014
- url: bestMatch.file.url,
1015
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
1016
- bitrate: bestMatch.file.bitrate,
1017
- score: bestMatch.score,
1018
- resolutionDiff: bestMatch.resolutionDiff,
1019
- bitrateDiff: bestMatch.bitrateDiff
1159
+ return accepted.map(function(entry) {
1160
+ return entry.file;
1020
1161
  });
1021
- return bestMatch.file;
1022
1162
  }
1023
1163
  function isHlsMediaFile(mediaFile) {
1024
1164
  var type = mediaFile.type.toLowerCase();
@@ -1035,9 +1175,10 @@ function createHlsAdPlayer(contentVideo, options) {
1035
1175
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
1036
1176
  return type.startsWith("audio/") || url.endsWith(".mp3") || url.endsWith(".aac") || url.endsWith(".m4a") || url.endsWith(".ogg") || url.endsWith(".oga") || url.endsWith(".opus") || url.endsWith(".wav") || url.endsWith(".weba");
1037
1177
  }
1038
- function collectVideoMediaFiles(linear, verbose) {
1178
+ function collectVideoMediaFiles(linear, verbose, stats) {
1039
1179
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
1040
1180
  var mediaFiles = [];
1181
+ if (stats) stats.total += mediaFileElements.length;
1041
1182
  if (verbose) {
1042
1183
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
1043
1184
  }
@@ -1058,6 +1199,7 @@ function createHlsAdPlayer(contentVideo, options) {
1058
1199
  }
1059
1200
  var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1060
1201
  if (apiFramework === "VPAID") {
1202
+ if (stats) stats.vpaid++;
1061
1203
  if (verbose) {
1062
1204
  console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
1063
1205
  }
@@ -1073,11 +1215,13 @@ function createHlsAdPlayer(contentVideo, options) {
1073
1215
  bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
1074
1216
  };
1075
1217
  if (isAudioMediaFile(mediaFile)) {
1218
+ if (stats) stats.audio++;
1076
1219
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
1077
1220
  return;
1078
1221
  }
1079
1222
  var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1080
1223
  if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
1224
+ if (stats) stats.audio++;
1081
1225
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, " skipped (degenerate dimensions ").concat(mediaFile.width, "x").concat(mediaFile.height, ', type="').concat(type, '") — likely an audio-only placeholder rendition'));
1082
1226
  return;
1083
1227
  }
@@ -1086,8 +1230,11 @@ function createHlsAdPlayer(contentVideo, options) {
1086
1230
  if (verbose) {
1087
1231
  console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
1088
1232
  }
1089
- } else if (verbose) {
1090
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1233
+ } else {
1234
+ if (stats) stats.unsupported++;
1235
+ if (verbose) {
1236
+ console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1237
+ }
1091
1238
  }
1092
1239
  });
1093
1240
  return mediaFiles;
@@ -1211,26 +1358,58 @@ function createHlsAdPlayer(contentVideo, options) {
1211
1358
  }
1212
1359
  function parseVastXml(xmlString) {
1213
1360
  try {
1214
- var _adElements_find;
1215
1361
  var xmlDoc = parseXml(xmlString);
1216
1362
  if (!xmlDoc) return {
1217
1363
  type: "empty"
1218
1364
  };
1219
1365
  var root = xmlDoc.documentElement;
1220
1366
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1221
- var adElement = (_adElements_find = adElements.find(function(el) {
1222
- return getAdSequence(el) === void 0;
1223
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1224
- if (!adElement) {
1367
+ if (adElements.length === 0) {
1225
1368
  var _root_getAttribute;
1226
1369
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1227
1370
  return emptyVastResult(root);
1228
1371
  }
1229
- var parsed = parseAdElement(adElement, true);
1230
- if (parsed.type === "wrapper") {
1231
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1372
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1373
+ return getAdSequence(el) === void 0;
1374
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1375
+ return getAdSequence(el) !== void 0;
1376
+ })));
1377
+ var firstEmpty;
1378
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1379
+ try {
1380
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1381
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1382
+ var parsed = parseAdElement(adElement, true);
1383
+ if (parsed.type === "empty") {
1384
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1385
+ continue;
1386
+ }
1387
+ if (index > 0) {
1388
+ logFunnel("vast_ad_fallback", {
1389
+ usedAdIndex: index,
1390
+ adCount: ordered.length
1391
+ });
1392
+ }
1393
+ if (parsed.type === "wrapper") {
1394
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1395
+ }
1396
+ return parsed;
1397
+ }
1398
+ } catch (err) {
1399
+ _didIteratorError = true;
1400
+ _iteratorError = err;
1401
+ } finally{
1402
+ try {
1403
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1404
+ _iterator.return();
1405
+ }
1406
+ } finally{
1407
+ if (_didIteratorError) {
1408
+ throw _iteratorError;
1409
+ }
1410
+ }
1232
1411
  }
1233
- return parsed;
1412
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1234
1413
  } catch (error) {
1235
1414
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1236
1415
  return {
@@ -1276,6 +1455,10 @@ function createHlsAdPlayer(contentVideo, options) {
1276
1455
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1277
1456
  if (adElement.getAttribute("conditionalAd") === "true") {
1278
1457
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1458
+ logFunnel("vast_no_supported_media", {
1459
+ reason: "vpaid_only",
1460
+ conditionalAd: true
1461
+ });
1279
1462
  return {
1280
1463
  type: "empty",
1281
1464
  errorUrls: errorUrls,
@@ -1284,11 +1467,17 @@ function createHlsAdPlayer(contentVideo, options) {
1284
1467
  }
1285
1468
  var linear;
1286
1469
  var mediaFiles = [];
1470
+ var rejectStats = {
1471
+ total: 0,
1472
+ vpaid: 0,
1473
+ audio: 0,
1474
+ unsupported: 0
1475
+ };
1287
1476
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1288
1477
  try {
1289
1478
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1290
1479
  var candidate = _step.value;
1291
- var files = collectVideoMediaFiles(candidate, verbose);
1480
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1292
1481
  if (files.length > 0) {
1293
1482
  linear = candidate;
1294
1483
  mediaFiles = files;
@@ -1311,6 +1500,10 @@ function createHlsAdPlayer(contentVideo, options) {
1311
1500
  }
1312
1501
  if (!linear) {
1313
1502
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1503
+ var reason = rejectStats.total === 0 ? "no_mediafiles" : rejectStats.vpaid > 0 ? "vpaid_only" : rejectStats.audio > 0 ? "audio_only" : "unsupported_type";
1504
+ logFunnel("vast_no_supported_media", _object_spread({
1505
+ reason: reason
1506
+ }, rejectStats));
1314
1507
  return {
1315
1508
  type: "empty",
1316
1509
  errorUrls: errorUrls,
@@ -1346,7 +1539,11 @@ function createHlsAdPlayer(contentVideo, options) {
1346
1539
  return _ts_generator(this, function(_state) {
1347
1540
  switch(_state.label){
1348
1541
  case 0:
1542
+ if (destroyed) {
1543
+ throw new Error("VAST request skipped: ad player destroyed");
1544
+ }
1349
1545
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1546
+ if (controller) pendingVastRequests.add(controller);
1350
1547
  timeoutId = controller ? setTimeout(function() {
1351
1548
  return controller.abort();
1352
1549
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
@@ -1395,6 +1592,9 @@ function createHlsAdPlayer(contentVideo, options) {
1395
1592
  6
1396
1593
  ];
1397
1594
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1595
+ logFunnel("vast_credentials_retry", {
1596
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1597
+ });
1398
1598
  return [
1399
1599
  4,
1400
1600
  requestVast("omit")
@@ -1428,11 +1628,15 @@ function createHlsAdPlayer(contentVideo, options) {
1428
1628
  case 10:
1429
1629
  error1 = _state.sent();
1430
1630
  if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1631
+ if (pendingRequestAbortReason) {
1632
+ throw new Error("".concat(pendingRequestAbortReason, " (timeout): ").concat(vastTagUrl));
1633
+ }
1431
1634
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1432
1635
  }
1433
1636
  throw error1;
1434
1637
  case 11:
1435
1638
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1639
+ if (controller) pendingVastRequests.delete(controller);
1436
1640
  return [
1437
1641
  7
1438
1642
  ];
@@ -1446,7 +1650,7 @@ function createHlsAdPlayer(contentVideo, options) {
1446
1650
  }
1447
1651
  function fetchAndParseVastAd(_0) {
1448
1652
  return _async_to_generator(function(vastTagUrl) {
1449
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1653
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1450
1654
  var _arguments = arguments;
1451
1655
  return _ts_generator(this, function(_state) {
1452
1656
  switch(_state.label){
@@ -1454,6 +1658,11 @@ function createHlsAdPlayer(contentVideo, options) {
1454
1658
  depth = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : 0, accumulatedTracking = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : createEmptyTrackingUrls(), rules = _arguments.length > 3 && _arguments[3] !== void 0 ? _arguments[3] : {
1455
1659
  followAdditionalWrappers: true
1456
1660
  };
1661
+ if (destroyed) return [
1662
+ 2,
1663
+ null
1664
+ ];
1665
+ fetchStartedAt = Date.now();
1457
1666
  _state.label = 1;
1458
1667
  case 1:
1459
1668
  _state.trys.push([
@@ -1476,14 +1685,35 @@ function createHlsAdPlayer(contentVideo, options) {
1476
1685
  error = _state.sent();
1477
1686
  if (depth === 0) throw error;
1478
1687
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1479
- fireTrackingPixels(accumulatedTracking.error, {
1480
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1688
+ logFunnel("wrapper_fetch", {
1689
+ reason: "failure",
1690
+ depth: depth,
1691
+ wrapperUrl: redactUrl(vastTagUrl),
1692
+ elapsedMs: Date.now() - fetchStartedAt,
1693
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1481
1694
  });
1695
+ if (!destroyed) {
1696
+ fireTrackingPixels(accumulatedTracking.error, {
1697
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1698
+ });
1699
+ }
1482
1700
  return [
1483
1701
  2,
1484
1702
  null
1485
1703
  ];
1486
1704
  case 4:
1705
+ if (destroyed) return [
1706
+ 2,
1707
+ null
1708
+ ];
1709
+ if (depth > 0) {
1710
+ logFunnel("wrapper_fetch", {
1711
+ reason: "success",
1712
+ depth: depth,
1713
+ wrapperUrl: redactUrl(vastTagUrl),
1714
+ elapsedMs: Date.now() - fetchStartedAt
1715
+ });
1716
+ }
1487
1717
  console.log("[HlsAdPlayer] VAST XML received");
1488
1718
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1489
1719
  parsed = parseVastXml(vastXml);
@@ -1515,6 +1745,9 @@ function createHlsAdPlayer(contentVideo, options) {
1515
1745
  ];
1516
1746
  }
1517
1747
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1748
+ logFunnel("inline_resolved", {
1749
+ depth: depth
1750
+ });
1518
1751
  return [
1519
1752
  2,
1520
1753
  parsed.ad
@@ -1535,6 +1768,10 @@ function createHlsAdPlayer(contentVideo, options) {
1535
1768
  ];
1536
1769
  case 1:
1537
1770
  vastXml = _state.sent();
1771
+ if (destroyed) return [
1772
+ 2,
1773
+ []
1774
+ ];
1538
1775
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1539
1776
  trimmedXml = vastXml.trim();
1540
1777
  if (trimmedXml.length === 0) {
@@ -1822,14 +2059,17 @@ function createHlsAdPlayer(contentVideo, options) {
1822
2059
  var progress = currentTime / currentAd.duration;
1823
2060
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1824
2061
  trackingFired.firstQuartile = true;
2062
+ logFunnel("first_quartile");
1825
2063
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1826
2064
  }
1827
2065
  if (progress >= 0.5 && !trackingFired.midpoint) {
1828
2066
  trackingFired.midpoint = true;
2067
+ logFunnel("midpoint");
1829
2068
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1830
2069
  }
1831
2070
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1832
2071
  trackingFired.thirdQuartile = true;
2072
+ logFunnel("third_quartile");
1833
2073
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1834
2074
  }
1835
2075
  };
@@ -1852,6 +2092,16 @@ function createHlsAdPlayer(contentVideo, options) {
1852
2092
  if (!trackingFired.impression) {
1853
2093
  trackingFired.impression = true;
1854
2094
  resolvedAds.add(currentAd);
2095
+ logFunnel("playing", {
2096
+ mutedByAutoplay: forcedMuteByAutoplay,
2097
+ candidateIndex: mediaCandidateIndex
2098
+ });
2099
+ logFunnel("impression_fired", {
2100
+ pixelCount: currentAd.trackingUrls.impression.length
2101
+ });
2102
+ if (currentAd.trackingUrls.impression.length === 0) {
2103
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
2104
+ }
1855
2105
  fireTrackingPixels(currentAd.trackingUrls.impression);
1856
2106
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1857
2107
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1874,6 +2124,7 @@ function createHlsAdPlayer(contentVideo, options) {
1874
2124
  sampleViewability();
1875
2125
  settleViewability();
1876
2126
  trackingFired.complete = true;
2127
+ logFunnel("complete");
1877
2128
  fireTrackingPixels(currentAd.trackingUrls.complete);
1878
2129
  console.log("[HlsAdPlayer] Ad completed");
1879
2130
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1882,16 +2133,41 @@ function createHlsAdPlayer(contentVideo, options) {
1882
2133
  handleAdComplete();
1883
2134
  };
1884
2135
  var onError = function onError(e) {
2136
+ var _adVideoElement_error, _adVideoElement_error1;
1885
2137
  if (!adPlaying) return;
1886
2138
  console.error("[HlsAdPlayer] Ad video error:", e);
1887
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1888
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1889
- return;
1890
- }
1891
- handleAdError();
2139
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
2140
+ logFunnel("media_error", {
2141
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
2142
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
2143
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2144
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2145
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2146
+ vastErrorCode: vastErrorCode
2147
+ });
2148
+ recoverFromAdFailure(vastErrorCode);
2149
+ };
2150
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
2151
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
2152
+ if (!adVideoElement.currentSrc) return;
2153
+ logFunnel("media_event", {
2154
+ reason: event.type,
2155
+ readyState: adVideoElement.readyState,
2156
+ networkState: adVideoElement.networkState,
2157
+ currentSrc: adVideoElement.currentSrc
2158
+ });
1892
2159
  };
1893
2160
  var onVolumeChange = function onVolumeChange() {
1894
2161
  if (!currentAd || !adVideoElement) return;
2162
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2163
+ var userActivation = navigator.userActivation;
2164
+ if (userActivation && !userActivation.isActive) {
2165
+ logFunnel("unexpected_unmute", {
2166
+ paused: adVideoElement.paused
2167
+ });
2168
+ }
2169
+ forcedMuteByAutoplay = false;
2170
+ }
1895
2171
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1896
2172
  if (!trackingFired.start) {
1897
2173
  trackingFired.lastMuted = muted;
@@ -1951,6 +2227,22 @@ function createHlsAdPlayer(contentVideo, options) {
1951
2227
  {
1952
2228
  type: "play",
1953
2229
  handler: onPlay
2230
+ },
2231
+ {
2232
+ type: "stalled",
2233
+ handler: onMediaDiagnostic
2234
+ },
2235
+ {
2236
+ type: "suspend",
2237
+ handler: onMediaDiagnostic
2238
+ },
2239
+ {
2240
+ type: "abort",
2241
+ handler: onMediaDiagnostic
2242
+ },
2243
+ {
2244
+ type: "emptied",
2245
+ handler: onMediaDiagnostic
1954
2246
  }
1955
2247
  ];
1956
2248
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2240,16 +2532,51 @@ function createHlsAdPlayer(contentVideo, options) {
2240
2532
  function settlePendingPlay() {
2241
2533
  pendingPlayPromise = void 0;
2242
2534
  }
2535
+ function toVastPlayErrorCode(error) {
2536
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2537
+ }
2538
+ function failAdPlayback(context, error) {
2539
+ var vastErrorCode = toVastPlayErrorCode(error);
2540
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2541
+ logFunnel("play_failed", {
2542
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2543
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2544
+ vastErrorCode: vastErrorCode
2545
+ });
2546
+ recoverFromAdFailure(vastErrorCode);
2547
+ }
2243
2548
  function startAdPlayback(context) {
2549
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2244
2550
  if (!adVideoElement) return;
2551
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2552
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2553
+ context: context,
2554
+ isConnected: adVideoElement.isConnected,
2555
+ clientWidth: adVideoElement.clientWidth,
2556
+ clientHeight: adVideoElement.clientHeight,
2557
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2558
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2559
+ });
2245
2560
  var playPromise = adVideoElement.play();
2246
2561
  pendingPlayPromise = playPromise;
2247
2562
  playPromise.catch(function(error) {
2248
2563
  if (pendingPlayPromise !== playPromise) {
2249
2564
  return;
2250
2565
  }
2251
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2252
- handleAdError();
2566
+ logFunnel("play_rejected", {
2567
+ context: context,
2568
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2569
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2570
+ });
2571
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2572
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2573
+ originalMutedState = true;
2574
+ forcedMuteByAutoplay = true;
2575
+ adVideoElement.muted = true;
2576
+ startAdPlayback(context, true);
2577
+ return;
2578
+ }
2579
+ failAdPlayback(context, error);
2253
2580
  }).finally(function() {
2254
2581
  if (pendingPlayPromise === playPromise) {
2255
2582
  pendingPlayPromise = void 0;
@@ -2288,17 +2615,109 @@ function createHlsAdPlayer(contentVideo, options) {
2288
2615
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2289
2616
  adVideoElement.muted = originalMutedState;
2290
2617
  }
2618
+ function clearMediaStartTimer() {
2619
+ if (mediaStartTimerId !== void 0) {
2620
+ clearTimeout(mediaStartTimerId);
2621
+ mediaStartTimerId = void 0;
2622
+ }
2623
+ }
2624
+ function startMediaStartTimer() {
2625
+ clearMediaStartTimer();
2626
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2627
+ var startedAt = Date.now();
2628
+ mediaStartTimerId = setTimeout(function() {
2629
+ mediaStartTimerId = void 0;
2630
+ if (!adPlaying || trackingFired.impression) return;
2631
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2632
+ logFunnel("play_resolved_but_never_started", {
2633
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2634
+ elapsedMs: Date.now() - startedAt,
2635
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2636
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2637
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2638
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2639
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2640
+ });
2641
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2642
+ }, MEDIA_START_TIMEOUT_MS);
2643
+ }
2644
+ function resetVideoElementForNextSource() {
2645
+ clearStallWatchdog();
2646
+ if (requiresMediaPipelineResetAfterAds()) {
2647
+ recreateAdVideoElement();
2648
+ setupAdEventListeners();
2649
+ } else {
2650
+ prepareVideoElementForNewSource();
2651
+ }
2652
+ }
2653
+ function tryNextMediaCandidate() {
2654
+ if (!currentAd || trackingFired.impression) return false;
2655
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2656
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2657
+ mediaCandidateIndex++;
2658
+ var next = mediaCandidates[mediaCandidateIndex];
2659
+ if (!next) return false;
2660
+ logFunnel("media_fallback", {
2661
+ failedUrl: failedUrl,
2662
+ nextUrl: next.url,
2663
+ nextType: next.type,
2664
+ candidateIndex: mediaCandidateIndex,
2665
+ candidateCount: mediaCandidates.length
2666
+ });
2667
+ resetVideoElementForNextSource();
2668
+ try {
2669
+ loadMediaCandidate(next);
2670
+ return true;
2671
+ } catch (error) {
2672
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2673
+ return tryNextMediaCandidate();
2674
+ }
2675
+ }
2676
+ function recoverFromAdFailure(vastErrorCode) {
2677
+ clearMediaStartTimer();
2678
+ if (tryNextMediaCandidate()) return;
2679
+ reportCurrentAdError(vastErrorCode);
2680
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2681
+ handleAdError();
2682
+ }
2291
2683
  function loadCurrentAdMedia() {
2292
2684
  if (!adVideoElement || !currentAd) {
2293
2685
  throw new Error("No ad video element or ad to load");
2294
2686
  }
2295
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2687
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2688
+ mediaCandidateIndex = 0;
2689
+ var mediaFile = mediaCandidates[0];
2296
2690
  if (!mediaFile) {
2297
- throw new Error("No media file available for ad");
2691
+ logFunnel("media_unsupported", {
2692
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2693
+ candidates: currentAd.mediaFiles.length
2694
+ });
2695
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2696
+ throw new Error("No media file this browser can play");
2697
+ }
2698
+ try {
2699
+ loadMediaCandidate(mediaFile);
2700
+ } catch (error) {
2701
+ if (tryNextMediaCandidate()) return;
2702
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2703
+ throw error;
2704
+ }
2705
+ }
2706
+ function loadMediaCandidate(mediaFile) {
2707
+ if (!adVideoElement || !currentAd) {
2708
+ throw new Error("No ad video element or ad to load");
2298
2709
  }
2299
2710
  currentAdMediaFile = mediaFile;
2300
2711
  var isHlsAd = isHlsMediaFile(mediaFile);
2712
+ logFunnel("media_selected", {
2713
+ width: mediaFile.width,
2714
+ height: mediaFile.height,
2715
+ bitrate: mediaFile.bitrate,
2716
+ candidateIndex: mediaCandidateIndex,
2717
+ candidates: mediaCandidates.length
2718
+ });
2301
2719
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2720
+ startMediaStartTimer();
2302
2721
  if (isHlsAd && import_hls.default.isSupported()) {
2303
2722
  if (adHls) {
2304
2723
  adHls.destroy();
@@ -2307,6 +2726,9 @@ function createHlsAdPlayer(contentVideo, options) {
2307
2726
  enableWorker: true,
2308
2727
  lowLatencyMode: false
2309
2728
  });
2729
+ logFunnel("media_load", {
2730
+ pipeline: "hls.js"
2731
+ });
2310
2732
  adHls.loadSource(mediaFile.url);
2311
2733
  adHls.attachMedia(adVideoElement);
2312
2734
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2316,10 +2738,24 @@ function createHlsAdPlayer(contentVideo, options) {
2316
2738
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2317
2739
  console.error("[HlsAdPlayer] HLS error:", data);
2318
2740
  if (data.fatal) {
2319
- handleAdError();
2741
+ var _data_response, _data_response1, _data_frag;
2742
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2743
+ logFunnel("hls_fatal", {
2744
+ reason: data.details,
2745
+ errorName: data.type,
2746
+ errorMessage: data.details,
2747
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2748
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2749
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2750
+ vastErrorCode: vastErrorCode
2751
+ });
2752
+ recoverFromAdFailure(vastErrorCode);
2320
2753
  }
2321
2754
  });
2322
2755
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2756
+ logFunnel("media_load", {
2757
+ pipeline: "native-hls"
2758
+ });
2323
2759
  adVideoElement.src = mediaFile.url;
2324
2760
  startAdPlayback("native HLS ad playback");
2325
2761
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2327,45 +2763,47 @@ function createHlsAdPlayer(contentVideo, options) {
2327
2763
  adHls.destroy();
2328
2764
  adHls = void 0;
2329
2765
  }
2766
+ logFunnel("media_load", {
2767
+ pipeline: "progressive"
2768
+ });
2330
2769
  adVideoElement.src = mediaFile.url;
2331
2770
  adVideoElement.load();
2332
2771
  startAdPlayback("progressive ad playback");
2333
2772
  } else {
2773
+ clearMediaStartTimer();
2774
+ logFunnel("media_unsupported", {
2775
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2776
+ });
2334
2777
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2335
2778
  }
2336
2779
  }
2337
2780
  function advanceToNextPodAd() {
2338
- if (podIndex >= podAds.length - 1) {
2339
- return false;
2340
- }
2341
- settleViewability();
2342
- podIndex++;
2343
- currentAd = podAds[podIndex];
2344
- currentAdMediaFile = void 0;
2345
- resetAdTracking();
2346
- if (currentAd) {
2347
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2348
- }
2349
- clearStallWatchdog();
2350
- if (requiresMediaPipelineResetAfterAds()) {
2351
- recreateAdVideoElement();
2352
- setupAdEventListeners();
2353
- } else {
2354
- prepareVideoElementForNewSource();
2355
- }
2356
- try {
2357
- loadCurrentAdMedia();
2358
- emit("pod_ad_started", {
2359
- index: podIndex,
2360
- total: podAds.length
2361
- });
2362
- return true;
2363
- } catch (error) {
2364
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2365
- return false;
2781
+ clearMediaStartTimer();
2782
+ while(podIndex < podAds.length - 1){
2783
+ settleViewability();
2784
+ podIndex++;
2785
+ currentAd = podAds[podIndex];
2786
+ currentAdMediaFile = void 0;
2787
+ resetAdTracking();
2788
+ if (currentAd) {
2789
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2790
+ }
2791
+ resetVideoElementForNextSource();
2792
+ try {
2793
+ loadCurrentAdMedia();
2794
+ emit("pod_ad_started", {
2795
+ index: podIndex,
2796
+ total: podAds.length
2797
+ });
2798
+ return true;
2799
+ } catch (error) {
2800
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2801
+ }
2366
2802
  }
2803
+ return false;
2367
2804
  }
2368
2805
  function clearStallWatchdog() {
2806
+ clearMediaStartTimer();
2369
2807
  if (stallWatchdogId != null) {
2370
2808
  clearInterval(stallWatchdogId);
2371
2809
  stallWatchdogId = void 0;
@@ -2381,11 +2819,10 @@ function createHlsAdPlayer(contentVideo, options) {
2381
2819
  function handleAdStall() {
2382
2820
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2383
2821
  clearStallWatchdog();
2384
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2385
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2386
- return;
2387
- }
2388
- handleAdError();
2822
+ logFunnel("stall", {
2823
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2824
+ });
2825
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2389
2826
  }
2390
2827
  function getDecodedVideoFrameCount(video) {
2391
2828
  try {
@@ -2447,11 +2884,10 @@ function createHlsAdPlayer(contentVideo, options) {
2447
2884
  function handleVideoDecodeFailure() {
2448
2885
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2449
2886
  clearStallWatchdog();
2450
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2451
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2452
- return;
2453
- }
2454
- handleAdError();
2887
+ logFunnel("decode_failure", {
2888
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2889
+ });
2890
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2455
2891
  }
2456
2892
  function startStallWatchdog() {
2457
2893
  clearStallWatchdog();
@@ -2575,6 +3011,15 @@ function createHlsAdPlayer(contentVideo, options) {
2575
3011
  Promise.reject(new Error("Ad already playing"))
2576
3012
  ];
2577
3013
  }
3014
+ if (destroyed) {
3015
+ return [
3016
+ 2,
3017
+ Promise.reject(new Error("Ad player destroyed"))
3018
+ ];
3019
+ }
3020
+ currentVastTagUrl = vastTagUrl;
3021
+ pendingRequestAbortReason = void 0;
3022
+ logFunnel("request_sent");
2578
3023
  _state.label = 1;
2579
3024
  case 1:
2580
3025
  _state.trys.push([
@@ -2609,8 +3054,18 @@ function createHlsAdPlayer(contentVideo, options) {
2609
3054
  ads = _state.sent();
2610
3055
  _state.label = 4;
2611
3056
  case 4:
3057
+ if (destroyed) {
3058
+ return [
3059
+ 2,
3060
+ Promise.reject(new Error("Ad player destroyed"))
3061
+ ];
3062
+ }
3063
+ if (!ads.length && pendingRequestAbortReason) {
3064
+ throw new Error(pendingRequestAbortReason);
3065
+ }
2612
3066
  if (!ads.length) {
2613
3067
  console.warn("[HlsAdPlayer] No ads available from VAST response");
3068
+ logFunnel("no_fill");
2614
3069
  emit("ad_error");
2615
3070
  return [
2616
3071
  2,
@@ -2621,6 +3076,23 @@ function createHlsAdPlayer(contentVideo, options) {
2621
3076
  podIndex = 0;
2622
3077
  currentAd = ads[0];
2623
3078
  currentAdMediaFile = void 0;
3079
+ logFunnel("vast_received", {
3080
+ adCount: ads.length,
3081
+ durations: ads.map(function(ad) {
3082
+ return ad.duration;
3083
+ }),
3084
+ impressionUrls: ads.map(function(ad) {
3085
+ return ad.trackingUrls.impression.length;
3086
+ })
3087
+ });
3088
+ ads.forEach(function(ad, index) {
3089
+ if (ad.trackingUrls.impression.length === 0) {
3090
+ logFunnel("vast_missing_impression", {
3091
+ adIndex: index,
3092
+ missingAdId: ad.id
3093
+ });
3094
+ }
3095
+ });
2624
3096
  console.log("[HlsAdPlayer] Pod parsed: ".concat(ads.length, ' ad(s), first="').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.title, '", duration=').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.duration, "s"));
2625
3097
  return [
2626
3098
  2,
@@ -2629,6 +3101,9 @@ function createHlsAdPlayer(contentVideo, options) {
2629
3101
  case 5:
2630
3102
  error = _state.sent();
2631
3103
  console.error("[HlsAdPlayer] Error requesting ads:", error);
3104
+ logFunnel("request_failed", {
3105
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3106
+ });
2632
3107
  emit("ad_error");
2633
3108
  return [
2634
3109
  2,
@@ -2684,13 +3159,22 @@ function createHlsAdPlayer(contentVideo, options) {
2684
3159
  adContainerEl.style.pointerEvents = "auto";
2685
3160
  }
2686
3161
  emit("content_pause");
2687
- loadCurrentAdMedia();
3162
+ try {
3163
+ loadCurrentAdMedia();
3164
+ } catch (loadError) {
3165
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3166
+ throw loadError;
3167
+ }
3168
+ }
2688
3169
  return [
2689
3170
  2,
2690
3171
  Promise.resolve()
2691
3172
  ];
2692
3173
  } catch (error) {
2693
3174
  console.error("[HlsAdPlayer] Error playing ad:", error);
3175
+ logFunnel("play_failed", {
3176
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3177
+ });
2694
3178
  handleAdError();
2695
3179
  return [
2696
3180
  2,
@@ -2732,6 +3216,9 @@ function createHlsAdPlayer(contentVideo, options) {
2732
3216
  var previousMutedState;
2733
3217
  return _ts_generator(this, function(_state) {
2734
3218
  console.log("[HlsAdPlayer] Stopping ad");
3219
+ if (adPlaying && currentAd && !trackingFired.impression) {
3220
+ logFunnel("stopped_before_start");
3221
+ }
2735
3222
  settleViewability();
2736
3223
  fireNotUsedForUnplayedAds();
2737
3224
  clearStallWatchdog();
@@ -2764,15 +3251,18 @@ function createHlsAdPlayer(contentVideo, options) {
2764
3251
  },
2765
3252
  destroy: function destroy() {
2766
3253
  console.log("[HlsAdPlayer] Destroying");
3254
+ if (adPlaying && currentAd && !trackingFired.impression) {
3255
+ logFunnel("stopped_before_start");
3256
+ }
2767
3257
  settleViewability();
2768
3258
  fireNotUsedForUnplayedAds();
2769
3259
  destroyed = true;
2770
- clearStallWatchdog();
3260
+ pendingRequestAbortReason = "Ad player destroyed";
2771
3261
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2772
3262
  try {
2773
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2774
- var timeoutId = _step.value;
2775
- clearTimeout(timeoutId);
3263
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3264
+ var controller = _step.value;
3265
+ controller.abort();
2776
3266
  }
2777
3267
  } catch (err) {
2778
3268
  _didIteratorError = true;
@@ -2788,6 +3278,28 @@ function createHlsAdPlayer(contentVideo, options) {
2788
3278
  }
2789
3279
  }
2790
3280
  }
3281
+ pendingVastRequests.clear();
3282
+ clearStallWatchdog();
3283
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3284
+ try {
3285
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3286
+ var timeoutId = _step1.value;
3287
+ clearTimeout(timeoutId);
3288
+ }
3289
+ } catch (err) {
3290
+ _didIteratorError1 = true;
3291
+ _iteratorError1 = err;
3292
+ } finally{
3293
+ try {
3294
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3295
+ _iterator1.return();
3296
+ }
3297
+ } finally{
3298
+ if (_didIteratorError1) {
3299
+ throw _iteratorError1;
3300
+ }
3301
+ }
3302
+ }
2791
3303
  pendingTimeouts = [];
2792
3304
  adPlaying = false;
2793
3305
  setAdPlayingFlag(false);
@@ -2807,6 +3319,35 @@ function createHlsAdPlayer(contentVideo, options) {
2807
3319
  isAdPlaying: function isAdPlaying() {
2808
3320
  return adPlaying;
2809
3321
  },
3322
+ setFunnelContext: function setFunnelContext(context) {
3323
+ funnelContext = _object_spread({}, context);
3324
+ },
3325
+ abortPendingRequest: function abortPendingRequest() {
3326
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3327
+ if (pendingVastRequests.size === 0) return;
3328
+ pendingRequestAbortReason = reason;
3329
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3330
+ try {
3331
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3332
+ var controller = _step.value;
3333
+ controller.abort();
3334
+ }
3335
+ } catch (err) {
3336
+ _didIteratorError = true;
3337
+ _iteratorError = err;
3338
+ } finally{
3339
+ try {
3340
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3341
+ _iterator.return();
3342
+ }
3343
+ } finally{
3344
+ if (_didIteratorError) {
3345
+ throw _iteratorError;
3346
+ }
3347
+ }
3348
+ }
3349
+ pendingVastRequests.clear();
3350
+ },
2810
3351
  resize: function resize(width, height) {
2811
3352
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2812
3353
  if (adContainerEl) {
@@ -2842,6 +3383,13 @@ function createHlsAdPlayer(contentVideo, options) {
2842
3383
  if (adVideoElement && adPlaying) {
2843
3384
  var clamped = Math.max(0, Math.min(1, volume));
2844
3385
  adVideoElement.volume = clamped;
3386
+ var userActivation = navigator.userActivation;
3387
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3388
+ logFunnel("unmute_blocked_without_gesture", {
3389
+ requestedVolume: clamped
3390
+ });
3391
+ return;
3392
+ }
2845
3393
  adVideoElement.muted = clamped === 0;
2846
3394
  }
2847
3395
  },
@@ -6905,7 +7453,7 @@ var AdTimingService = /*#__PURE__*/ function() {
6905
7453
  {
6906
7454
  key: "adFitsRemainingBudget",
6907
7455
  value: function adFitsRemainingBudget(durationMs) {
6908
- if (durationMs <= 0) {
7456
+ if (durationMs <= 0 || this.expectedAdBreakDurationMs == null) {
6909
7457
  return true;
6910
7458
  }
6911
7459
  return durationMs <= this.getDurationBudgetRemainingMs();
@@ -6964,6 +7512,11 @@ var AdTimingService = /*#__PURE__*/ function() {
6964
7512
  value: function markAdStarted() {
6965
7513
  this.currentAdIndex++;
6966
7514
  this.totalAdsInBreak = this.currentAdIndex;
7515
+ }
7516
+ },
7517
+ {
7518
+ key: "noteAdRequestSent",
7519
+ value: function noteAdRequestSent() {
6967
7520
  this.totalAdRequestsInBreak++;
6968
7521
  this.lastAdRequestTime = Date.now();
6969
7522
  }
@@ -7015,6 +7568,9 @@ var AdTimingService = /*#__PURE__*/ function() {
7015
7568
  if (message.includes("timeout")) {
7016
7569
  return true;
7017
7570
  }
7571
+ if (message.includes("ad player destroyed") || message.includes("aborted")) {
7572
+ return true;
7573
+ }
7018
7574
  if (message.includes("rate limit") || message.includes("too many requests")) {
7019
7575
  return true;
7020
7576
  }
@@ -8148,6 +8704,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8148
8704
  this.adDetectSentForCurrentBreak = false;
8149
8705
  this.continuousFetchingActive = false;
8150
8706
  this.continuousFetchLoopRunning = false;
8707
+ this.breakFunnel = {};
8708
+ this.controllerCallInFlight = false;
8709
+ this.playbackStartedForCurrentRequest = false;
8710
+ this.opportunityEpoch = -1;
8151
8711
  this.adRequestQueue = [];
8152
8712
  this.adPodQueue = [];
8153
8713
  this.maxPlaceholderDurationMs = 5e3;
@@ -8200,7 +8760,25 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8200
8760
  adPlayer.on("ad_interaction", function(event) {
8201
8761
  if (event) _this.host.onAdInteraction(event);
8202
8762
  });
8763
+ adPlayer.on("ad_funnel", function(payload) {
8764
+ if (!(payload === null || payload === void 0 ? void 0 : payload.stage)) return;
8765
+ _this.countFunnelStage(payload.stage);
8766
+ if (payload.reason) {
8767
+ _this.countFunnelStage("".concat(payload.stage, ":").concat(payload.reason));
8768
+ }
8769
+ if (payload.stage === "impression_fired" && payload.pixelCount != null) {
8770
+ _this.countFunnelStage("impression_urls", payload.pixelCount);
8771
+ }
8772
+ if (payload.visibilityState === "hidden") {
8773
+ _this.countFunnelStage("while_hidden");
8774
+ }
8775
+ });
8203
8776
  adPlayer.on("ad_impression", function() {
8777
+ _this.timing.consecutiveFailures = 0;
8778
+ if (!_this.playbackStartedForCurrentRequest) {
8779
+ _this.playbackStartedForCurrentRequest = true;
8780
+ _this.timing.markAdStarted();
8781
+ }
8204
8782
  sendAdImpressionTracking(_this.host.config.licenseKey, _object_spread_props(_object_spread({
8205
8783
  source: "hls",
8206
8784
  adIndex: _this.timing.currentAdIndex
@@ -8244,6 +8822,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8244
8822
  }
8245
8823
  }
8246
8824
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
8825
+ if (_this.controllerCallInFlight) {
8826
+ _this.timing.recordGamNoFill();
8827
+ return;
8828
+ }
8247
8829
  _this.handleAdFailure();
8248
8830
  });
8249
8831
  adPlayer.on("content_pause", function() {
@@ -8315,6 +8897,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8315
8897
  }
8316
8898
  var preservedMutedState = adPlayer.getOriginalMutedState();
8317
8899
  var preservedVolumeState = adPlayer.getOriginalVolume();
8900
+ this.playbackStartedForCurrentRequest = false;
8318
8901
  if (adPlayer) {
8319
8902
  try {
8320
8903
  adPlayer.destroy();
@@ -8404,9 +8987,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8404
8987
  if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {
8405
8988
  this.timing.expectedAdBreakDurationMs = adBreakDurationMs;
8406
8989
  }
8990
+ this.noteOpportunity("scte35", this.cueManager.activeScte35BreakKey);
8407
8991
  return [
8408
8992
  4,
8409
- this.startOptimizedPod(baseVastUrl, adBreakDurationMs, currentMuted, currentVolume)
8993
+ this.startOptimizedPod(baseVastUrl, adBreakDurationMs)
8410
8994
  ];
8411
8995
  case 1:
8412
8996
  podPlayed = _state.sent();
@@ -8440,7 +9024,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8440
9024
  value: // ───────────────────────────────────────────────────────────────
8441
9025
  // Optimized pod (single multi-ad request)
8442
9026
  // ───────────────────────────────────────────────────────────────
8443
- function startOptimizedPod(baseVastUrl, breakDurationMs, currentMuted, currentVolume) {
9027
+ function startOptimizedPod(baseVastUrl, breakDurationMs) {
8444
9028
  return _async_to_generator(function() {
8445
9029
  var podUrl, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
8446
9030
  return _ts_generator(this, function(_state) {
@@ -8479,10 +9063,13 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8479
9063
  case 2:
8480
9064
  _state.sent();
8481
9065
  this.timing.startAdRequestWatchdog(requestToken);
8482
- this.timing.lastAdRequestTime = Date.now();
9066
+ this.timing.noteAdRequestSent();
9067
+ this.beginFunnelRequest(adPlayer, requestToken);
8483
9068
  return [
8484
9069
  4,
8485
- adPlayer.requestAds(podUrl)
9070
+ this.callController(function() {
9071
+ return adPlayer.requestAds(podUrl);
9072
+ })
8486
9073
  ];
8487
9074
  case 3:
8488
9075
  _state.sent();
@@ -8511,16 +9098,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8511
9098
  this.timing.startAdFailsafeTimer(requestToken);
8512
9099
  return [
8513
9100
  4,
8514
- adPlayer.play()
9101
+ this.callController(function() {
9102
+ return adPlayer.play();
9103
+ })
8515
9104
  ];
8516
9105
  case 4:
8517
9106
  _state.sent();
8518
- this.timing.markAdStarted();
8519
9107
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
8520
9108
  this.timing.scheduleAdStopAtBreakBoundary();
8521
9109
  }
8522
- adPlayer.setAdVolume(currentMuted ? 0 : currentVolume);
8523
- this.timing.consecutiveFailures = 0;
9110
+ adPlayer.setAdVolume(getAdAudioVolume(adPlayer));
8524
9111
  this.continuousFetchingActive = true;
8525
9112
  this.startContinuousFetching(baseVastUrl);
8526
9113
  return [
@@ -8885,7 +9472,6 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8885
9472
  ];
8886
9473
  case 3:
8887
9474
  _state.sent();
8888
- this.timing.consecutiveFailures = 0;
8889
9475
  return [
8890
9476
  3,
8891
9477
  8
@@ -8898,6 +9484,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8898
9484
  3,
8899
9485
  6
8900
9486
  ];
9487
+ this.timing.consecutiveFailures++;
8901
9488
  return [
8902
9489
  4,
8903
9490
  this.tryNextAvailableAdWithRateLimit()
@@ -8989,11 +9576,137 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8989
9576
  }
8990
9577
  }
8991
9578
  },
9579
+ {
9580
+ key: "countFunnelStage",
9581
+ value: function countFunnelStage(stage) {
9582
+ var amount = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1;
9583
+ var _this_breakFunnel_stage;
9584
+ this.breakFunnel[stage] = ((_this_breakFunnel_stage = this.breakFunnel[stage]) !== null && _this_breakFunnel_stage !== void 0 ? _this_breakFunnel_stage : 0) + amount;
9585
+ }
9586
+ },
9587
+ {
9588
+ key: "logOrchestratorFunnel",
9589
+ value: function logOrchestratorFunnel(stage) {
9590
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
9591
+ this.countFunnelStage(stage);
9592
+ console.log("[AdBreak][FUNNEL] ".concat(stage), _object_spread({
9593
+ breakId: this.timing.adBreakEpoch,
9594
+ requestId: this.currentRequestId,
9595
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0
9596
+ }, extra));
9597
+ }
9598
+ },
9599
+ {
9600
+ key: "noteOpportunity",
9601
+ value: function noteOpportunity(source, breakKey) {
9602
+ if (breakKey && breakKey === this.opportunityBreakKey && this.opportunityEpoch === this.timing.adBreakEpoch) {
9603
+ this.logOrchestratorFunnel("duplicate_break_start", {
9604
+ source: source,
9605
+ breakKey: breakKey
9606
+ });
9607
+ return;
9608
+ }
9609
+ this.opportunityBreakKey = breakKey;
9610
+ this.opportunityEpoch = this.timing.adBreakEpoch;
9611
+ this.logOrchestratorFunnel("opportunity_created", {
9612
+ source: source,
9613
+ breakKey: breakKey,
9614
+ expectedDurationMs: this.timing.expectedAdBreakDurationMs
9615
+ });
9616
+ }
9617
+ },
9618
+ {
9619
+ key: "beginFunnelRequest",
9620
+ value: function beginFunnelRequest(adPlayer, requestToken) {
9621
+ var _adPlayer_setFunnelContext;
9622
+ if (this.controllerCallInFlight) {
9623
+ this.logOrchestratorFunnel("duplicate_request_detected", {
9624
+ newRequestId: requestToken
9625
+ });
9626
+ }
9627
+ this.currentRequestId = requestToken;
9628
+ this.requestStartedAt = Date.now();
9629
+ (_adPlayer_setFunnelContext = adPlayer.setFunnelContext) === null || _adPlayer_setFunnelContext === void 0 ? void 0 : _adPlayer_setFunnelContext.call(adPlayer, {
9630
+ breakId: this.timing.adBreakEpoch,
9631
+ requestId: requestToken
9632
+ });
9633
+ }
9634
+ },
9635
+ {
9636
+ key: "isAdLoadingWithoutPlayback",
9637
+ value: function isAdLoadingWithoutPlayback() {
9638
+ return this.host.getAdPlayer().isAdPlaying() && !this.playbackStartedForCurrentRequest;
9639
+ }
9640
+ },
9641
+ {
9642
+ key: "noteStopBeforeStart",
9643
+ value: function noteStopBeforeStart(reason) {
9644
+ if (!this.isAdLoadingWithoutPlayback()) return;
9645
+ this.logOrchestratorFunnel("ad_stopped_before_start", {
9646
+ reason: reason,
9647
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9648
+ });
9649
+ }
9650
+ },
9651
+ {
9652
+ key: "handleRequestWatchdogTimeout",
9653
+ value: function handleRequestWatchdogTimeout() {
9654
+ var adPlayer = this.host.getAdPlayer();
9655
+ if (this.controllerCallInFlight && adPlayer.abortPendingRequest) {
9656
+ this.logOrchestratorFunnel("request_aborted_timeout", {
9657
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9658
+ });
9659
+ adPlayer.abortPendingRequest("VAST request aborted after request watchdog timeout");
9660
+ return;
9661
+ }
9662
+ this.handleAdFailure();
9663
+ }
9664
+ },
9665
+ {
9666
+ key: "callController",
9667
+ value: function callController(call) {
9668
+ return _async_to_generator(function() {
9669
+ return _ts_generator(this, function(_state) {
9670
+ switch(_state.label){
9671
+ case 0:
9672
+ this.controllerCallInFlight = true;
9673
+ _state.label = 1;
9674
+ case 1:
9675
+ _state.trys.push([
9676
+ 1,
9677
+ ,
9678
+ 3,
9679
+ 4
9680
+ ]);
9681
+ return [
9682
+ 4,
9683
+ call()
9684
+ ];
9685
+ case 2:
9686
+ _state.sent();
9687
+ return [
9688
+ 3,
9689
+ 4
9690
+ ];
9691
+ case 3:
9692
+ this.controllerCallInFlight = false;
9693
+ return [
9694
+ 7
9695
+ ];
9696
+ case 4:
9697
+ return [
9698
+ 2
9699
+ ];
9700
+ }
9701
+ });
9702
+ }).call(this);
9703
+ }
9704
+ },
8992
9705
  {
8993
9706
  key: "playSingleAd",
8994
9707
  value: function playSingleAd(vastTagUrl) {
8995
9708
  return _async_to_generator(function() {
8996
- var adPlayer, requestToken, ap, requestUrl, playError, error, errorMessage;
9709
+ var adPlayer, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, playError, error, errorMessage;
8997
9710
  return _ts_generator(this, function(_state) {
8998
9711
  switch(_state.label){
8999
9712
  case 0:
@@ -9035,13 +9748,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9035
9748
  case 2:
9036
9749
  _state.sent();
9037
9750
  this.timing.startAdRequestWatchdog(requestToken);
9038
- this.timing.lastAdRequestTime = Date.now();
9751
+ this.timing.noteAdRequestSent();
9039
9752
  ap = this.host.getAdPlayer();
9040
9753
  requestUrl = this.withCurrentPodBudget(vastTagUrl);
9041
9754
  this.currentVastUrl = requestUrl;
9755
+ this.beginFunnelRequest(ap, requestToken);
9042
9756
  return [
9043
9757
  4,
9044
- ap.requestAds(requestUrl)
9758
+ this.callController(function() {
9759
+ return ap.requestAds(requestUrl);
9760
+ })
9045
9761
  ];
9046
9762
  case 3:
9047
9763
  _state.sent();
@@ -9055,6 +9771,14 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9055
9771
  2
9056
9772
  ];
9057
9773
  if (!this.timing.ensureLoadedAdFitsBudget(ap)) {
9774
+ ;
9775
+ adDurationS = (_ap_getLoadedAdDuration = ap.getLoadedAdDuration) === null || _ap_getLoadedAdDuration === void 0 ? void 0 : _ap_getLoadedAdDuration.call(ap);
9776
+ remainingMs = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
9777
+ this.logOrchestratorFunnel("discarded_budget", {
9778
+ vastUrl: requestUrl,
9779
+ adDurationMs: adDurationS != null ? adDurationS * 1e3 : void 0,
9780
+ remainingMs: remainingMs
9781
+ });
9058
9782
  this.timing.rejectLoadedAdForDuration(ap);
9059
9783
  this.recreateAdController();
9060
9784
  throw new Error("ad_duration_exceeds_budget");
@@ -9070,16 +9794,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9070
9794
  this.timing.startAdFailsafeTimer(requestToken);
9071
9795
  return [
9072
9796
  4,
9073
- ap.play()
9797
+ this.callController(function() {
9798
+ return ap.play();
9799
+ })
9074
9800
  ];
9075
9801
  case 5:
9076
9802
  _state.sent();
9077
- this.timing.markAdStarted();
9078
9803
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
9079
9804
  this.timing.scheduleAdStopAtBreakBoundary();
9080
9805
  }
9081
9806
  ap.setAdVolume(getAdAudioVolume(ap));
9082
- this.timing.consecutiveFailures = 0;
9083
9807
  this.timing.temporaryFailureUrls.delete(vastTagUrl);
9084
9808
  return [
9085
9809
  3,
@@ -9243,7 +9967,6 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9243
9967
  ];
9244
9968
  case 5:
9245
9969
  _state.sent();
9246
- this.timing.consecutiveFailures = 0;
9247
9970
  return [
9248
9971
  3,
9249
9972
  10
@@ -9255,6 +9978,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9255
9978
  3,
9256
9979
  8
9257
9980
  ];
9981
+ this.timing.consecutiveFailures++;
9258
9982
  return [
9259
9983
  4,
9260
9984
  this.tryNextAvailableAdWithRateLimit()
@@ -9305,6 +10029,67 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9305
10029
  // ───────────────────────────────────────────────────────────────
9306
10030
  // Ad break completion
9307
10031
  // ───────────────────────────────────────────────────────────────
10032
+ key: "logBreakFunnel",
10033
+ value: function logBreakFunnel() {
10034
+ var funnel = this.breakFunnel;
10035
+ this.breakFunnel = {};
10036
+ if (Object.keys(funnel).length === 0) return;
10037
+ var count = function count(stage) {
10038
+ var _funnel_stage;
10039
+ return (_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0;
10040
+ };
10041
+ var breakId = this.opportunityEpoch;
10042
+ if (count("request_sent") > 0 && count("impression_fired") === 0) {
10043
+ console.log("[AdBreak][FUNNEL] break_abandoned_before_start", {
10044
+ breakId: breakId,
10045
+ requests: count("request_sent")
10046
+ });
10047
+ }
10048
+ console.log("[AdBreak][FUNNEL] Break summary", {
10049
+ breakId: breakId,
10050
+ opportunities: count("opportunity_created"),
10051
+ requests: count("request_sent"),
10052
+ duplicates: count("duplicate_request_detected") + count("duplicate_break_start"),
10053
+ filled: count("vast_received"),
10054
+ noFill: count("no_fill"),
10055
+ requestFailed: count("request_failed"),
10056
+ requestAbortedTimeout: count("request_aborted_timeout"),
10057
+ credentialsRetries: count("vast_credentials_retry"),
10058
+ wrapperFailures: count("wrapper_fetch:failure"),
10059
+ noSupportedMedia: count("vast_no_supported_media"),
10060
+ vpaidOnly: count("vast_no_supported_media:vpaid_only"),
10061
+ missingImpression: count("vast_missing_impression"),
10062
+ discardedBudget: count("discarded_budget"),
10063
+ mediaCandidates: count("media_candidate:accepted") + count("media_candidate:rejected"),
10064
+ mediaRejected: count("media_candidate:rejected"),
10065
+ mediaFallbacks: count("media_fallback"),
10066
+ playCalled: count("play_called"),
10067
+ playRejected: count("play_rejected"),
10068
+ mutedRetry: count("muted_retry"),
10069
+ startTimeouts: count("play_resolved_but_never_started"),
10070
+ impressions: count("impression_fired"),
10071
+ impressionUrls: count("impression_urls"),
10072
+ trackingRequests: count("tracking_request_created"),
10073
+ trackingNotLoaded: count("tracking_request_settled:error") + count("tracking_request_settled:timeout"),
10074
+ trackingUnexpandedMacros: count("tracking_url_unexpanded_macro"),
10075
+ trackingInvalidUrls: count("tracking_url_invalid"),
10076
+ vastAdFallbacks: count("vast_ad_fallback"),
10077
+ mediaEvents: count("media_event"),
10078
+ quartile25: count("first_quartile"),
10079
+ quartile50: count("midpoint"),
10080
+ quartile75: count("third_quartile"),
10081
+ complete: count("complete"),
10082
+ stoppedBeforeStart: count("stopped_before_start"),
10083
+ stoppedBeforeStartByBreakEnd: count("ad_stopped_before_start"),
10084
+ unexpectedUnmutes: count("unexpected_unmute"),
10085
+ unmuteBlocked: count("unmute_blocked_without_gesture"),
10086
+ visibilityHidden: count("while_hidden"),
10087
+ playbackFailures: count("play_failed") + count("media_error") + count("hls_fatal") + count("stall") + count("decode_failure") + count("media_unsupported"),
10088
+ stages: funnel
10089
+ });
10090
+ }
10091
+ },
10092
+ {
9308
10093
  key: "handleAdPodComplete",
9309
10094
  value: function handleAdPodComplete() {
9310
10095
  if (this.debug) {
@@ -9325,6 +10110,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9325
10110
  this.adPodQueue = [];
9326
10111
  this.showAds = false;
9327
10112
  this.host.getAdPlayer().stop().catch(function() {});
10113
+ this.logBreakFunnel();
9328
10114
  var restoredMuted = this.host.getAdPlayer().getOriginalMutedState();
9329
10115
  var restoredVolume = this.host.getAdPlayer().getOriginalVolume();
9330
10116
  if (this.host.video.muted !== restoredMuted) {
@@ -9676,7 +10462,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9676
10462
  _this.startScte35AdBreak(marker, cueKey, marker.durationSeconds != null ? marker.durationSeconds * 1e3 : _this.timing.expectedAdBreakDurationMs);
9677
10463
  },
9678
10464
  onWatchdogTimeout: function onWatchdogTimeout() {
9679
- return _this.adBreak.handleAdFailure();
10465
+ return _this.adBreak.handleRequestWatchdogTimeout();
9680
10466
  },
9681
10467
  onFailsafeTimeout: function onFailsafeTimeout() {
9682
10468
  return _this.adBreak.handleAdFailure();
@@ -9781,6 +10567,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9781
10567
  licenseKey: this.config.licenseKey
9782
10568
  } : {}, ((_this_hlsEngine = this.hlsEngine) === null || _this_hlsEngine === void 0 ? void 0 : _this_hlsEngine.hls) ? {
9783
10569
  mainHlsInstance: this.hlsEngine.hls
10570
+ } : {}, this.config.adMediaStartTimeoutMs != null ? {
10571
+ mediaStartTimeoutMs: this.config.adMediaStartTimeoutMs
9784
10572
  } : {}));
9785
10573
  }
9786
10574
  },
@@ -10135,6 +10923,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10135
10923
  this.timing.clearAdStartTimer();
10136
10924
  this.timing.clearAdStopTimer();
10137
10925
  if (adPlaying) {
10926
+ this.adBreak.noteStopBeforeStart("scte_end");
10138
10927
  this.adPlayer.stop().catch(function() {});
10139
10928
  }
10140
10929
  this.adBreak.handleAdPodComplete();
@@ -10174,6 +10963,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10174
10963
  console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(overrunMs, "ms) - hard-stopping ads and resuming stream"));
10175
10964
  }
10176
10965
  if (adPlaying) {
10966
+ this.adBreak.noteStopBeforeStart("break_boundary");
10177
10967
  this.adPlayer.stop().catch(function() {});
10178
10968
  }
10179
10969
  this.adBreak.handleAdPodComplete();
@@ -10302,6 +11092,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10302
11092
  this.adBreak.showAds = true;
10303
11093
  this.adBreak.inAdBreak = true;
10304
11094
  this.timing.currentAdBreakStartWallClockMs = Date.now();
11095
+ if (durationMs > 0) {
11096
+ this.timing.setAdBreakDurationBoundary(durationMs);
11097
+ }
11098
+ this.adBreak.noteOpportunity("vmap", key);
10305
11099
  _state.label = 1;
10306
11100
  case 1:
10307
11101
  _state.trys.push([