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.
@@ -774,7 +774,7 @@ function toVastMediaErrorCode(error) {
774
774
  }
775
775
  }
776
776
  function createHlsAdPlayer(contentVideo, options) {
777
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
777
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
778
778
  var adPlaying = false;
779
779
  var originalMutedState = false;
780
780
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -806,6 +806,16 @@ function createHlsAdPlayer(contentVideo, options) {
806
806
  var sawDecodedVideoFrame = false;
807
807
  var videoFrameCallbackHandle;
808
808
  var pendingPlayPromise;
809
+ var currentVastTagUrl;
810
+ var funnelContext = {};
811
+ var mediaCandidates = [];
812
+ var mediaCandidateIndex = 0;
813
+ var mediaStartTimerId;
814
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
815
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
816
+ var pendingVastRequests = /* @__PURE__ */ new Set();
817
+ var pendingRequestAbortReason;
818
+ var forcedMuteByAutoplay = false;
809
819
  function createTrackingState() {
810
820
  return {
811
821
  impression: false,
@@ -856,6 +866,77 @@ function createHlsAdPlayer(contentVideo, options) {
856
866
  }
857
867
  }
858
868
  }
869
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
870
+ "ppid",
871
+ "rdid",
872
+ "idtype",
873
+ "is_lat",
874
+ "ifa",
875
+ "idfa",
876
+ "aaid",
877
+ "uid",
878
+ "user_id",
879
+ "userid",
880
+ "device_id",
881
+ "deviceid",
882
+ "ip",
883
+ "ua",
884
+ "gdpr_consent",
885
+ "us_privacy",
886
+ "gpp",
887
+ "addtl_consent",
888
+ "cust_params",
889
+ "email"
890
+ ]);
891
+ function redactUrl(url) {
892
+ if (!url) return url;
893
+ try {
894
+ var parsed = new URL(url);
895
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
896
+ try {
897
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
898
+ var key = _step.value;
899
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
900
+ parsed.searchParams.set(key, "REDACTED");
901
+ }
902
+ }
903
+ } catch (err) {
904
+ _didIteratorError = true;
905
+ _iteratorError = err;
906
+ } finally{
907
+ try {
908
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
909
+ _iterator.return();
910
+ }
911
+ } finally{
912
+ if (_didIteratorError) {
913
+ throw _iteratorError;
914
+ }
915
+ }
916
+ }
917
+ return parsed.toString();
918
+ } catch (unused) {
919
+ return url.split("?")[0];
920
+ }
921
+ }
922
+ function logFunnel(stage) {
923
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
924
+ var payload = _object_spread({
925
+ stage: stage,
926
+ breakId: funnelContext.breakId,
927
+ requestId: funnelContext.requestId,
928
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
929
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
930
+ podIndex: podIndex,
931
+ podSize: podAds.length,
932
+ vastUrl: redactUrl(currentVastTagUrl),
933
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
934
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
935
+ muted: adVideoElement ? adVideoElement.muted : void 0
936
+ }, extra);
937
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
938
+ emit("ad_funnel", payload);
939
+ }
859
940
  function buildTrackingMacroContext() {
860
941
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
861
942
  var _options2_ad;
@@ -895,20 +976,53 @@ function createHlsAdPlayer(contentVideo, options) {
895
976
  urls.forEach(function(url) {
896
977
  try {
897
978
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
979
+ var trackingHost;
980
+ try {
981
+ trackingHost = new URL(trackingUrl).host;
982
+ } catch (unused) {
983
+ logFunnel("tracking_url_invalid", {
984
+ trackingUrl: redactUrl(trackingUrl)
985
+ });
986
+ return;
987
+ }
988
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
989
+ if (unexpanded) {
990
+ logFunnel("tracking_url_unexpanded_macro", {
991
+ trackingHost: trackingHost,
992
+ macros: Array.from(new Set(unexpanded))
993
+ });
994
+ }
898
995
  var img = new Image(1, 1);
899
996
  inFlightBeacons.add(img);
900
997
  var timeoutId;
901
- var release = function release() {
998
+ var release = function release(outcome) {
902
999
  if (timeoutId !== void 0) clearTimeout(timeoutId);
903
1000
  img.onload = null;
904
1001
  img.onerror = null;
905
1002
  inFlightBeacons.delete(img);
1003
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
1004
+ if (outcome !== "load") {
1005
+ logFunnel("tracking_request_settled", {
1006
+ reason: outcome,
1007
+ trackingHost: trackingHost
1008
+ });
1009
+ }
1010
+ };
1011
+ img.onload = function() {
1012
+ return release("load");
1013
+ };
1014
+ img.onerror = function() {
1015
+ return release("error");
906
1016
  };
907
- img.onload = release;
908
- img.onerror = release;
909
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
1017
+ timeoutId = setTimeout(function() {
1018
+ return release("timeout");
1019
+ }, BEACON_TIMEOUT_MS);
910
1020
  img.src = trackingUrl;
911
1021
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
1022
+ logFunnel("tracking_request_created", {
1023
+ trackingHost: trackingHost,
1024
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
1025
+ });
912
1026
  } catch (error) {
913
1027
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
914
1028
  }
@@ -938,54 +1052,80 @@ function createHlsAdPlayer(contentVideo, options) {
938
1052
  bitrate: level.bitrate || 5e6
939
1053
  };
940
1054
  }
941
- function selectBestMediaFile(mediaFiles) {
942
- if (mediaFiles.length === 0) {
943
- throw new Error("No media files available");
944
- }
945
- var firstFile = mediaFiles[0];
946
- if (!firstFile) {
947
- throw new Error("No media files available");
948
- }
949
- if (mediaFiles.length === 1) {
950
- return firstFile;
951
- }
1055
+ function getMediaTargetQuality() {
952
1056
  var mainQuality = getMainStreamQuality();
953
- if (!mainQuality) {
954
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
955
- return firstFile;
956
- }
957
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
958
- var scoredFiles = mediaFiles.map(function(file) {
959
- var widthDiff = Math.abs(file.width - mainQuality.width);
960
- var heightDiff = Math.abs(file.height - mainQuality.height);
961
- var resolutionDiff = widthDiff + heightDiff;
962
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
963
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
964
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
965
- return {
1057
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
1058
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
1059
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
1060
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
1061
+ return null;
1062
+ }
1063
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
1064
+ width: containerWidth,
1065
+ height: containerHeight,
1066
+ bitrate: 5e6
1067
+ };
1068
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
1069
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
1070
+ return {
1071
+ width: width,
1072
+ height: height,
1073
+ bitrate: base.bitrate
1074
+ };
1075
+ }
1076
+ function rankMediaCandidates(mediaFiles) {
1077
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
1078
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
1079
+ var target = getMediaTargetQuality();
1080
+ var accepted = [];
1081
+ mediaFiles.forEach(function(file, index) {
1082
+ var isHls = isHlsMediaFile(file);
1083
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
1084
+ var canPlay2 = probe.canPlayType(mimeForProbe);
1085
+ var playable = isHls ? import_hls.default.isSupported() || canPlay2 !== "" : canPlay2 !== "";
1086
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
1087
+ var details = {
1088
+ index: index,
1089
+ candidateUrl: file.url,
1090
+ candidateType: file.type,
1091
+ width: file.width,
1092
+ height: file.height,
1093
+ bitrate: file.bitrate,
1094
+ canPlayType: canPlay2,
1095
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
1096
+ };
1097
+ if (!playable) {
1098
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1099
+ reason: "rejected",
1100
+ why: "cannot_play_type"
1101
+ }));
1102
+ return;
1103
+ }
1104
+ var score = 0;
1105
+ if (target) {
1106
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
1107
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
1108
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
1109
+ }
1110
+ accepted.push({
966
1111
  file: file,
967
1112
  score: score,
968
- resolutionDiff: resolutionDiff,
969
- bitrateDiff: bitrateDiff
970
- };
1113
+ insecure: insecure
1114
+ });
1115
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1116
+ reason: "accepted",
1117
+ // Mixed-content media is often auto-upgraded, so it is kept as a last resort.
1118
+ why: insecure ? "insecure_http_deprioritized" : "playable",
1119
+ score: score
1120
+ }));
971
1121
  });
972
- scoredFiles.sort(function(a, b) {
1122
+ accepted.sort(function(a, b) {
1123
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
973
1124
  return a.score - b.score;
974
1125
  });
975
- var bestMatch = scoredFiles[0];
976
- if (!bestMatch) {
977
- console.log("[HlsAdPlayer] No best match found, using first media file");
978
- return firstFile;
979
- }
980
- console.log("[HlsAdPlayer] Selected media file:", {
981
- url: bestMatch.file.url,
982
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
983
- bitrate: bestMatch.file.bitrate,
984
- score: bestMatch.score,
985
- resolutionDiff: bestMatch.resolutionDiff,
986
- bitrateDiff: bestMatch.bitrateDiff
1126
+ return accepted.map(function(entry) {
1127
+ return entry.file;
987
1128
  });
988
- return bestMatch.file;
989
1129
  }
990
1130
  function isHlsMediaFile(mediaFile) {
991
1131
  var type = mediaFile.type.toLowerCase();
@@ -1002,9 +1142,10 @@ function createHlsAdPlayer(contentVideo, options) {
1002
1142
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
1003
1143
  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");
1004
1144
  }
1005
- function collectVideoMediaFiles(linear, verbose) {
1145
+ function collectVideoMediaFiles(linear, verbose, stats) {
1006
1146
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
1007
1147
  var mediaFiles = [];
1148
+ if (stats) stats.total += mediaFileElements.length;
1008
1149
  if (verbose) {
1009
1150
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
1010
1151
  }
@@ -1025,6 +1166,7 @@ function createHlsAdPlayer(contentVideo, options) {
1025
1166
  }
1026
1167
  var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1027
1168
  if (apiFramework === "VPAID") {
1169
+ if (stats) stats.vpaid++;
1028
1170
  if (verbose) {
1029
1171
  console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
1030
1172
  }
@@ -1040,11 +1182,13 @@ function createHlsAdPlayer(contentVideo, options) {
1040
1182
  bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
1041
1183
  };
1042
1184
  if (isAudioMediaFile(mediaFile)) {
1185
+ if (stats) stats.audio++;
1043
1186
  console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
1044
1187
  return;
1045
1188
  }
1046
1189
  var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1047
1190
  if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
1191
+ if (stats) stats.audio++;
1048
1192
  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'));
1049
1193
  return;
1050
1194
  }
@@ -1053,8 +1197,11 @@ function createHlsAdPlayer(contentVideo, options) {
1053
1197
  if (verbose) {
1054
1198
  console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
1055
1199
  }
1056
- } else if (verbose) {
1057
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1200
+ } else {
1201
+ if (stats) stats.unsupported++;
1202
+ if (verbose) {
1203
+ console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1204
+ }
1058
1205
  }
1059
1206
  });
1060
1207
  return mediaFiles;
@@ -1178,26 +1325,58 @@ function createHlsAdPlayer(contentVideo, options) {
1178
1325
  }
1179
1326
  function parseVastXml(xmlString) {
1180
1327
  try {
1181
- var _adElements_find;
1182
1328
  var xmlDoc = parseXml(xmlString);
1183
1329
  if (!xmlDoc) return {
1184
1330
  type: "empty"
1185
1331
  };
1186
1332
  var root = xmlDoc.documentElement;
1187
1333
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1188
- var adElement = (_adElements_find = adElements.find(function(el) {
1189
- return getAdSequence(el) === void 0;
1190
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1191
- if (!adElement) {
1334
+ if (adElements.length === 0) {
1192
1335
  var _root_getAttribute;
1193
1336
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1194
1337
  return emptyVastResult(root);
1195
1338
  }
1196
- var parsed = parseAdElement(adElement, true);
1197
- if (parsed.type === "wrapper") {
1198
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1339
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1340
+ return getAdSequence(el) === void 0;
1341
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1342
+ return getAdSequence(el) !== void 0;
1343
+ })));
1344
+ var firstEmpty;
1345
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1346
+ try {
1347
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1348
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1349
+ var parsed = parseAdElement(adElement, true);
1350
+ if (parsed.type === "empty") {
1351
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1352
+ continue;
1353
+ }
1354
+ if (index > 0) {
1355
+ logFunnel("vast_ad_fallback", {
1356
+ usedAdIndex: index,
1357
+ adCount: ordered.length
1358
+ });
1359
+ }
1360
+ if (parsed.type === "wrapper") {
1361
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1362
+ }
1363
+ return parsed;
1364
+ }
1365
+ } catch (err) {
1366
+ _didIteratorError = true;
1367
+ _iteratorError = err;
1368
+ } finally{
1369
+ try {
1370
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1371
+ _iterator.return();
1372
+ }
1373
+ } finally{
1374
+ if (_didIteratorError) {
1375
+ throw _iteratorError;
1376
+ }
1377
+ }
1199
1378
  }
1200
- return parsed;
1379
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1201
1380
  } catch (error) {
1202
1381
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1203
1382
  return {
@@ -1243,6 +1422,10 @@ function createHlsAdPlayer(contentVideo, options) {
1243
1422
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1244
1423
  if (adElement.getAttribute("conditionalAd") === "true") {
1245
1424
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1425
+ logFunnel("vast_no_supported_media", {
1426
+ reason: "vpaid_only",
1427
+ conditionalAd: true
1428
+ });
1246
1429
  return {
1247
1430
  type: "empty",
1248
1431
  errorUrls: errorUrls,
@@ -1251,11 +1434,17 @@ function createHlsAdPlayer(contentVideo, options) {
1251
1434
  }
1252
1435
  var linear;
1253
1436
  var mediaFiles = [];
1437
+ var rejectStats = {
1438
+ total: 0,
1439
+ vpaid: 0,
1440
+ audio: 0,
1441
+ unsupported: 0
1442
+ };
1254
1443
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1255
1444
  try {
1256
1445
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1257
1446
  var candidate = _step.value;
1258
- var files = collectVideoMediaFiles(candidate, verbose);
1447
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1259
1448
  if (files.length > 0) {
1260
1449
  linear = candidate;
1261
1450
  mediaFiles = files;
@@ -1278,6 +1467,10 @@ function createHlsAdPlayer(contentVideo, options) {
1278
1467
  }
1279
1468
  if (!linear) {
1280
1469
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1470
+ var reason = rejectStats.total === 0 ? "no_mediafiles" : rejectStats.vpaid > 0 ? "vpaid_only" : rejectStats.audio > 0 ? "audio_only" : "unsupported_type";
1471
+ logFunnel("vast_no_supported_media", _object_spread({
1472
+ reason: reason
1473
+ }, rejectStats));
1281
1474
  return {
1282
1475
  type: "empty",
1283
1476
  errorUrls: errorUrls,
@@ -1313,7 +1506,11 @@ function createHlsAdPlayer(contentVideo, options) {
1313
1506
  return _ts_generator(this, function(_state) {
1314
1507
  switch(_state.label){
1315
1508
  case 0:
1509
+ if (destroyed) {
1510
+ throw new Error("VAST request skipped: ad player destroyed");
1511
+ }
1316
1512
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1513
+ if (controller) pendingVastRequests.add(controller);
1317
1514
  timeoutId = controller ? setTimeout(function() {
1318
1515
  return controller.abort();
1319
1516
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
@@ -1362,6 +1559,9 @@ function createHlsAdPlayer(contentVideo, options) {
1362
1559
  6
1363
1560
  ];
1364
1561
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1562
+ logFunnel("vast_credentials_retry", {
1563
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1564
+ });
1365
1565
  return [
1366
1566
  4,
1367
1567
  requestVast("omit")
@@ -1395,11 +1595,15 @@ function createHlsAdPlayer(contentVideo, options) {
1395
1595
  case 10:
1396
1596
  error1 = _state.sent();
1397
1597
  if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1598
+ if (pendingRequestAbortReason) {
1599
+ throw new Error("".concat(pendingRequestAbortReason, " (timeout): ").concat(vastTagUrl));
1600
+ }
1398
1601
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1399
1602
  }
1400
1603
  throw error1;
1401
1604
  case 11:
1402
1605
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1606
+ if (controller) pendingVastRequests.delete(controller);
1403
1607
  return [
1404
1608
  7
1405
1609
  ];
@@ -1413,7 +1617,7 @@ function createHlsAdPlayer(contentVideo, options) {
1413
1617
  }
1414
1618
  function fetchAndParseVastAd(_0) {
1415
1619
  return _async_to_generator(function(vastTagUrl) {
1416
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1620
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1417
1621
  var _arguments = arguments;
1418
1622
  return _ts_generator(this, function(_state) {
1419
1623
  switch(_state.label){
@@ -1421,6 +1625,11 @@ function createHlsAdPlayer(contentVideo, options) {
1421
1625
  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] : {
1422
1626
  followAdditionalWrappers: true
1423
1627
  };
1628
+ if (destroyed) return [
1629
+ 2,
1630
+ null
1631
+ ];
1632
+ fetchStartedAt = Date.now();
1424
1633
  _state.label = 1;
1425
1634
  case 1:
1426
1635
  _state.trys.push([
@@ -1443,14 +1652,35 @@ function createHlsAdPlayer(contentVideo, options) {
1443
1652
  error = _state.sent();
1444
1653
  if (depth === 0) throw error;
1445
1654
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1446
- fireTrackingPixels(accumulatedTracking.error, {
1447
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1655
+ logFunnel("wrapper_fetch", {
1656
+ reason: "failure",
1657
+ depth: depth,
1658
+ wrapperUrl: redactUrl(vastTagUrl),
1659
+ elapsedMs: Date.now() - fetchStartedAt,
1660
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1448
1661
  });
1662
+ if (!destroyed) {
1663
+ fireTrackingPixels(accumulatedTracking.error, {
1664
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1665
+ });
1666
+ }
1449
1667
  return [
1450
1668
  2,
1451
1669
  null
1452
1670
  ];
1453
1671
  case 4:
1672
+ if (destroyed) return [
1673
+ 2,
1674
+ null
1675
+ ];
1676
+ if (depth > 0) {
1677
+ logFunnel("wrapper_fetch", {
1678
+ reason: "success",
1679
+ depth: depth,
1680
+ wrapperUrl: redactUrl(vastTagUrl),
1681
+ elapsedMs: Date.now() - fetchStartedAt
1682
+ });
1683
+ }
1454
1684
  console.log("[HlsAdPlayer] VAST XML received");
1455
1685
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1456
1686
  parsed = parseVastXml(vastXml);
@@ -1482,6 +1712,9 @@ function createHlsAdPlayer(contentVideo, options) {
1482
1712
  ];
1483
1713
  }
1484
1714
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1715
+ logFunnel("inline_resolved", {
1716
+ depth: depth
1717
+ });
1485
1718
  return [
1486
1719
  2,
1487
1720
  parsed.ad
@@ -1502,6 +1735,10 @@ function createHlsAdPlayer(contentVideo, options) {
1502
1735
  ];
1503
1736
  case 1:
1504
1737
  vastXml = _state.sent();
1738
+ if (destroyed) return [
1739
+ 2,
1740
+ []
1741
+ ];
1505
1742
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1506
1743
  trimmedXml = vastXml.trim();
1507
1744
  if (trimmedXml.length === 0) {
@@ -1789,14 +2026,17 @@ function createHlsAdPlayer(contentVideo, options) {
1789
2026
  var progress = currentTime / currentAd.duration;
1790
2027
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1791
2028
  trackingFired.firstQuartile = true;
2029
+ logFunnel("first_quartile");
1792
2030
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1793
2031
  }
1794
2032
  if (progress >= 0.5 && !trackingFired.midpoint) {
1795
2033
  trackingFired.midpoint = true;
2034
+ logFunnel("midpoint");
1796
2035
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1797
2036
  }
1798
2037
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1799
2038
  trackingFired.thirdQuartile = true;
2039
+ logFunnel("third_quartile");
1800
2040
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1801
2041
  }
1802
2042
  };
@@ -1819,6 +2059,16 @@ function createHlsAdPlayer(contentVideo, options) {
1819
2059
  if (!trackingFired.impression) {
1820
2060
  trackingFired.impression = true;
1821
2061
  resolvedAds.add(currentAd);
2062
+ logFunnel("playing", {
2063
+ mutedByAutoplay: forcedMuteByAutoplay,
2064
+ candidateIndex: mediaCandidateIndex
2065
+ });
2066
+ logFunnel("impression_fired", {
2067
+ pixelCount: currentAd.trackingUrls.impression.length
2068
+ });
2069
+ if (currentAd.trackingUrls.impression.length === 0) {
2070
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
2071
+ }
1822
2072
  fireTrackingPixels(currentAd.trackingUrls.impression);
1823
2073
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1824
2074
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1841,6 +2091,7 @@ function createHlsAdPlayer(contentVideo, options) {
1841
2091
  sampleViewability();
1842
2092
  settleViewability();
1843
2093
  trackingFired.complete = true;
2094
+ logFunnel("complete");
1844
2095
  fireTrackingPixels(currentAd.trackingUrls.complete);
1845
2096
  console.log("[HlsAdPlayer] Ad completed");
1846
2097
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1849,16 +2100,41 @@ function createHlsAdPlayer(contentVideo, options) {
1849
2100
  handleAdComplete();
1850
2101
  };
1851
2102
  var onError = function onError(e) {
2103
+ var _adVideoElement_error, _adVideoElement_error1;
1852
2104
  if (!adPlaying) return;
1853
2105
  console.error("[HlsAdPlayer] Ad video error:", e);
1854
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1855
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1856
- return;
1857
- }
1858
- handleAdError();
2106
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
2107
+ logFunnel("media_error", {
2108
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
2109
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
2110
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2111
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2112
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2113
+ vastErrorCode: vastErrorCode
2114
+ });
2115
+ recoverFromAdFailure(vastErrorCode);
2116
+ };
2117
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
2118
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
2119
+ if (!adVideoElement.currentSrc) return;
2120
+ logFunnel("media_event", {
2121
+ reason: event.type,
2122
+ readyState: adVideoElement.readyState,
2123
+ networkState: adVideoElement.networkState,
2124
+ currentSrc: adVideoElement.currentSrc
2125
+ });
1859
2126
  };
1860
2127
  var onVolumeChange = function onVolumeChange() {
1861
2128
  if (!currentAd || !adVideoElement) return;
2129
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2130
+ var userActivation = navigator.userActivation;
2131
+ if (userActivation && !userActivation.isActive) {
2132
+ logFunnel("unexpected_unmute", {
2133
+ paused: adVideoElement.paused
2134
+ });
2135
+ }
2136
+ forcedMuteByAutoplay = false;
2137
+ }
1862
2138
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1863
2139
  if (!trackingFired.start) {
1864
2140
  trackingFired.lastMuted = muted;
@@ -1918,6 +2194,22 @@ function createHlsAdPlayer(contentVideo, options) {
1918
2194
  {
1919
2195
  type: "play",
1920
2196
  handler: onPlay
2197
+ },
2198
+ {
2199
+ type: "stalled",
2200
+ handler: onMediaDiagnostic
2201
+ },
2202
+ {
2203
+ type: "suspend",
2204
+ handler: onMediaDiagnostic
2205
+ },
2206
+ {
2207
+ type: "abort",
2208
+ handler: onMediaDiagnostic
2209
+ },
2210
+ {
2211
+ type: "emptied",
2212
+ handler: onMediaDiagnostic
1921
2213
  }
1922
2214
  ];
1923
2215
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2207,16 +2499,51 @@ function createHlsAdPlayer(contentVideo, options) {
2207
2499
  function settlePendingPlay() {
2208
2500
  pendingPlayPromise = void 0;
2209
2501
  }
2502
+ function toVastPlayErrorCode(error) {
2503
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2504
+ }
2505
+ function failAdPlayback(context, error) {
2506
+ var vastErrorCode = toVastPlayErrorCode(error);
2507
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2508
+ logFunnel("play_failed", {
2509
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2510
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2511
+ vastErrorCode: vastErrorCode
2512
+ });
2513
+ recoverFromAdFailure(vastErrorCode);
2514
+ }
2210
2515
  function startAdPlayback(context) {
2516
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2211
2517
  if (!adVideoElement) return;
2518
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2519
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2520
+ context: context,
2521
+ isConnected: adVideoElement.isConnected,
2522
+ clientWidth: adVideoElement.clientWidth,
2523
+ clientHeight: adVideoElement.clientHeight,
2524
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2525
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2526
+ });
2212
2527
  var playPromise = adVideoElement.play();
2213
2528
  pendingPlayPromise = playPromise;
2214
2529
  playPromise.catch(function(error) {
2215
2530
  if (pendingPlayPromise !== playPromise) {
2216
2531
  return;
2217
2532
  }
2218
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2219
- handleAdError();
2533
+ logFunnel("play_rejected", {
2534
+ context: context,
2535
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2536
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2537
+ });
2538
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2539
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2540
+ originalMutedState = true;
2541
+ forcedMuteByAutoplay = true;
2542
+ adVideoElement.muted = true;
2543
+ startAdPlayback(context, true);
2544
+ return;
2545
+ }
2546
+ failAdPlayback(context, error);
2220
2547
  }).finally(function() {
2221
2548
  if (pendingPlayPromise === playPromise) {
2222
2549
  pendingPlayPromise = void 0;
@@ -2255,17 +2582,109 @@ function createHlsAdPlayer(contentVideo, options) {
2255
2582
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2256
2583
  adVideoElement.muted = originalMutedState;
2257
2584
  }
2585
+ function clearMediaStartTimer() {
2586
+ if (mediaStartTimerId !== void 0) {
2587
+ clearTimeout(mediaStartTimerId);
2588
+ mediaStartTimerId = void 0;
2589
+ }
2590
+ }
2591
+ function startMediaStartTimer() {
2592
+ clearMediaStartTimer();
2593
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2594
+ var startedAt = Date.now();
2595
+ mediaStartTimerId = setTimeout(function() {
2596
+ mediaStartTimerId = void 0;
2597
+ if (!adPlaying || trackingFired.impression) return;
2598
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2599
+ logFunnel("play_resolved_but_never_started", {
2600
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2601
+ elapsedMs: Date.now() - startedAt,
2602
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2603
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2604
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2605
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2606
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2607
+ });
2608
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2609
+ }, MEDIA_START_TIMEOUT_MS);
2610
+ }
2611
+ function resetVideoElementForNextSource() {
2612
+ clearStallWatchdog();
2613
+ if (requiresMediaPipelineResetAfterAds()) {
2614
+ recreateAdVideoElement();
2615
+ setupAdEventListeners();
2616
+ } else {
2617
+ prepareVideoElementForNewSource();
2618
+ }
2619
+ }
2620
+ function tryNextMediaCandidate() {
2621
+ if (!currentAd || trackingFired.impression) return false;
2622
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2623
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2624
+ mediaCandidateIndex++;
2625
+ var next = mediaCandidates[mediaCandidateIndex];
2626
+ if (!next) return false;
2627
+ logFunnel("media_fallback", {
2628
+ failedUrl: failedUrl,
2629
+ nextUrl: next.url,
2630
+ nextType: next.type,
2631
+ candidateIndex: mediaCandidateIndex,
2632
+ candidateCount: mediaCandidates.length
2633
+ });
2634
+ resetVideoElementForNextSource();
2635
+ try {
2636
+ loadMediaCandidate(next);
2637
+ return true;
2638
+ } catch (error) {
2639
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2640
+ return tryNextMediaCandidate();
2641
+ }
2642
+ }
2643
+ function recoverFromAdFailure(vastErrorCode) {
2644
+ clearMediaStartTimer();
2645
+ if (tryNextMediaCandidate()) return;
2646
+ reportCurrentAdError(vastErrorCode);
2647
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2648
+ handleAdError();
2649
+ }
2258
2650
  function loadCurrentAdMedia() {
2259
2651
  if (!adVideoElement || !currentAd) {
2260
2652
  throw new Error("No ad video element or ad to load");
2261
2653
  }
2262
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2654
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2655
+ mediaCandidateIndex = 0;
2656
+ var mediaFile = mediaCandidates[0];
2263
2657
  if (!mediaFile) {
2264
- throw new Error("No media file available for ad");
2658
+ logFunnel("media_unsupported", {
2659
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2660
+ candidates: currentAd.mediaFiles.length
2661
+ });
2662
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2663
+ throw new Error("No media file this browser can play");
2664
+ }
2665
+ try {
2666
+ loadMediaCandidate(mediaFile);
2667
+ } catch (error) {
2668
+ if (tryNextMediaCandidate()) return;
2669
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2670
+ throw error;
2671
+ }
2672
+ }
2673
+ function loadMediaCandidate(mediaFile) {
2674
+ if (!adVideoElement || !currentAd) {
2675
+ throw new Error("No ad video element or ad to load");
2265
2676
  }
2266
2677
  currentAdMediaFile = mediaFile;
2267
2678
  var isHlsAd = isHlsMediaFile(mediaFile);
2679
+ logFunnel("media_selected", {
2680
+ width: mediaFile.width,
2681
+ height: mediaFile.height,
2682
+ bitrate: mediaFile.bitrate,
2683
+ candidateIndex: mediaCandidateIndex,
2684
+ candidates: mediaCandidates.length
2685
+ });
2268
2686
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2687
+ startMediaStartTimer();
2269
2688
  if (isHlsAd && import_hls.default.isSupported()) {
2270
2689
  if (adHls) {
2271
2690
  adHls.destroy();
@@ -2274,6 +2693,9 @@ function createHlsAdPlayer(contentVideo, options) {
2274
2693
  enableWorker: true,
2275
2694
  lowLatencyMode: false
2276
2695
  });
2696
+ logFunnel("media_load", {
2697
+ pipeline: "hls.js"
2698
+ });
2277
2699
  adHls.loadSource(mediaFile.url);
2278
2700
  adHls.attachMedia(adVideoElement);
2279
2701
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2283,10 +2705,24 @@ function createHlsAdPlayer(contentVideo, options) {
2283
2705
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2284
2706
  console.error("[HlsAdPlayer] HLS error:", data);
2285
2707
  if (data.fatal) {
2286
- handleAdError();
2708
+ var _data_response, _data_response1, _data_frag;
2709
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2710
+ logFunnel("hls_fatal", {
2711
+ reason: data.details,
2712
+ errorName: data.type,
2713
+ errorMessage: data.details,
2714
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2715
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2716
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2717
+ vastErrorCode: vastErrorCode
2718
+ });
2719
+ recoverFromAdFailure(vastErrorCode);
2287
2720
  }
2288
2721
  });
2289
2722
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2723
+ logFunnel("media_load", {
2724
+ pipeline: "native-hls"
2725
+ });
2290
2726
  adVideoElement.src = mediaFile.url;
2291
2727
  startAdPlayback("native HLS ad playback");
2292
2728
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2294,45 +2730,47 @@ function createHlsAdPlayer(contentVideo, options) {
2294
2730
  adHls.destroy();
2295
2731
  adHls = void 0;
2296
2732
  }
2733
+ logFunnel("media_load", {
2734
+ pipeline: "progressive"
2735
+ });
2297
2736
  adVideoElement.src = mediaFile.url;
2298
2737
  adVideoElement.load();
2299
2738
  startAdPlayback("progressive ad playback");
2300
2739
  } else {
2740
+ clearMediaStartTimer();
2741
+ logFunnel("media_unsupported", {
2742
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2743
+ });
2301
2744
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2302
2745
  }
2303
2746
  }
2304
2747
  function advanceToNextPodAd() {
2305
- if (podIndex >= podAds.length - 1) {
2306
- return false;
2307
- }
2308
- settleViewability();
2309
- podIndex++;
2310
- currentAd = podAds[podIndex];
2311
- currentAdMediaFile = void 0;
2312
- resetAdTracking();
2313
- if (currentAd) {
2314
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2315
- }
2316
- clearStallWatchdog();
2317
- if (requiresMediaPipelineResetAfterAds()) {
2318
- recreateAdVideoElement();
2319
- setupAdEventListeners();
2320
- } else {
2321
- prepareVideoElementForNewSource();
2322
- }
2323
- try {
2324
- loadCurrentAdMedia();
2325
- emit("pod_ad_started", {
2326
- index: podIndex,
2327
- total: podAds.length
2328
- });
2329
- return true;
2330
- } catch (error) {
2331
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2332
- return false;
2748
+ clearMediaStartTimer();
2749
+ while(podIndex < podAds.length - 1){
2750
+ settleViewability();
2751
+ podIndex++;
2752
+ currentAd = podAds[podIndex];
2753
+ currentAdMediaFile = void 0;
2754
+ resetAdTracking();
2755
+ if (currentAd) {
2756
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2757
+ }
2758
+ resetVideoElementForNextSource();
2759
+ try {
2760
+ loadCurrentAdMedia();
2761
+ emit("pod_ad_started", {
2762
+ index: podIndex,
2763
+ total: podAds.length
2764
+ });
2765
+ return true;
2766
+ } catch (error) {
2767
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2768
+ }
2333
2769
  }
2770
+ return false;
2334
2771
  }
2335
2772
  function clearStallWatchdog() {
2773
+ clearMediaStartTimer();
2336
2774
  if (stallWatchdogId != null) {
2337
2775
  clearInterval(stallWatchdogId);
2338
2776
  stallWatchdogId = void 0;
@@ -2348,11 +2786,10 @@ function createHlsAdPlayer(contentVideo, options) {
2348
2786
  function handleAdStall() {
2349
2787
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2350
2788
  clearStallWatchdog();
2351
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2352
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2353
- return;
2354
- }
2355
- handleAdError();
2789
+ logFunnel("stall", {
2790
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2791
+ });
2792
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2356
2793
  }
2357
2794
  function getDecodedVideoFrameCount(video) {
2358
2795
  try {
@@ -2414,11 +2851,10 @@ function createHlsAdPlayer(contentVideo, options) {
2414
2851
  function handleVideoDecodeFailure() {
2415
2852
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2416
2853
  clearStallWatchdog();
2417
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2418
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2419
- return;
2420
- }
2421
- handleAdError();
2854
+ logFunnel("decode_failure", {
2855
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2856
+ });
2857
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2422
2858
  }
2423
2859
  function startStallWatchdog() {
2424
2860
  clearStallWatchdog();
@@ -2542,6 +2978,15 @@ function createHlsAdPlayer(contentVideo, options) {
2542
2978
  Promise.reject(new Error("Ad already playing"))
2543
2979
  ];
2544
2980
  }
2981
+ if (destroyed) {
2982
+ return [
2983
+ 2,
2984
+ Promise.reject(new Error("Ad player destroyed"))
2985
+ ];
2986
+ }
2987
+ currentVastTagUrl = vastTagUrl;
2988
+ pendingRequestAbortReason = void 0;
2989
+ logFunnel("request_sent");
2545
2990
  _state.label = 1;
2546
2991
  case 1:
2547
2992
  _state.trys.push([
@@ -2576,8 +3021,18 @@ function createHlsAdPlayer(contentVideo, options) {
2576
3021
  ads = _state.sent();
2577
3022
  _state.label = 4;
2578
3023
  case 4:
3024
+ if (destroyed) {
3025
+ return [
3026
+ 2,
3027
+ Promise.reject(new Error("Ad player destroyed"))
3028
+ ];
3029
+ }
3030
+ if (!ads.length && pendingRequestAbortReason) {
3031
+ throw new Error(pendingRequestAbortReason);
3032
+ }
2579
3033
  if (!ads.length) {
2580
3034
  console.warn("[HlsAdPlayer] No ads available from VAST response");
3035
+ logFunnel("no_fill");
2581
3036
  emit("ad_error");
2582
3037
  return [
2583
3038
  2,
@@ -2588,6 +3043,23 @@ function createHlsAdPlayer(contentVideo, options) {
2588
3043
  podIndex = 0;
2589
3044
  currentAd = ads[0];
2590
3045
  currentAdMediaFile = void 0;
3046
+ logFunnel("vast_received", {
3047
+ adCount: ads.length,
3048
+ durations: ads.map(function(ad) {
3049
+ return ad.duration;
3050
+ }),
3051
+ impressionUrls: ads.map(function(ad) {
3052
+ return ad.trackingUrls.impression.length;
3053
+ })
3054
+ });
3055
+ ads.forEach(function(ad, index) {
3056
+ if (ad.trackingUrls.impression.length === 0) {
3057
+ logFunnel("vast_missing_impression", {
3058
+ adIndex: index,
3059
+ missingAdId: ad.id
3060
+ });
3061
+ }
3062
+ });
2591
3063
  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"));
2592
3064
  return [
2593
3065
  2,
@@ -2596,6 +3068,9 @@ function createHlsAdPlayer(contentVideo, options) {
2596
3068
  case 5:
2597
3069
  error = _state.sent();
2598
3070
  console.error("[HlsAdPlayer] Error requesting ads:", error);
3071
+ logFunnel("request_failed", {
3072
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3073
+ });
2599
3074
  emit("ad_error");
2600
3075
  return [
2601
3076
  2,
@@ -2651,13 +3126,22 @@ function createHlsAdPlayer(contentVideo, options) {
2651
3126
  adContainerEl.style.pointerEvents = "auto";
2652
3127
  }
2653
3128
  emit("content_pause");
2654
- loadCurrentAdMedia();
3129
+ try {
3130
+ loadCurrentAdMedia();
3131
+ } catch (loadError) {
3132
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3133
+ throw loadError;
3134
+ }
3135
+ }
2655
3136
  return [
2656
3137
  2,
2657
3138
  Promise.resolve()
2658
3139
  ];
2659
3140
  } catch (error) {
2660
3141
  console.error("[HlsAdPlayer] Error playing ad:", error);
3142
+ logFunnel("play_failed", {
3143
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3144
+ });
2661
3145
  handleAdError();
2662
3146
  return [
2663
3147
  2,
@@ -2699,6 +3183,9 @@ function createHlsAdPlayer(contentVideo, options) {
2699
3183
  var previousMutedState;
2700
3184
  return _ts_generator(this, function(_state) {
2701
3185
  console.log("[HlsAdPlayer] Stopping ad");
3186
+ if (adPlaying && currentAd && !trackingFired.impression) {
3187
+ logFunnel("stopped_before_start");
3188
+ }
2702
3189
  settleViewability();
2703
3190
  fireNotUsedForUnplayedAds();
2704
3191
  clearStallWatchdog();
@@ -2731,15 +3218,18 @@ function createHlsAdPlayer(contentVideo, options) {
2731
3218
  },
2732
3219
  destroy: function destroy() {
2733
3220
  console.log("[HlsAdPlayer] Destroying");
3221
+ if (adPlaying && currentAd && !trackingFired.impression) {
3222
+ logFunnel("stopped_before_start");
3223
+ }
2734
3224
  settleViewability();
2735
3225
  fireNotUsedForUnplayedAds();
2736
3226
  destroyed = true;
2737
- clearStallWatchdog();
3227
+ pendingRequestAbortReason = "Ad player destroyed";
2738
3228
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2739
3229
  try {
2740
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2741
- var timeoutId = _step.value;
2742
- clearTimeout(timeoutId);
3230
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3231
+ var controller = _step.value;
3232
+ controller.abort();
2743
3233
  }
2744
3234
  } catch (err) {
2745
3235
  _didIteratorError = true;
@@ -2755,6 +3245,28 @@ function createHlsAdPlayer(contentVideo, options) {
2755
3245
  }
2756
3246
  }
2757
3247
  }
3248
+ pendingVastRequests.clear();
3249
+ clearStallWatchdog();
3250
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3251
+ try {
3252
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3253
+ var timeoutId = _step1.value;
3254
+ clearTimeout(timeoutId);
3255
+ }
3256
+ } catch (err) {
3257
+ _didIteratorError1 = true;
3258
+ _iteratorError1 = err;
3259
+ } finally{
3260
+ try {
3261
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3262
+ _iterator1.return();
3263
+ }
3264
+ } finally{
3265
+ if (_didIteratorError1) {
3266
+ throw _iteratorError1;
3267
+ }
3268
+ }
3269
+ }
2758
3270
  pendingTimeouts = [];
2759
3271
  adPlaying = false;
2760
3272
  setAdPlayingFlag(false);
@@ -2774,6 +3286,35 @@ function createHlsAdPlayer(contentVideo, options) {
2774
3286
  isAdPlaying: function isAdPlaying() {
2775
3287
  return adPlaying;
2776
3288
  },
3289
+ setFunnelContext: function setFunnelContext(context) {
3290
+ funnelContext = _object_spread({}, context);
3291
+ },
3292
+ abortPendingRequest: function abortPendingRequest() {
3293
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3294
+ if (pendingVastRequests.size === 0) return;
3295
+ pendingRequestAbortReason = reason;
3296
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3297
+ try {
3298
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3299
+ var controller = _step.value;
3300
+ controller.abort();
3301
+ }
3302
+ } catch (err) {
3303
+ _didIteratorError = true;
3304
+ _iteratorError = err;
3305
+ } finally{
3306
+ try {
3307
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3308
+ _iterator.return();
3309
+ }
3310
+ } finally{
3311
+ if (_didIteratorError) {
3312
+ throw _iteratorError;
3313
+ }
3314
+ }
3315
+ }
3316
+ pendingVastRequests.clear();
3317
+ },
2777
3318
  resize: function resize(width, height) {
2778
3319
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2779
3320
  if (adContainerEl) {
@@ -2809,6 +3350,13 @@ function createHlsAdPlayer(contentVideo, options) {
2809
3350
  if (adVideoElement && adPlaying) {
2810
3351
  var clamped = Math.max(0, Math.min(1, volume));
2811
3352
  adVideoElement.volume = clamped;
3353
+ var userActivation = navigator.userActivation;
3354
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3355
+ logFunnel("unmute_blocked_without_gesture", {
3356
+ requestedVolume: clamped
3357
+ });
3358
+ return;
3359
+ }
2812
3360
  adVideoElement.muted = clamped === 0;
2813
3361
  }
2814
3362
  },
@@ -6872,7 +7420,7 @@ var AdTimingService = /*#__PURE__*/ function() {
6872
7420
  {
6873
7421
  key: "adFitsRemainingBudget",
6874
7422
  value: function adFitsRemainingBudget(durationMs) {
6875
- if (durationMs <= 0) {
7423
+ if (durationMs <= 0 || this.expectedAdBreakDurationMs == null) {
6876
7424
  return true;
6877
7425
  }
6878
7426
  return durationMs <= this.getDurationBudgetRemainingMs();
@@ -6931,6 +7479,11 @@ var AdTimingService = /*#__PURE__*/ function() {
6931
7479
  value: function markAdStarted() {
6932
7480
  this.currentAdIndex++;
6933
7481
  this.totalAdsInBreak = this.currentAdIndex;
7482
+ }
7483
+ },
7484
+ {
7485
+ key: "noteAdRequestSent",
7486
+ value: function noteAdRequestSent() {
6934
7487
  this.totalAdRequestsInBreak++;
6935
7488
  this.lastAdRequestTime = Date.now();
6936
7489
  }
@@ -6982,6 +7535,9 @@ var AdTimingService = /*#__PURE__*/ function() {
6982
7535
  if (message.includes("timeout")) {
6983
7536
  return true;
6984
7537
  }
7538
+ if (message.includes("ad player destroyed") || message.includes("aborted")) {
7539
+ return true;
7540
+ }
6985
7541
  if (message.includes("rate limit") || message.includes("too many requests")) {
6986
7542
  return true;
6987
7543
  }
@@ -8115,6 +8671,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8115
8671
  this.adDetectSentForCurrentBreak = false;
8116
8672
  this.continuousFetchingActive = false;
8117
8673
  this.continuousFetchLoopRunning = false;
8674
+ this.breakFunnel = {};
8675
+ this.controllerCallInFlight = false;
8676
+ this.playbackStartedForCurrentRequest = false;
8677
+ this.opportunityEpoch = -1;
8118
8678
  this.adRequestQueue = [];
8119
8679
  this.adPodQueue = [];
8120
8680
  this.maxPlaceholderDurationMs = 5e3;
@@ -8167,7 +8727,25 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8167
8727
  adPlayer.on("ad_interaction", function(event) {
8168
8728
  if (event) _this.host.onAdInteraction(event);
8169
8729
  });
8730
+ adPlayer.on("ad_funnel", function(payload) {
8731
+ if (!(payload === null || payload === void 0 ? void 0 : payload.stage)) return;
8732
+ _this.countFunnelStage(payload.stage);
8733
+ if (payload.reason) {
8734
+ _this.countFunnelStage("".concat(payload.stage, ":").concat(payload.reason));
8735
+ }
8736
+ if (payload.stage === "impression_fired" && payload.pixelCount != null) {
8737
+ _this.countFunnelStage("impression_urls", payload.pixelCount);
8738
+ }
8739
+ if (payload.visibilityState === "hidden") {
8740
+ _this.countFunnelStage("while_hidden");
8741
+ }
8742
+ });
8170
8743
  adPlayer.on("ad_impression", function() {
8744
+ _this.timing.consecutiveFailures = 0;
8745
+ if (!_this.playbackStartedForCurrentRequest) {
8746
+ _this.playbackStartedForCurrentRequest = true;
8747
+ _this.timing.markAdStarted();
8748
+ }
8171
8749
  sendAdImpressionTracking(_this.host.config.licenseKey, _object_spread_props(_object_spread({
8172
8750
  source: "hls",
8173
8751
  adIndex: _this.timing.currentAdIndex
@@ -8211,6 +8789,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8211
8789
  }
8212
8790
  }
8213
8791
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
8792
+ if (_this.controllerCallInFlight) {
8793
+ _this.timing.recordGamNoFill();
8794
+ return;
8795
+ }
8214
8796
  _this.handleAdFailure();
8215
8797
  });
8216
8798
  adPlayer.on("content_pause", function() {
@@ -8282,6 +8864,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8282
8864
  }
8283
8865
  var preservedMutedState = adPlayer.getOriginalMutedState();
8284
8866
  var preservedVolumeState = adPlayer.getOriginalVolume();
8867
+ this.playbackStartedForCurrentRequest = false;
8285
8868
  if (adPlayer) {
8286
8869
  try {
8287
8870
  adPlayer.destroy();
@@ -8371,9 +8954,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8371
8954
  if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {
8372
8955
  this.timing.expectedAdBreakDurationMs = adBreakDurationMs;
8373
8956
  }
8957
+ this.noteOpportunity("scte35", this.cueManager.activeScte35BreakKey);
8374
8958
  return [
8375
8959
  4,
8376
- this.startOptimizedPod(baseVastUrl, adBreakDurationMs, currentMuted, currentVolume)
8960
+ this.startOptimizedPod(baseVastUrl, adBreakDurationMs)
8377
8961
  ];
8378
8962
  case 1:
8379
8963
  podPlayed = _state.sent();
@@ -8407,7 +8991,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8407
8991
  value: // ───────────────────────────────────────────────────────────────
8408
8992
  // Optimized pod (single multi-ad request)
8409
8993
  // ───────────────────────────────────────────────────────────────
8410
- function startOptimizedPod(baseVastUrl, breakDurationMs, currentMuted, currentVolume) {
8994
+ function startOptimizedPod(baseVastUrl, breakDurationMs) {
8411
8995
  return _async_to_generator(function() {
8412
8996
  var podUrl, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
8413
8997
  return _ts_generator(this, function(_state) {
@@ -8446,10 +9030,13 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8446
9030
  case 2:
8447
9031
  _state.sent();
8448
9032
  this.timing.startAdRequestWatchdog(requestToken);
8449
- this.timing.lastAdRequestTime = Date.now();
9033
+ this.timing.noteAdRequestSent();
9034
+ this.beginFunnelRequest(adPlayer, requestToken);
8450
9035
  return [
8451
9036
  4,
8452
- adPlayer.requestAds(podUrl)
9037
+ this.callController(function() {
9038
+ return adPlayer.requestAds(podUrl);
9039
+ })
8453
9040
  ];
8454
9041
  case 3:
8455
9042
  _state.sent();
@@ -8478,16 +9065,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8478
9065
  this.timing.startAdFailsafeTimer(requestToken);
8479
9066
  return [
8480
9067
  4,
8481
- adPlayer.play()
9068
+ this.callController(function() {
9069
+ return adPlayer.play();
9070
+ })
8482
9071
  ];
8483
9072
  case 4:
8484
9073
  _state.sent();
8485
- this.timing.markAdStarted();
8486
9074
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
8487
9075
  this.timing.scheduleAdStopAtBreakBoundary();
8488
9076
  }
8489
- adPlayer.setAdVolume(currentMuted ? 0 : currentVolume);
8490
- this.timing.consecutiveFailures = 0;
9077
+ adPlayer.setAdVolume(getAdAudioVolume(adPlayer));
8491
9078
  this.continuousFetchingActive = true;
8492
9079
  this.startContinuousFetching(baseVastUrl);
8493
9080
  return [
@@ -8852,7 +9439,6 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8852
9439
  ];
8853
9440
  case 3:
8854
9441
  _state.sent();
8855
- this.timing.consecutiveFailures = 0;
8856
9442
  return [
8857
9443
  3,
8858
9444
  8
@@ -8865,6 +9451,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8865
9451
  3,
8866
9452
  6
8867
9453
  ];
9454
+ this.timing.consecutiveFailures++;
8868
9455
  return [
8869
9456
  4,
8870
9457
  this.tryNextAvailableAdWithRateLimit()
@@ -8956,11 +9543,137 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8956
9543
  }
8957
9544
  }
8958
9545
  },
9546
+ {
9547
+ key: "countFunnelStage",
9548
+ value: function countFunnelStage(stage) {
9549
+ var amount = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1;
9550
+ var _this_breakFunnel_stage;
9551
+ this.breakFunnel[stage] = ((_this_breakFunnel_stage = this.breakFunnel[stage]) !== null && _this_breakFunnel_stage !== void 0 ? _this_breakFunnel_stage : 0) + amount;
9552
+ }
9553
+ },
9554
+ {
9555
+ key: "logOrchestratorFunnel",
9556
+ value: function logOrchestratorFunnel(stage) {
9557
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
9558
+ this.countFunnelStage(stage);
9559
+ console.log("[AdBreak][FUNNEL] ".concat(stage), _object_spread({
9560
+ breakId: this.timing.adBreakEpoch,
9561
+ requestId: this.currentRequestId,
9562
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0
9563
+ }, extra));
9564
+ }
9565
+ },
9566
+ {
9567
+ key: "noteOpportunity",
9568
+ value: function noteOpportunity(source, breakKey) {
9569
+ if (breakKey && breakKey === this.opportunityBreakKey && this.opportunityEpoch === this.timing.adBreakEpoch) {
9570
+ this.logOrchestratorFunnel("duplicate_break_start", {
9571
+ source: source,
9572
+ breakKey: breakKey
9573
+ });
9574
+ return;
9575
+ }
9576
+ this.opportunityBreakKey = breakKey;
9577
+ this.opportunityEpoch = this.timing.adBreakEpoch;
9578
+ this.logOrchestratorFunnel("opportunity_created", {
9579
+ source: source,
9580
+ breakKey: breakKey,
9581
+ expectedDurationMs: this.timing.expectedAdBreakDurationMs
9582
+ });
9583
+ }
9584
+ },
9585
+ {
9586
+ key: "beginFunnelRequest",
9587
+ value: function beginFunnelRequest(adPlayer, requestToken) {
9588
+ var _adPlayer_setFunnelContext;
9589
+ if (this.controllerCallInFlight) {
9590
+ this.logOrchestratorFunnel("duplicate_request_detected", {
9591
+ newRequestId: requestToken
9592
+ });
9593
+ }
9594
+ this.currentRequestId = requestToken;
9595
+ this.requestStartedAt = Date.now();
9596
+ (_adPlayer_setFunnelContext = adPlayer.setFunnelContext) === null || _adPlayer_setFunnelContext === void 0 ? void 0 : _adPlayer_setFunnelContext.call(adPlayer, {
9597
+ breakId: this.timing.adBreakEpoch,
9598
+ requestId: requestToken
9599
+ });
9600
+ }
9601
+ },
9602
+ {
9603
+ key: "isAdLoadingWithoutPlayback",
9604
+ value: function isAdLoadingWithoutPlayback() {
9605
+ return this.host.getAdPlayer().isAdPlaying() && !this.playbackStartedForCurrentRequest;
9606
+ }
9607
+ },
9608
+ {
9609
+ key: "noteStopBeforeStart",
9610
+ value: function noteStopBeforeStart(reason) {
9611
+ if (!this.isAdLoadingWithoutPlayback()) return;
9612
+ this.logOrchestratorFunnel("ad_stopped_before_start", {
9613
+ reason: reason,
9614
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9615
+ });
9616
+ }
9617
+ },
9618
+ {
9619
+ key: "handleRequestWatchdogTimeout",
9620
+ value: function handleRequestWatchdogTimeout() {
9621
+ var adPlayer = this.host.getAdPlayer();
9622
+ if (this.controllerCallInFlight && adPlayer.abortPendingRequest) {
9623
+ this.logOrchestratorFunnel("request_aborted_timeout", {
9624
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9625
+ });
9626
+ adPlayer.abortPendingRequest("VAST request aborted after request watchdog timeout");
9627
+ return;
9628
+ }
9629
+ this.handleAdFailure();
9630
+ }
9631
+ },
9632
+ {
9633
+ key: "callController",
9634
+ value: function callController(call) {
9635
+ return _async_to_generator(function() {
9636
+ return _ts_generator(this, function(_state) {
9637
+ switch(_state.label){
9638
+ case 0:
9639
+ this.controllerCallInFlight = true;
9640
+ _state.label = 1;
9641
+ case 1:
9642
+ _state.trys.push([
9643
+ 1,
9644
+ ,
9645
+ 3,
9646
+ 4
9647
+ ]);
9648
+ return [
9649
+ 4,
9650
+ call()
9651
+ ];
9652
+ case 2:
9653
+ _state.sent();
9654
+ return [
9655
+ 3,
9656
+ 4
9657
+ ];
9658
+ case 3:
9659
+ this.controllerCallInFlight = false;
9660
+ return [
9661
+ 7
9662
+ ];
9663
+ case 4:
9664
+ return [
9665
+ 2
9666
+ ];
9667
+ }
9668
+ });
9669
+ }).call(this);
9670
+ }
9671
+ },
8959
9672
  {
8960
9673
  key: "playSingleAd",
8961
9674
  value: function playSingleAd(vastTagUrl) {
8962
9675
  return _async_to_generator(function() {
8963
- var adPlayer, requestToken, ap, requestUrl, playError, error, errorMessage;
9676
+ var adPlayer, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, playError, error, errorMessage;
8964
9677
  return _ts_generator(this, function(_state) {
8965
9678
  switch(_state.label){
8966
9679
  case 0:
@@ -9002,13 +9715,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9002
9715
  case 2:
9003
9716
  _state.sent();
9004
9717
  this.timing.startAdRequestWatchdog(requestToken);
9005
- this.timing.lastAdRequestTime = Date.now();
9718
+ this.timing.noteAdRequestSent();
9006
9719
  ap = this.host.getAdPlayer();
9007
9720
  requestUrl = this.withCurrentPodBudget(vastTagUrl);
9008
9721
  this.currentVastUrl = requestUrl;
9722
+ this.beginFunnelRequest(ap, requestToken);
9009
9723
  return [
9010
9724
  4,
9011
- ap.requestAds(requestUrl)
9725
+ this.callController(function() {
9726
+ return ap.requestAds(requestUrl);
9727
+ })
9012
9728
  ];
9013
9729
  case 3:
9014
9730
  _state.sent();
@@ -9022,6 +9738,14 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9022
9738
  2
9023
9739
  ];
9024
9740
  if (!this.timing.ensureLoadedAdFitsBudget(ap)) {
9741
+ ;
9742
+ adDurationS = (_ap_getLoadedAdDuration = ap.getLoadedAdDuration) === null || _ap_getLoadedAdDuration === void 0 ? void 0 : _ap_getLoadedAdDuration.call(ap);
9743
+ remainingMs = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
9744
+ this.logOrchestratorFunnel("discarded_budget", {
9745
+ vastUrl: requestUrl,
9746
+ adDurationMs: adDurationS != null ? adDurationS * 1e3 : void 0,
9747
+ remainingMs: remainingMs
9748
+ });
9025
9749
  this.timing.rejectLoadedAdForDuration(ap);
9026
9750
  this.recreateAdController();
9027
9751
  throw new Error("ad_duration_exceeds_budget");
@@ -9037,16 +9761,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9037
9761
  this.timing.startAdFailsafeTimer(requestToken);
9038
9762
  return [
9039
9763
  4,
9040
- ap.play()
9764
+ this.callController(function() {
9765
+ return ap.play();
9766
+ })
9041
9767
  ];
9042
9768
  case 5:
9043
9769
  _state.sent();
9044
- this.timing.markAdStarted();
9045
9770
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
9046
9771
  this.timing.scheduleAdStopAtBreakBoundary();
9047
9772
  }
9048
9773
  ap.setAdVolume(getAdAudioVolume(ap));
9049
- this.timing.consecutiveFailures = 0;
9050
9774
  this.timing.temporaryFailureUrls.delete(vastTagUrl);
9051
9775
  return [
9052
9776
  3,
@@ -9210,7 +9934,6 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9210
9934
  ];
9211
9935
  case 5:
9212
9936
  _state.sent();
9213
- this.timing.consecutiveFailures = 0;
9214
9937
  return [
9215
9938
  3,
9216
9939
  10
@@ -9222,6 +9945,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9222
9945
  3,
9223
9946
  8
9224
9947
  ];
9948
+ this.timing.consecutiveFailures++;
9225
9949
  return [
9226
9950
  4,
9227
9951
  this.tryNextAvailableAdWithRateLimit()
@@ -9272,6 +9996,67 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9272
9996
  // ───────────────────────────────────────────────────────────────
9273
9997
  // Ad break completion
9274
9998
  // ───────────────────────────────────────────────────────────────
9999
+ key: "logBreakFunnel",
10000
+ value: function logBreakFunnel() {
10001
+ var funnel = this.breakFunnel;
10002
+ this.breakFunnel = {};
10003
+ if (Object.keys(funnel).length === 0) return;
10004
+ var count = function count(stage) {
10005
+ var _funnel_stage;
10006
+ return (_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0;
10007
+ };
10008
+ var breakId = this.opportunityEpoch;
10009
+ if (count("request_sent") > 0 && count("impression_fired") === 0) {
10010
+ console.log("[AdBreak][FUNNEL] break_abandoned_before_start", {
10011
+ breakId: breakId,
10012
+ requests: count("request_sent")
10013
+ });
10014
+ }
10015
+ console.log("[AdBreak][FUNNEL] Break summary", {
10016
+ breakId: breakId,
10017
+ opportunities: count("opportunity_created"),
10018
+ requests: count("request_sent"),
10019
+ duplicates: count("duplicate_request_detected") + count("duplicate_break_start"),
10020
+ filled: count("vast_received"),
10021
+ noFill: count("no_fill"),
10022
+ requestFailed: count("request_failed"),
10023
+ requestAbortedTimeout: count("request_aborted_timeout"),
10024
+ credentialsRetries: count("vast_credentials_retry"),
10025
+ wrapperFailures: count("wrapper_fetch:failure"),
10026
+ noSupportedMedia: count("vast_no_supported_media"),
10027
+ vpaidOnly: count("vast_no_supported_media:vpaid_only"),
10028
+ missingImpression: count("vast_missing_impression"),
10029
+ discardedBudget: count("discarded_budget"),
10030
+ mediaCandidates: count("media_candidate:accepted") + count("media_candidate:rejected"),
10031
+ mediaRejected: count("media_candidate:rejected"),
10032
+ mediaFallbacks: count("media_fallback"),
10033
+ playCalled: count("play_called"),
10034
+ playRejected: count("play_rejected"),
10035
+ mutedRetry: count("muted_retry"),
10036
+ startTimeouts: count("play_resolved_but_never_started"),
10037
+ impressions: count("impression_fired"),
10038
+ impressionUrls: count("impression_urls"),
10039
+ trackingRequests: count("tracking_request_created"),
10040
+ trackingNotLoaded: count("tracking_request_settled:error") + count("tracking_request_settled:timeout"),
10041
+ trackingUnexpandedMacros: count("tracking_url_unexpanded_macro"),
10042
+ trackingInvalidUrls: count("tracking_url_invalid"),
10043
+ vastAdFallbacks: count("vast_ad_fallback"),
10044
+ mediaEvents: count("media_event"),
10045
+ quartile25: count("first_quartile"),
10046
+ quartile50: count("midpoint"),
10047
+ quartile75: count("third_quartile"),
10048
+ complete: count("complete"),
10049
+ stoppedBeforeStart: count("stopped_before_start"),
10050
+ stoppedBeforeStartByBreakEnd: count("ad_stopped_before_start"),
10051
+ unexpectedUnmutes: count("unexpected_unmute"),
10052
+ unmuteBlocked: count("unmute_blocked_without_gesture"),
10053
+ visibilityHidden: count("while_hidden"),
10054
+ playbackFailures: count("play_failed") + count("media_error") + count("hls_fatal") + count("stall") + count("decode_failure") + count("media_unsupported"),
10055
+ stages: funnel
10056
+ });
10057
+ }
10058
+ },
10059
+ {
9275
10060
  key: "handleAdPodComplete",
9276
10061
  value: function handleAdPodComplete() {
9277
10062
  if (this.debug) {
@@ -9292,6 +10077,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9292
10077
  this.adPodQueue = [];
9293
10078
  this.showAds = false;
9294
10079
  this.host.getAdPlayer().stop().catch(function() {});
10080
+ this.logBreakFunnel();
9295
10081
  var restoredMuted = this.host.getAdPlayer().getOriginalMutedState();
9296
10082
  var restoredVolume = this.host.getAdPlayer().getOriginalVolume();
9297
10083
  if (this.host.video.muted !== restoredMuted) {
@@ -9643,7 +10429,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9643
10429
  _this.startScte35AdBreak(marker, cueKey, marker.durationSeconds != null ? marker.durationSeconds * 1e3 : _this.timing.expectedAdBreakDurationMs);
9644
10430
  },
9645
10431
  onWatchdogTimeout: function onWatchdogTimeout() {
9646
- return _this.adBreak.handleAdFailure();
10432
+ return _this.adBreak.handleRequestWatchdogTimeout();
9647
10433
  },
9648
10434
  onFailsafeTimeout: function onFailsafeTimeout() {
9649
10435
  return _this.adBreak.handleAdFailure();
@@ -9748,6 +10534,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9748
10534
  licenseKey: this.config.licenseKey
9749
10535
  } : {}, ((_this_hlsEngine = this.hlsEngine) === null || _this_hlsEngine === void 0 ? void 0 : _this_hlsEngine.hls) ? {
9750
10536
  mainHlsInstance: this.hlsEngine.hls
10537
+ } : {}, this.config.adMediaStartTimeoutMs != null ? {
10538
+ mediaStartTimeoutMs: this.config.adMediaStartTimeoutMs
9751
10539
  } : {}));
9752
10540
  }
9753
10541
  },
@@ -10102,6 +10890,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10102
10890
  this.timing.clearAdStartTimer();
10103
10891
  this.timing.clearAdStopTimer();
10104
10892
  if (adPlaying) {
10893
+ this.adBreak.noteStopBeforeStart("scte_end");
10105
10894
  this.adPlayer.stop().catch(function() {});
10106
10895
  }
10107
10896
  this.adBreak.handleAdPodComplete();
@@ -10141,6 +10930,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10141
10930
  console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(overrunMs, "ms) - hard-stopping ads and resuming stream"));
10142
10931
  }
10143
10932
  if (adPlaying) {
10933
+ this.adBreak.noteStopBeforeStart("break_boundary");
10144
10934
  this.adPlayer.stop().catch(function() {});
10145
10935
  }
10146
10936
  this.adBreak.handleAdPodComplete();
@@ -10269,6 +11059,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10269
11059
  this.adBreak.showAds = true;
10270
11060
  this.adBreak.inAdBreak = true;
10271
11061
  this.timing.currentAdBreakStartWallClockMs = Date.now();
11062
+ if (durationMs > 0) {
11063
+ this.timing.setAdBreakDurationBoundary(durationMs);
11064
+ }
11065
+ this.adBreak.noteOpportunity("vmap", key);
10272
11066
  _state.label = 1;
10273
11067
  case 1:
10274
11068
  _state.trys.push([