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