m3u8parse
Version:
Structural parsing of Apple HTTP Live Streaming .m3u8 format
88 lines (87 loc) • 2.57 kB
JavaScript
import { AttrList } from "./attrlist.js";
import { PlaylistWriter } from "./writer.js";
export const cloneAttrArray = function (src) {
const dst = [];
for (const entry of src ?? []) {
dst.push(new AttrList(entry));
}
return dst;
};
class JSONableMap extends Map {
toJSON() {
const obj = Object.create(null);
for (const [key, value] of this) {
obj[key] = value;
}
return obj;
}
}
const isIterable = function (x) {
return !!x?.[Symbol.iterator];
};
export const cloneAttrMap = function (src) {
const dst = new JSONableMap();
if (src) {
if (isIterable(src)) {
for (const [key, list] of src) {
dst.set(key, list.map((attrs) => new AttrList(attrs)));
}
}
else {
for (const key in src) {
const list = src[key];
dst.set(key, list.map((attrs) => new AttrList(attrs)));
}
}
}
return dst;
};
export const isStringish = function (val) {
return !!val || val === '';
};
export const rewriteAttr = function (mapFn, attrs, type) {
if (attrs?.has('uri')) {
const newUri = mapFn(attrs.get('uri', AttrList.Types.String), type, attrs);
if (isStringish(newUri)) {
attrs.set('uri', newUri, AttrList.Types.String);
}
}
};
export const rewriteAttrs = function (mapFn, list, type) {
for (const item of list || []) {
rewriteAttr(mapFn, item, type);
}
};
export const rewriteMappedAttrs = function (mapFn, map, type) {
if (map) {
for (const list of map.values()) {
rewriteAttrs(mapFn, list, type);
}
}
};
export class BasePlaylist {
constructor(obj) {
this.master = !!obj.master;
this.version = obj.version || 1;
this.start = obj.start ? new AttrList(obj.start) : undefined;
this.independent_segments = obj.independent_segments !== undefined ? !!obj.independent_segments : undefined;
this.defines = cloneAttrArray(obj.defines);
if (obj.vendor) {
if (typeof obj.vendor[Symbol.iterator] !== 'function') {
this.vendor = Object.entries(obj.vendor);
}
else {
const set = this.vendor = [];
for (const [ext, value] of obj.vendor) {
set.push([ext, value]);
}
}
}
}
isLive() {
return false;
}
toString() {
return new PlaylistWriter(this).toString();
}
}