// Copyright 2024 Martin Riedl
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package gomp4

// MediaDataBox Media Data Box
//
// 8.1.1 Media Data Box
// Box Type: ‘mdat’
// Container: File
// Mandatory: No
// Quantity: Zero or more
//
// This box contains the media data. In video tracks, this box would contain video frames. A presentation
// may contain zero or more Media Data Boxes. The actual media data follows the type field; its structure
// is described by the metadata (see particularly the sample table, subclause 8.5, and the item location box,
// subclause 8.11.3).
//
// In large presentations, it may be desirable to have more data in this box than a 32‐bit size would permit.
// In this case, the large variant of the size field, above in subclause 4.2, is used.
//
// There may be any number of these boxes in the file (including zero, if all the media data is in other files).
// The metadata refers to media data by its absolute offset within the file (see subclause 8.7.5, the Chunk
// Offset Box); so Media Data Box headers and free space may easily be skipped, and files without any box
// structure may also be referenced and used.
type MediaDataBox struct {
	*Box
	ContentStartPosition uint64
	ContentEndPosition   uint64
}

// BoxTypeMediaData Media Data Box
const BoxTypeMediaData = "mdat"

func init() {
	BoxDefinitions = append(BoxDefinitions, BoxDefinition{
		Type:        BoxTypeMediaData,
		ParentTypes: []string{boxTypeParentFile},
		Parser:      ParseMediaDataBox,
	})
}

// ParseMediaDataBox creates a new media data box struct
func ParseMediaDataBox(parser *Parser, filePosition uint64, headerSize uint32, content []byte) (any, error) {
	box := &MediaDataBox{Box: &Box{filePosition, headerSize}}

	// parse positions of content
	box.ContentStartPosition = filePosition + uint64(headerSize)
	box.ContentEndPosition = box.ContentStartPosition + uint64(len(content))

	return box, nil
}
